Make HTTPS decryption opt-in with a decrypt list (#822)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Gregory SchierandClaude Opus 5.5 authored and GitHub committed 2026-11-06 21:24:39 -07:00
1 parent 91696c2d1f
commit 4538123d88
44 files changed
+3259 -66

No files matched your search

+1 -2
View File
@@ -63,8 +63,7 @@ import { isSidebarFocused } from "../lib/scopes";
import { navigateToRequestOrFolderOrWorkspace } from "../lib/setWorkspaceSearchParams";
import type { ContextMenuProps, DropdownItem } from "./core/Dropdown";
import { ContextMenu, Dropdown } from "./core/Dropdown";
import type { FieldDef } from "./core/Editor/filter/extension";
import { filter } from "./core/Editor/filter/extension";
import { type FieldDef, filter } from "@yaakapp-internal/ui/editor";
import type { Ast } from "./core/Editor/filter/query";
import { evaluate, parseQuery } from "./core/Editor/filter/query";
import { formatFieldFilter } from "./core/Editor/filter/format";
@@ -1,211 +0,0 @@
import type { Completion, CompletionContext, CompletionResult } from "@codemirror/autocomplete";
import { autocompletion, startCompletion } from "@codemirror/autocomplete";
import { LanguageSupport, LRLanguage, syntaxTree } from "@codemirror/language";
import type { SyntaxNode } from "@lezer/common";
import { parser } from "./filter";
export interface FieldDef {
name: string;
// Optional static or dynamic value suggestions for this field
values?: string[] | (() => string[]);
info?: string;
}
export interface FilterOptions {
fields: FieldDef[] | null; // e.g., ['method','status','path'] or [{name:'tag', values:()=>cachedTags}]
}
const FIELD_IDENT = /[A-Za-z0-9_/]+$/;
const VALUE_IDENT = /\S+$/;
const VALUE_IDENT_ONLY = /^\S+$/;
function normalizeFields(fields: FieldDef[]): {
fieldNames: string[];
fieldMap: Record<string, { values?: string[] | (() => string[]); info?: string }>;
} {
const fieldNames: string[] = [];
const fieldMap: Record<string, { values?: string[] | (() => string[]); info?: string }> = {};
for (const f of fields) {
fieldNames.push(f.name);
fieldMap[f.name] = { values: f.values, info: f.info };
}
return { fieldNames, fieldMap };
}
function wordBefore(
doc: string,
pos: number,
pattern: RegExp,
): { from: number; to: number; text: string } | null {
const upto = doc.slice(0, pos);
const m = upto.match(pattern);
if (!m) return null;
const from = pos - m[0].length;
return { from, to: pos, text: m[0] };
}
function fieldCompletionFrom(doc: string, pos: number): { from: number; includeAt: boolean } | null {
const w = wordBefore(doc, pos, FIELD_IDENT);
const from = w?.from ?? pos;
const beforeToken = doc[from - 1];
if (from === 0 || (beforeToken != null && /\s/.test(beforeToken))) {
return { from, includeAt: true };
}
if (beforeToken === "@") {
const beforeAt = doc[from - 2];
if (from === 1 || (beforeAt != null && /\s/.test(beforeAt))) {
return { from, includeAt: false };
}
}
return null;
}
function inPhrase(ctx: CompletionContext): boolean {
// Lezer node names from your grammar: Phrase is the quoted token
let n: SyntaxNode | null = syntaxTree(ctx.state).resolveInner(ctx.pos, -1);
while (n) {
if (n.name === "Phrase") return true;
n = n.parent;
}
return false;
}
// While typing an incomplete quote, there's no Phrase token yet.
function inUnclosedQuote(doc: string, pos: number): boolean {
let quotes = 0;
for (let i = 0; i < pos; i++) {
if (doc[i] === '"' && doc[i - 1] !== "\\") quotes++;
}
return quotes % 2 === 1; // odd = inside an open quote
}
/**
* Heuristic context detector (works without relying on exact node names):
* - If there's a ':' after the last whitespace and before the cursor, we're in a field value.
* - Otherwise, we're in a field name or bare term position.
*/
function contextInfo(stateDoc: string, pos: number) {
const lastColon = stateDoc.lastIndexOf(":", pos - 1);
const lastBoundary = Math.max(
stateDoc.lastIndexOf(" ", pos - 1),
stateDoc.lastIndexOf("\t", pos - 1),
stateDoc.lastIndexOf("\n", pos - 1),
stateDoc.lastIndexOf("(", pos - 1),
stateDoc.lastIndexOf(")", pos - 1),
);
const inValue = lastColon > lastBoundary;
let fieldName: string | null = null;
let emptyAfterColon = false;
if (inValue) {
// word before the colon = field name
const beforeColon = stateDoc.slice(0, lastColon);
const m = beforeColon.match(FIELD_IDENT);
fieldName = m ? m[0] : null;
// nothing (or only spaces) typed after the colon?
const after = stateDoc.slice(lastColon + 1, pos);
emptyAfterColon = after.length === 0 || /^\s+$/.test(after);
}
return { inValue, fieldName, lastColon, emptyAfterColon };
}
/** Build a completion list for field names */
function fieldNameCompletions(fieldNames: string[], includeAt: boolean): Completion[] {
return fieldNames.map((name) => ({
label: name,
type: "property",
apply: (view, _completion, from, to) => {
// Leave cursor right after the field filter colon.
const insert = `${includeAt ? "@" : ""}${name}:`;
view.dispatch({
changes: { from, to, insert },
selection: { anchor: from + insert.length },
});
startCompletion(view);
},
}));
}
/** Build a completion list for field values (if provided) */
function fieldValueCompletions(
def: { values?: string[] | (() => string[]); info?: string } | undefined,
): Completion[] | null {
if (!def || !def.values) return null;
const vals = Array.isArray(def.values) ? def.values : def.values();
return vals.map((v) => ({
label: v.match(VALUE_IDENT_ONLY) ? v : `"${v}"`,
displayLabel: v,
type: "constant",
}));
}
/** The main completion source */
function makeCompletionSource(opts: FilterOptions) {
const { fieldNames, fieldMap } = normalizeFields(opts.fields ?? []);
return (ctx: CompletionContext): CompletionResult | null => {
const { state, pos } = ctx;
const doc = state.doc.toString();
if (inPhrase(ctx) || inUnclosedQuote(doc, pos)) {
return null;
}
const { inValue, fieldName, emptyAfterColon } = contextInfo(doc, pos);
// In field value position
if (inValue && fieldName) {
const w = wordBefore(doc, pos, VALUE_IDENT);
const from = w?.from ?? pos;
const to = pos;
const valDefs = fieldMap[fieldName];
const vals = fieldValueCompletions(valDefs);
// If user hasn't typed a value char yet:
// - Show value suggestions if available
// - Otherwise show nothing (no fallback to field names)
if (emptyAfterColon) {
if (vals?.length) {
return { from, to, options: vals, filter: true };
}
return null; // <-- key change: do not suggest fields here
}
// User started typing a value; filter value suggestions (if any)
if (vals?.length) {
return { from, to, options: vals, filter: true };
}
// No specific values: also show nothing (keeps UI quiet)
return null;
}
// Not in a value: suggest field names (and maybe boolean ops)
const completion = fieldCompletionFrom(doc, pos);
if (completion == null) return null;
const { from, includeAt } = completion;
const to = pos;
const options: Completion[] = fieldNameCompletions(fieldNames, includeAt);
return { from, to, options, filter: true };
};
}
const language = LRLanguage.define({
name: "filter",
parser,
languageData: {
autocompletion: {},
},
});
/** Public extension */
export function filter(options: FilterOptions) {
const source = makeCompletionSource(options);
return new LanguageSupport(language, [autocompletion({ override: [source] })]);
}
@@ -1,78 +0,0 @@
@top Query { Expr }
@skip { space+ }
@tokens {
space { $[ \t\r\n]+ }
LParen { "(" }
RParen { ")" }
At { "@" }
Colon { ":" }
Not { "-" | "NOT" }
// Keywords (case-insensitive)
And { "AND" }
Or { "OR" }
// "quoted phrase" with simple escapes: \" and \\
Phrase { '"' (!["\\] | "\\" _)* '"' }
// Bare words run until filter syntax or whitespace. Leading '-' remains unary
// negation, but '-' may appear after the first character.
Word { ![ \t\r\n():"@-] ![ \t\r\n():"@]* }
FieldValueWord { ![ \t\r\n"] ![ \t\r\n]* }
@precedence { Not, And, Or, Word }
}
@detectDelim
// Precedence: NOT (highest) > AND > OR (lowest)
// We also allow implicit AND in your parser/evaluator, but for highlighting,
// this grammar parses explicit AND/OR/NOT + adjacency as a sequence (Seq).
Expr {
OrExpr
}
OrExpr {
AndExpr (Or AndExpr)*
}
AndExpr {
Unary (And Unary | Unary)* // allow implicit AND by adjacency: Unary Unary
}
Unary {
Not Unary
| Primary
}
Primary {
Group
| Field
| Phrase
| Term
}
Group {
LParen Expr RParen
}
Field {
FieldName Colon FieldValue
}
FieldName {
At? Word
}
FieldValue {
Phrase
| FieldValueWord
}
Term {
Word
}
@external propSource highlight from "./highlight"
@@ -1,42 +0,0 @@
import { describe, expect, test } from "vite-plus/test";
import { parser } from "./filter";
function getNodeNames(input: string): string[] {
const tree = parser.parse(input);
const nodes: string[] = [];
const cursor = tree.cursor();
do {
if (cursor.name !== "Query") {
nodes.push(cursor.name);
}
} while (cursor.next());
return nodes;
}
describe("filter grammar", () => {
test("parses URL-like field values as one value", () => {
const nodes = getNodeNames("@url:yaak.app/foo-bar");
expect(nodes).not.toContain("⚠");
expect(nodes).toContain("FieldValue");
expect(nodes).toContain("FieldValueWord");
});
test("parses punctuation-heavy field values as one value", () => {
const nodes = getNodeNames("@url:yaa$&#*@tsrna(*)");
expect(nodes).not.toContain("⚠");
expect(nodes).toContain("FieldValue");
expect(nodes).toContain("FieldValueWord");
});
test("parses operator-looking field values as one value", () => {
const negativeValueNodes = getNodeNames("@url:-foo");
const operatorWordNodes = getNodeNames("@url:AND");
expect(negativeValueNodes).not.toContain("⚠");
expect(negativeValueNodes).toContain("FieldValueWord");
expect(operatorWordNodes).not.toContain("⚠");
expect(operatorWordNodes).toContain("FieldValueWord");
});
});
@@ -1,22 +0,0 @@
// This file was generated by lezer-generator. You probably shouldn't edit it.
import {LRParser} from "@lezer/lr"
import {highlight} from "./highlight"
export const parser = LRParser.deserialize({
version: 14,
states: "%WOVQPOOPhOPOOOVQPO'#CfOmQPO'#ChO!_QPO'#ChO!dQPO'#CgOOQO'#Cc'#CcOVQPO'#CaOOQO'#Ca'#CaO!iQPO'#C`O!yQPO'#C_OOQO'#C^'#C^QOQPOOPOOO'#Cr'#CrP#UOPO)C>lO#]QPO,59QOOQO,59S,59SO#bQQO,59ROOQO,58{,58{OVQPO'#CsOOQO'#Cs'#CsO#jQPO,58zOVQPO'#CtO#zQPO,58yPOOO-E6p-E6pOOQO1G.l1G.lOOQO'#Cl'#ClOOQO1G.m1G.mOOQO,59_,59_OOQO-E6q-E6qOOQO,59`,59`OOQO-E6r-E6r",
stateData: "$]~OkPQ~OUVOXQO]SO^ROaUO~Ok]O~OUcXXcX]cX^cX_[XacXdcXecXicXWcX~O^`O~O_aO~OdcOeSXiSXWSX~PVOefOiRXWRX~Ok]O~Qj]WiO~OajObjO~OdcOeSaiSaWSa~PVOefOiRaWRa~OUde^e~",
goto: "#^iPPjpt{P![PP!e!e!nPPP!wPP!ePP!z#Q#WQ[OR_QTZOQSYOQRnfUXOQfQbVSdXeRlc_WOQVXcef_UOQVXcef_TOQVXcefRkaQ^PRh^QeXRmeQgYRog",
nodeNames: "⚠ Query Expr OrExpr AndExpr Unary Not Primary RParen LParen Group Field FieldName At Word Colon FieldValue Phrase FieldValueWord Term And Or",
maxTerm: 27,
nodeProps: [
["openedBy", 8,"LParen"],
["closedBy", 9,"RParen"]
],
propSources: [highlight],
skippedNodes: [0,22],
repeatNodeCount: 3,
tokenData: "2h~RiOX!pXY$hYZ$hZ]!p]^$h^p!ppq$hqr!prs$ysx!pxy&gyz'Qz}!p}!O'k!O![!p![!](U!]!b!p!b!c(o!c!d)Y!d!p!p!p!q,q!q!r0Y!r;'S!p;'S;=`$b<%lO!pR!w^bQ^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c;'S!p;'S;=`$b<%lO!pQ#xUbQOX#sZ]#s^p#sq;'S#s;'S;=`$[<%lO#sQ$_P;=`<%l#sR$eP;=`<%l!p~$mSk~XY$hYZ$h]^$hpq$h~$|VOr$yrs%cs#O$y#O#P%h#P;'S$y;'S;=`&a<%lO$y~%hOa~~%kRO;'S$y;'S;=`%t;=`O$y~%wWOr$yrs%cs#O$y#O#P%h#P;'S$y;'S;=`&a;=`<%l$y<%lO$y~&dP;=`<%l$yR&nUbQXPOX#sZ]#s^p#sq;'S#s;'S;=`$[<%lO#sR'XUbQWPOX#sZ]#s^p#sq;'S#s;'S;=`$[<%lO#sR'rUbQUPOX#sZ]#s^p#sq;'S#s;'S;=`$[<%lO#sR(]U_PbQOX#sZ]#s^p#sq;'S#s;'S;=`$[<%lO#sR(vU]PbQOX#sZ]#s^p#sq;'S#s;'S;=`$[<%lO#sR)a`bQ^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c!p!p!p!q*c!q;'S!p;'S;=`$b<%lO!pR*j`bQ^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c!f!p!f!g+l!g;'S!p;'S;=`$b<%lO!pR+u^bQdP^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c;'S!p;'S;=`$b<%lO!pR,x`bQ^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c!q!p!q!r-z!r;'S!p;'S;=`$b<%lO!pR.R`bQ^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c!v!p!v!w/T!w;'S!p;'S;=`$b<%lO!pR/^^bQUP^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c;'S!p;'S;=`$b<%lO!pR0a`bQ^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c!t!p!t!u1c!u;'S!p;'S;=`$b<%lO!pR1l^bQeP^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c;'S!p;'S;=`$b<%lO!p",
tokenizers: [0, 1],
topRules: {"Query":[0,1]},
tokenPrec: 145
})
@@ -1,22 +0,0 @@
import { styleTags, tags as t } from "@lezer/highlight";
export const highlight = styleTags({
// Boolean operators
And: t.operatorKeyword,
Or: t.operatorKeyword,
Not: t.operatorKeyword,
// Structural punctuation
LParen: t.paren,
RParen: t.paren,
Colon: t.punctuation,
Minus: t.operator,
// Literals
Phrase: t.string, // "quoted string"
// Fields
"FieldName/At": t.attributeName,
"FieldName/Word": t.attributeName,
"FieldValue/FieldValueWord": t.attributeValue,
});
@@ -0,0 +1,187 @@
import { Prec } from "@codemirror/state";
import { type EditorView, keymap } from "@codemirror/view";
import type { DecryptListEntry, SeenTargets } from "@yaakapp-internal/proxy-lib";
import { Dialog, Icon, IconButton, Input } from "@yaakapp-internal/ui";
import { filterAutocomplete } from "@yaakapp-internal/ui/editor";
import classNames from "classnames";
import { atom, useAtom } from "jotai";
import { useMemo, useRef, useState } from "react";
import { useDecryptList, useEditDecryptList } from "../hooks/useDecryptList";
import { useRpcQuery } from "../hooks/useRpcQuery";
import { decryptFilterOptions, entryLabel, normalizeEntry } from "../lib/decrypt";
/**
* What HTTPS is decrypted: one row per entry, the user's in order and then the built-in
* exclusions, each removable, and an input that adds one, suggesting `host:`, `app:` and `!`,
* then the hosts and apps seen in the capture. Saves as it changes. Placed by Settings; until
* that exists, by the dialog the state pill's More… opens.
*/
export function DecryptListEditor({ className }: { className?: string }) {
const list = useDecryptList();
const save = useEditDecryptList();
// Read when the input opens its suggestions, so new traffic shows without rebuilding it.
const seen = useRpcQuery("list_seen", {}, { staleTime: 0, refetchOnMount: "always" });
const seenRef = useRef<SeenTargets | undefined>(seen.data);
seenRef.current = seen.data;
// Each change replaces the whole list, so one waits for the last to land rather than undo it.
const remove = (entry: string) => {
if (save.isPending) return;
save.mutate({ add: [], remove: [entry] });
};
return (
<div className={classNames(className, "grid gap-2")}>
<EntryInput
seenRef={seenRef}
list={list}
disabled={save.isPending}
onAdd={(entry) => save.mutate({ add: [entry], remove: [] })}
/>
<div className="rounded-md border border-border-subtle divide-y divide-border-subtle">
{list.length === 0 && (
<div className="px-3 py-2 text-sm text-text-subtle">Nothing decrypted</div>
)}
{list.map((e) => (
<EntryRow
key={e.entry}
entry={e}
disabled={save.isPending}
onRemove={() => remove(e.entry)}
/>
))}
</div>
</div>
);
}
function EntryRow({
entry,
disabled,
onRemove,
}: {
entry: DecryptListEntry;
disabled: boolean;
onRemove: () => void;
}) {
const negated = entry.entry.startsWith("!");
return (
<div
className={classNames(
"group/entry flex items-center gap-2 h-xs pl-3 pr-1 text-sm",
entry.builtIn && "text-text-subtlest",
)}
>
<Icon
icon={negated ? "lock" : "lock_open"}
size="sm"
className={classNames("shrink-0", entry.builtIn ? "opacity-60" : "text-text-subtle")}
title={negated ? "Excluded" : "Decrypted"}
/>
<span className={classNames("truncate", entry.entry !== "*" && "font-mono text-xs")}>
{entryLabel(entry.entry)}
</span>
{entry.builtIn && (
<span
title="Ships with Yaak Proxy"
className="shrink-0 text-2xs rounded px-1 border border-border-subtle"
>
built-in
</span>
)}
<IconButton
size="xs"
icon="x"
iconColor="secondary"
title={`Remove ${entryLabel(entry.entry)}`}
disabled={disabled}
className="ml-auto opacity-0 group-hover/entry:opacity-100 focus-visible:opacity-100"
onClick={onRemove}
/>
</div>
);
}
/** The input that adds an entry on Enter, once the suggestions are closed or none is picked */
function EntryInput({
seenRef,
list,
disabled,
onAdd,
}: {
seenRef: React.RefObject<SeenTargets | undefined>;
list: DecryptListEntry[];
/** A change is being saved; Enter waits for it, keeping what was typed */
disabled: boolean;
onAdd: (entry: string) => void;
}) {
const [error, setError] = useState<string | null>(null);
const onAddRef = useRef(onAdd);
onAddRef.current = onAdd;
const listRef = useRef(list);
listRef.current = list;
const disabledRef = useRef(disabled);
disabledRef.current = disabled;
const extensions = useMemo(() => {
const options = decryptFilterOptions(null);
// The suggestions read the capture as they open, not as the input was made.
for (const field of options.fields ?? []) {
field.values = () => {
const fresh = decryptFilterOptions(seenRef.current).fields ?? [];
const values = fresh.find((f) => f.name === field.name)?.values;
return Array.isArray(values) ? values : [];
};
}
const add = (view: EditorView) => {
const text = view.state.doc.toString();
if (text.trim() === "") return false;
if (disabledRef.current) return true;
const entry = normalizeEntry(text);
if (entry == null) {
setError("Not a host or app");
return true;
}
setError(null);
if (!listRef.current.some((e) => e.entry === entry)) onAddRef.current(entry);
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: "" } });
return true;
};
// Low, so Enter picks a suggestion while they are open.
return [filterAutocomplete(options), Prec.low(keymap.of([{ key: "Enter", run: add }]))];
}, [seenRef]);
return (
<div className="grid gap-1" title="Applies to new connections">
<Input
label="Add entry"
hideLabel
size="sm"
stateKey={null}
language={null}
placeholder="Add host, app or *"
extensions={extensions}
onChange={() => setError(null)}
/>
{error != null && <div className="text-xs text-danger">{error}</div>}
</div>
);
}
/** Opens the decrypt list from the state pill's More…, until Settings holds it */
export const decryptListDialogOpenAtom = atom(false);
export function DecryptListDialog() {
const [open, setOpen] = useAtom(decryptListDialogOpenAtom);
return (
<Dialog
open={open}
onClose={() => setOpen(false)}
size="dynamic"
title="Decrypt List"
className="w-[36rem]"
>
<div className="pb-4">{open && <DecryptListEditor />}</div>
</Dialog>
);
}
+45 -3
View File
@@ -2,7 +2,10 @@ import { Button, Icon, InlineCode, LoadingIcon } from "@yaakapp-internal/ui";
import classNames from "classnames";
import { useAtomValue } from "jotai";
import type { ReactNode } from "react";
import { useDecryptList, useEditDecryptList } from "../hooks/useDecryptList";
import { useRpcMutation } from "../hooks/useRpcMutation";
import { everythingEdit } from "../lib/decrypt";
import { decryptStep } from "../lib/firstRun";
import { encryptingPercent } from "../lib/encrypting";
import { proxyStateAtom } from "../lib/store";
import { useCopyEnvironment, useProxySetup, useSystemProxySwitch } from "./ProxyStatus";
@@ -11,7 +14,7 @@ type StepState = "todo" | "next" | "wait" | "done" | "fail";
/**
* The list's empty state until traffic arrives: trust the certificate, turn on the system proxy,
* then see traffic. Not dismissable and nothing remembered; the first flow replaces it. Copy
* choose what to decrypt, then see traffic. Not dismissable and nothing remembered; the first flow replaces it. Copy
* environment beside it serves someone who wants one terminal proxied and nothing system-wide.
*/
export function FirstRun() {
@@ -22,6 +25,8 @@ export function FirstRun() {
const execute = useRpcMutation("execute_action");
const retry = useRpcMutation("take_over");
const copyEnvironment = useCopyEnvironment();
const decryptList = useDecryptList();
const saveDecryptList = useEditDecryptList();
const running = proxyState?.state === "running";
// Changed only by the process that owns the engine, so not from here while the CLI does.
@@ -47,6 +52,9 @@ export function FirstRun() {
: trusted
? "next"
: "todo";
const decrypt = decryptStep(decryptList, trusted);
const everything = decrypt.choice === "everything";
const setEverything = (on: boolean) => saveDecryptList.mutate(everythingEdit(on));
const ready = trusted && (systemOn || !systemSupported);
const encrypting = !running && !otherOwner ? encryptingPercent(proxyState) : null;
const trafficState: StepState =
@@ -57,8 +65,8 @@ export function FirstRun() {
<div className="w-full max-w-[40rem]">
<div className="text-xl font-semibold mb-1.5">Set up Yaak Proxy</div>
<div className="text-text-subtle text-sm leading-relaxed mb-4">
Three steps, once. Then every app on this Mac sends its traffic here, and HTTPS reads as
plain text.
{systemSupported ? "Four" : "Three"} steps, once. Then every app on this Mac sends its
traffic here.
</div>
<div className="rounded-lg border border-border-subtle bg-surface divide-y divide-border-subtle">
<Step
@@ -115,6 +123,40 @@ export function FirstRun() {
)}
<Step
n={systemSupported ? 3 : 2}
state={decrypt.state}
title="What to decrypt"
description={
everything ? (
<span title="Except the built-in exclusions">Everything</span>
) : (
<span title="From a flow or the sidebar">Pick as they appear</span>
)
}
action={
everything ? (
<Button
size="2xs"
variant="border"
isLoading={saveDecryptList.isPending}
onClick={() => setEverything(false)}
>
Pick As They Appear
</Button>
) : (
<Button
size="2xs"
variant="border"
color={decrypt.state === "next" ? "primary" : "default"}
isLoading={saveDecryptList.isPending}
onClick={() => setEverything(true)}
>
Everything
</Button>
)
}
/>
<Step
n={systemSupported ? 4 : 3}
state={trafficState}
title={
encrypting != null
@@ -30,6 +30,7 @@ import { messagesTabLabel, streamIsOpen } from "../lib/messages";
import { EmptyState, FlowBodyViewer, useFlowBody } from "./FlowBodyViewer";
import { FlowHeaders, FlowQuery, queryParams } from "./FlowHeaders";
import { FlowMessages } from "./FlowMessages";
import { NotDecrypted } from "./NotDecrypted";
const TAB_RESPONSE = "response";
const TAB_REQUEST = "request";
@@ -62,6 +63,8 @@ export function FlowDetail({ style, sideBySide }: { style?: CSSProperties; sideB
<Keys keys={["⌘", "K"]} />
</div>
</EmptyState>
) : flow.tunnelled ? (
<NotDecrypted flow={flow} />
) : (
<FlowPane flow={flow} />
)}
+15 -5
View File
@@ -457,14 +457,15 @@ const FlowRow = memo(function FlowRow({
});
/**
* One mark per row, by a fixed priority: failed, cancelled, cut, saved. Its tooltip lists every
* state the flow has. Streaming and agent reads join it once the engine records them.
* One mark per row, by a fixed priority: failed, cancelled, not decrypted, streaming, cut, saved.
* Its tooltip lists every state the flow has. Agent reads join it once the engine records them.
*/
function FlowMark({ flow }: { flow: Flow }) {
const open = isOpenStream(flow);
const states: string[] = [];
if (flow.error != null) states.push(`Failed: ${flow.error}`);
if (flow.cancelled) states.push("Cancelled by the app");
if (flow.tunnelled) states.push("Not decrypted");
if (open) states.push("Streaming");
if (flow.responseTruncated) states.push("Body cut at the capture limit");
if (flow.savedRequestId != null) states.push("Saved to Yaak");
@@ -475,6 +476,8 @@ function FlowMark({ flow }: { flow: Flow }) {
<Icon icon="circle_alert" size="sm" color="danger" />
) : flow.cancelled ? (
<Icon icon="circle_off" size="sm" className="text-text-subtlest" />
) : flow.tunnelled ? (
<Icon icon="lock" size="sm" className="text-text-subtlest" />
) : open ? (
<span aria-hidden className="w-[7px] h-[7px] rounded-full bg-info ring-3 ring-info/20" />
) : flow.responseTruncated ? (
@@ -488,6 +491,11 @@ function FlowMark({ flow }: { flow: Flow }) {
const mono = "font-mono text-xs";
/** An undecrypted tunnel still open: written as it opens, done once it closes */
function isOpenTunnel(flow: Flow): boolean {
return flow.tunnelled && flow.elapsedMs == null && flow.error == null;
}
/** A WebSocket, event stream or gRPC call still open: written as it opens, done once it ends */
function isOpenStream(flow: Flow): boolean {
return flow.streamKind != null && flow.elapsedMs == null && flow.error == null && !flow.cancelled;
@@ -529,6 +537,8 @@ function FlowCell({ column, flow, span }: { column: ColumnId; flow: Flow; span:
</span>
);
case "path": {
// A tunnel's only path is its host; what it carried is unread.
if (flow.tunnelled) return <span className="text-text-subtlest">Not decrypted</span>;
const { path, query } = splitPath(flow.url);
if (flow.streamKind == null) {
return (
@@ -556,7 +566,7 @@ function FlowCell({ column, flow, span }: { column: ColumnId; flow: Flow; span:
);
}
case "status":
return flow.cancelled && flow.status == null ? (
return (flow.cancelled || flow.tunnelled) && flow.status == null ? (
<span className={classNames(mono, "text-text-subtlest")}>--</span>
) : (
<HttpStatusTagRaw status={flow.status ?? 0} short className={mono} />
@@ -589,8 +599,8 @@ function FlowCell({ column, flow, span }: { column: ColumnId; flow: Flow; span:
</span>
);
case "time":
// An open stream shows how long it has been open, quietly, as its messages land.
if (isOpenStream(flow)) {
// An open stream or tunnel shows how long it has been open, quietly, as its messages land.
if (isOpenStream(flow) || isOpenTunnel(flow)) {
const open = Date.now() - Date.parse(utcTimestamp(flow.startedAt));
return (
<span className={classNames(mono, "text-right text-text-subtlest")}>
@@ -0,0 +1,85 @@
import { formatSize } from "@yaakapp-internal/lib/formatSize";
import type { Flow } from "@yaakapp-internal/proxy-lib";
import { Button, formatMillis, Icon } from "@yaakapp-internal/ui";
import { useDecryptList, useEditDecryptList } from "../hooks/useDecryptList";
import { type DecryptSubject, detailActions, listEdit, setDecrypted } from "../lib/decrypt";
import { sidebarPath } from "../lib/search";
import { EmptyState } from "./FlowBodyViewer";
/**
* The detail of HTTPS passed through undecrypted: its sizes and time, and buttons that add its
* host or its app to the decrypt list, from the next connection on.
*/
export function NotDecrypted({ flow }: { flow: Flow }) {
const list = useDecryptList();
const save = useEditDecryptList();
const host = sidebarPath(flow.url).split("/")[0] ?? flow.url;
const hostSubject: DecryptSubject = { kind: "host", host };
const appSubject: DecryptSubject | null =
flow.clientName == null
? null
: { kind: "app", name: flow.clientName, bundleId: flow.clientBundleId };
const app = flow.clientName;
const actions = detailActions(
list,
host,
app == null ? null : { name: app, bundleId: flow.clientBundleId },
);
const open = flow.elapsedMs == null && flow.error == null;
const decrypt = (subject: DecryptSubject) =>
save.mutate(listEdit(list, setDecrypted(list, [subject], true)));
const facts = [
`${formatSize(Number(flow.requestSize))} sent`,
`${formatSize(Number(flow.responseSize))} received`,
open ? "open" : flow.elapsedMs == null ? null : formatMillis(flow.elapsedMs),
].filter((f) => f != null);
return (
<EmptyState>
<div className="grid justify-items-center gap-2">
<div className="flex items-center gap-1.5 text-text-subtle">
<Icon icon="lock" size="sm" />
Not decrypted
</div>
<div className="font-mono text-xs">{facts.join(" · ")}</div>
{flow.error != null && <div className="text-danger">{flow.error}</div>}
{actions.listed ? (
<div title="Still tunnelled? The app may pin its certificate">
Decrypting new connections
</div>
) : actions.blocked != null ? (
<div title="Remove it from the decrypt list to decrypt">
Excluded by <span className="font-mono text-xs">{actions.blocked}</span>
</div>
) : (
<div className="flex gap-2 mt-1">
{actions.host && (
<Button
size="xs"
variant="border"
title={`Decrypt new connections to ${host}`}
disabled={save.isPending}
onClick={() => decrypt(hostSubject)}
>
Decrypt Host
</Button>
)}
{actions.app && appSubject != null && (
<Button
size="xs"
variant="border"
title={`Decrypt new connections from ${app}`}
disabled={save.isPending}
onClick={() => decrypt(appSubject)}
>
Decrypt App
</Button>
)}
</div>
)}
</div>
</EmptyState>
);
}
@@ -20,6 +20,7 @@ import { FlowDetail } from "./FlowDetail";
import { FlowList } from "./FlowList";
import { LockedState } from "./LockedState";
import { ProxyStatus, useProxySetup } from "./ProxyStatus";
import { DecryptListDialog } from "./DecryptListEditor";
import { HelperDialog } from "./HelperDialog";
import { SaveDialog } from "./SaveDialog";
import { SearchBar } from "./SearchBar";
@@ -150,6 +151,7 @@ export function ProxyLayout() {
</SidebarLayout>
<SaveDialog />
<HelperDialog />
<DecryptListDialog />
<Toasts />
</div>
);
@@ -17,6 +17,7 @@ import { useRpcEvent } from "../hooks/useRpcEvent";
import { useRpcMutation } from "../hooks/useRpcMutation";
import { useRpcQuery } from "../hooks/useRpcQuery";
import { helperDialogOpenAtom, helperRegisteredAtAtom } from "../lib/atoms";
import { decryptListDialogOpenAtom } from "./DecryptListEditor";
import { encryptingPercent } from "../lib/encrypting";
import { environmentExports } from "../lib/env";
import { proxyStateAtom, refreshProxyState, systemProxyEverOnAtom } from "../lib/store";
@@ -45,6 +46,7 @@ export function ProxyStatus() {
const setHttpVersion = useSetHttpVersion();
const copyEnvironment = useCopyEnvironment();
const setHelperDialogOpen = useSetAtom(helperDialogOpenAtom);
const setDecryptListOpen = useSetAtom(decryptListDialogOpenAtom);
const { caStatus, trust, systemProxy, setSystemProxy } = setup;
const systemSwitch = useSystemProxySwitch(setup);
@@ -165,6 +167,11 @@ export function ProxyStatus() {
),
},
{ type: "separator" },
{
label: "Decrypt List…",
icon: "lock_open",
onSelect: () => setDecryptListOpen(true),
},
{
label: "Copy Environment for a Terminal",
icon: "square_terminal",
+75 -2
View File
@@ -1,12 +1,22 @@
import { Icon, IconButton, Tree } from "@yaakapp-internal/ui";
import {
ContextMenu,
type DropdownItem,
Icon,
IconButton,
Tree,
type TreeProps,
} from "@yaakapp-internal/ui";
import classNames from "classnames";
import { atom, useAtom, useAtomValue } from "jotai";
import { atomWithStorage } from "jotai/utils";
import { useCallback } from "react";
import { useCallback, useEffect } from "react";
import { useDecryptList, useEditDecryptList } from "../hooks/useDecryptList";
import { SIDEBAR_TREE_ID } from "../lib/atoms";
import { blockerOf, decryptMenuAction, isDecrypted, listEdit, setDecrypted } from "../lib/decrypt";
import { applyCollapsed, type CollapsedMap, collapsedMap, folderIds } from "../lib/sidebarCollapse";
import { type SidebarItem, SYSTEM_ID } from "../lib/sidebarTree";
import { hideSystemAtom, noteSidebarInput, sidebarTreeAtom } from "../lib/store";
import { useShowToast } from "../lib/toast";
import { AppIcon } from "./AppIcon";
/** The apps, sites, hosts and paths the user expanded, by node id, kept across launches */
@@ -52,16 +62,33 @@ function ItemInner({ item }: { item: SidebarItem }) {
return (
<div className="flex items-center gap-2 w-full min-w-0">
{item.kind === "all" && <Icon icon="layers" size="sm" className="text-text-subtle" />}
{item.kind === "tunnelled" && <Icon icon="lock" size="sm" className="text-text-subtle" />}
{item.appPath != null && <AppIcon path={item.appPath} />}
<span className="truncate">{item.label}</span>
{item.sublabel != null && (
<span className="truncate text-xs text-text-subtlest">{item.sublabel}</span>
)}
{item.decrypt != null && <DecryptedMark item={item} />}
<Count item={item} />
</div>
);
}
/** A row with nothing in its menu: the menu closes as it opens, so the row is not left marked */
function CloseAtOnce({ onClose }: { onClose: () => void }) {
useEffect(() => onClose(), [onClose]);
return null;
}
/** A small open lock on a host, site or app the decrypt list decrypts */
function DecryptedMark({ item }: { item: SidebarItem }) {
const list = useDecryptList();
if (item.decrypt == null || !isDecrypted(list, item.decrypt)) return null;
return (
<Icon icon="lock_open" size="xs" title="Decrypted" className="shrink-0 text-text-subtlest" />
);
}
/** Beside the row's button rather than in it, since it is a button of its own */
function ItemRightSlot({ item }: { item: SidebarItem }) {
return item.id === SYSTEM_ID ? <HideSystemToggle /> : <span aria-hidden />;
@@ -94,6 +121,50 @@ export function Sidebar() {
(item: SidebarItem) => `${item.id}:${item.count}:${item.countLabel ?? ""}`,
[],
);
const decryptList = useDecryptList();
const setDecryptList = useEditDecryptList();
const { mutate: saveDecryptList } = setDecryptList;
const showToast = useShowToast();
// Decrypt or Stop Decrypting the selected hosts, sites and apps, from new connections on.
const getContextMenu = useCallback(
(items: SidebarItem[]): DropdownItem[] => {
const subjects = items.flatMap((i) => (i.decrypt == null ? [] : [i.decrypt]));
const action = decryptMenuAction(decryptList, subjects);
if (action == null) return [];
return [
{
label: action.label,
icon: action.on ? "lock_open" : "lock",
onSelect: () => {
const blocked = action.on ? blockerOf(decryptList, subjects) : null;
if (blocked != null) {
showToast({
id: "decrypt-blocked",
color: "notice",
message: `Excluded by ${blocked}`,
});
return;
}
// Only what this changes, applied to the list as it is then, so a second change
// made before this one lands keeps it.
const next = setDecrypted(decryptList, subjects, action.on);
saveDecryptList(listEdit(decryptList, next));
},
},
];
},
[decryptList, saveDecryptList, showToast],
);
const renderContextMenu = useCallback<NonNullable<TreeProps<SidebarItem>["renderContextMenu"]>>(
({ items, position, onClose }) =>
items.length === 0 ? (
<CloseAtOnce onClose={onClose} />
) : (
<ContextMenu items={items as DropdownItem[]} triggerPosition={position} onClose={onClose} />
),
[],
);
return (
// The tree scrolls itself, in a row of bounded height, so its virtualizer mounts only the rows
@@ -114,6 +185,8 @@ export function Sidebar() {
getItemKey={getItemKey}
ItemInner={ItemInner}
ItemRightSlot={ItemRightSlot}
getContextMenu={getContextMenu}
renderContextMenu={renderContextMenu}
/>
</aside>
);
+1
View File
@@ -50,6 +50,7 @@ const base: Flow = {
grpcMethod: null,
grpcStatus: null,
grpcMessage: null,
tunnelled: false,
};
const jsonRequest = JSON.stringify({ amount: 4200, currency: "usd", capture: true });
@@ -49,6 +49,7 @@ const flowBase: Flow = {
grpcMethod: null,
grpcStatus: null,
grpcMessage: null,
tunnelled: false,
};
/** Seconds past 21:41:12 as a stored timestamp */
+45
View File
@@ -0,0 +1,45 @@
import { useQueryClient } from "@tanstack/react-query";
import type {
DecryptList,
DecryptListChangedPayload,
DecryptListEntry,
} from "@yaakapp-internal/proxy-lib";
import { useCallback } from "react";
import { useShowToast } from "../lib/toast";
import { useRpcEvent } from "./useRpcEvent";
import { useRpcMutation } from "./useRpcMutation";
import { useRpcQuery } from "./useRpcQuery";
const KEY = ["get_decrypt_list", {}];
const EMPTY: DecryptListEntry[] = [];
/**
* The decrypt list's entries, empty until read. Kept current as this process changes it, from
* the app or through its control API.
*/
export function useDecryptList(): DecryptListEntry[] {
const queryClient = useQueryClient();
const onChanged = useCallback(
(payload: DecryptListChangedPayload) =>
queryClient.setQueryData<DecryptList>(KEY, payload.list),
[queryClient],
);
useRpcEvent("decrypt_list_changed", onChanged);
return useRpcQuery("get_decrypt_list", {}).data?.entries ?? EMPTY;
}
/**
* Adds and removes entries, `edit_decrypt_list` applying them to the list as it is when they
* land, so two changes made in quick succession both stick. Everything that reads the list
* then reads it again. A failure, such as an entry that does not parse, is a toast.
*/
export function useEditDecryptList() {
const queryClient = useQueryClient();
const showToast = useShowToast();
return useRpcMutation("edit_decrypt_list", {
// Read again rather than taken from the answer, which can land after a newer change's
// event and would put the older list back.
onSuccess: () => queryClient.invalidateQueries({ queryKey: KEY }),
onError: (e) => showToast({ id: "decrypt-list", color: "danger", message: e.message }),
});
}
+305
View File
@@ -0,0 +1,305 @@
import { CompletionContext } from "@codemirror/autocomplete";
import { EditorState } from "@codemirror/state";
import type { DecryptListEntry } from "@yaakapp-internal/proxy-lib";
import { filterCompletionSource } from "@yaakapp-internal/ui/editor";
import { describe, expect, test } from "vite-plus/test";
import {
blockerOf,
blockingExclusion,
decryptFilterOptions,
detailActions,
decryptMenuAction,
decrypts,
decryptsEverything,
entryLabel,
everythingEdit,
isDecrypted,
listEdit,
normalizeEntry,
setDecrypted,
subjectQuery,
toggleDecrypt,
} from "./decrypt";
const user = (...entries: string[]): DecryptListEntry[] =>
entries.map((entry) => ({ entry, builtIn: false }));
const builtIn = (...entries: string[]): DecryptListEntry[] =>
entries.map((entry) => ({ entry, builtIn: true }));
const BUILT_INS = builtIn("!host:*.apple.com", "!host:*.icloud.com");
describe("normalizeEntry", () => {
test("a bare hostname is a host entry", () => {
expect(normalizeEntry("api.example.com")).toBe("host:api.example.com");
expect(normalizeEntry(" API.Example.com. ")).toBe("host:api.example.com");
expect(normalizeEntry("https://api.example.com:8443/v1")).toBe("host:api.example.com:8443");
});
test("prefixes and exclusions", () => {
expect(normalizeEntry("HOST:*.Example.com")).toBe("host:*.example.com");
expect(normalizeEntry("!x.com")).toBe("!host:x.com");
expect(normalizeEntry("! host:x.com")).toBe("!host:x.com");
expect(normalizeEntry('app:"Google Chrome"')).toBe("app:Google Chrome");
expect(normalizeEntry("App: com.google.Chrome")).toBe("app:com.google.Chrome");
expect(normalizeEntry("host:[::1]:8443")).toBe("host:[::1]:8443");
expect(normalizeEntry(" * ")).toBe("*");
});
test("what is not an entry", () => {
for (const bad of ["", "!", "app:", "host:a b", "host:a.com:http", "host:a.com:99999"]) {
expect(normalizeEntry(bad)).toBeNull();
}
});
test("labels", () => {
expect(entryLabel("*")).toBe("Everything");
expect(entryLabel("host:a.com")).toBe("host:a.com");
});
});
describe("decrypts", () => {
test("an empty list decrypts nothing, with or without the built-ins", () => {
expect(decrypts([], { host: "a.com" })).toBe(false);
expect(decrypts(BUILT_INS, { host: "a.com" })).toBe(false);
});
test("hosts, sites and ports", () => {
const list = user("host:*.example.com", "host:other.com:8443");
expect(decrypts(list, { host: "api.example.com" })).toBe(true);
expect(decrypts(list, { host: "example.com" })).toBe(true);
expect(decrypts(list, { host: "notexample.com" })).toBe(false);
expect(decrypts(list, { host: "other.com", port: 8443 })).toBe(true);
expect(decrypts(list, { host: "other.com" })).toBe(false);
});
test("apps by name or bundle id", () => {
const chrome = { name: "Google Chrome", bundleId: "com.google.Chrome" };
expect(decrypts(user("app:google chrome"), { host: "a.com", app: chrome })).toBe(true);
expect(decrypts(user("app:com.google.*"), { host: "a.com", app: chrome })).toBe(true);
expect(decrypts(user("app:Safari"), { host: "a.com", app: chrome })).toBe(false);
});
test("everything keeps the built-in exclusions, which a specific entry beats", () => {
const list = [...user("*"), ...BUILT_INS];
expect(decrypts(list, { host: "api.example.com" })).toBe(true);
expect(decrypts(list, { host: "gateway.icloud.com" })).toBe(false);
const specific = [...user("*", "host:developer.apple.com"), ...BUILT_INS];
expect(decrypts(specific, { host: "developer.apple.com" })).toBe(true);
expect(decrypts(specific, { host: "www.apple.com" })).toBe(false);
});
test("the user's exclusions win wherever they sit", () => {
for (const list of [user("!host:a.example.com", "*"), user("*", "!host:a.example.com")]) {
expect(decrypts(list, { host: "a.example.com" })).toBe(false);
expect(decrypts(list, { host: "b.example.com" })).toBe(true);
}
});
});
describe("the sidebar's Decrypt and Stop Decrypting", () => {
test("Decrypt adds the host's entry before the built-ins", () => {
const list = BUILT_INS;
const subject = { kind: "host", host: "api.example.com" } as const;
expect(isDecrypted(list, subject)).toBe(false);
expect(toggleDecrypt(list, subject)).toEqual([
"host:api.example.com",
"!host:*.apple.com",
"!host:*.icloud.com",
]);
});
test("Stop Decrypting removes the entry that decrypts it", () => {
const list = [...user("host:api.example.com", "host:b.com"), ...BUILT_INS];
const subject = { kind: "host", host: "api.example.com" } as const;
expect(isDecrypted(list, subject)).toBe(true);
expect(toggleDecrypt(list, subject)).toEqual([
"host:b.com",
"!host:*.apple.com",
"!host:*.icloud.com",
]);
});
test("Stop Decrypting under everything excludes the host", () => {
const list = user("*");
const subject = { kind: "site", site: "example.com" } as const;
expect(isDecrypted(list, subject)).toBe(true);
expect(toggleDecrypt(list, subject)).toEqual(["*", "!host:*.example.com"]);
});
test("Decrypt adds nothing while a broader exclusion of the user's would still win", () => {
const list = user("*", "!host:*.example.com");
const subject = { kind: "host", host: "api.example.com" } as const;
expect(blockingExclusion(list, subjectQuery(subject))).toBe("!host:*.example.com");
expect(toggleDecrypt(list, subject)).toEqual(["*", "!host:*.example.com"]);
// The built-ins are not the user's to block with: a specific entry beats them.
expect(blockingExclusion(BUILT_INS, { host: "www.apple.com" })).toBeNull();
});
test("Decrypt undoes the sidebar's own Stop Decrypting", () => {
const subject = { kind: "site", site: "example.com" } as const;
const stopped = toggleDecrypt(user("*"), subject);
expect(stopped).toEqual(["*", "!host:*.example.com"]);
const list = user(...stopped);
expect(blockerOf(list, [subject])).toBeNull();
expect(toggleDecrypt(list, subject)).toEqual(["*"]);
const host = { kind: "host", host: "api.example.com" } as const;
expect(blockerOf(list, [host])).toBe("!host:*.example.com");
});
test("an exact site entry beats the built-in exclusion of the same site", () => {
expect(decrypts([...user("host:apple.com"), ...BUILT_INS], { host: "apple.com" })).toBe(true);
});
test("Decrypt drops the user's own exclusion first", () => {
const list = user("*", "!host:*.example.com");
const subject = { kind: "site", site: "example.com" } as const;
expect(toggleDecrypt(list, subject)).toEqual(["*"]);
});
test("apps by name, and a host with a port", () => {
const slack = { kind: "app", name: "Slack", bundleId: "com.tinyspeck.slackmacgap" } as const;
expect(toggleDecrypt([], slack)).toEqual(["app:Slack"]);
expect(isDecrypted(user("app:com.tinyspeck.slackmacgap"), slack)).toBe(true);
expect(isDecrypted(user("*"), slack)).toBe(true);
const port = { kind: "host", host: "localhost:8443" } as const;
expect(toggleDecrypt([], port)).toEqual(["host:localhost:8443"]);
expect(isDecrypted(user("host:localhost:8443"), port)).toBe(true);
});
});
describe("the sidebar menu", () => {
const a = { kind: "host", host: "a.com" } as const;
const b = { kind: "host", host: "b.com" } as const;
test("offers Decrypt unless every selected row is decrypted", () => {
expect(decryptMenuAction(user("host:a.com"), [a])).toEqual({
label: "Stop Decrypting",
on: false,
});
expect(decryptMenuAction(user("host:a.com"), [a, b])).toEqual({ label: "Decrypt", on: true });
expect(decryptMenuAction([], [])).toBeNull();
});
test("applies to every selected row, leaving those already so", () => {
const next = setDecrypted(user("host:a.com"), [a, b], true).map((e) => e.entry);
expect(next).toEqual(["host:a.com", "host:b.com"]);
expect(setDecrypted(user("host:a.com", "host:b.com"), [a, b], false)).toEqual([]);
});
});
describe("the Not decrypted detail's buttons", () => {
const slack = { name: "Slack", bundleId: "com.tinyspeck.slackmacgap" };
test("each button is offered only when its own change would decrypt the connection", () => {
// `!app:Slack` still excludes Slack's connections whatever host is added.
const list = user("*", "!app:Slack");
expect(detailActions(list, "edgeapi.slack.com", slack)).toEqual({
listed: false,
host: false,
app: true,
blocked: null,
});
// And `!host:` the other way round.
expect(detailActions(user("*", "!host:edgeapi.slack.com"), "edgeapi.slack.com", slack)).toEqual(
{ listed: false, host: true, app: false, blocked: null },
);
});
test("names the exclusion when neither would", () => {
const list = user("*", "!host:*.slack.com", "!app:Slack");
expect(detailActions(list, "edgeapi.slack.com", slack)).toEqual({
listed: false,
host: false,
app: false,
blocked: "!host:*.slack.com",
});
});
test("both on an empty list, and none once it is listed", () => {
expect(detailActions(BUILT_INS, "a.com", slack)).toEqual({
listed: false,
host: true,
app: true,
blocked: null,
});
expect(detailActions(user("host:a.com"), "a.com", null).listed).toBe(true);
});
});
describe("the first-run step", () => {
test("Everything adds *, and Pick as they appear takes it out", () => {
expect(decryptsEverything(BUILT_INS)).toBe(false);
expect(decryptsEverything([...user("*"), ...BUILT_INS])).toBe(true);
expect(everythingEdit(true)).toEqual({ add: ["*"], remove: [] });
expect(everythingEdit(false)).toEqual({ add: [], remove: ["*"] });
});
});
describe("edits sent as additions and removals", () => {
test("a toggle becomes what it adds and removes, not the whole list", () => {
const list = [...user("*", "!host:*.example.com"), ...BUILT_INS];
const site = { kind: "site", site: "example.com" } as const;
expect(listEdit(list, setDecrypted(list, [site], true))).toEqual({
add: [],
remove: ["!host:*.example.com"],
});
const host = { kind: "host", host: "a.com" } as const;
expect(listEdit(BUILT_INS, setDecrypted(BUILT_INS, [host], true))).toEqual({
add: ["host:a.com"],
remove: [],
});
});
test("two edits from the same stale list both survive, applied in turn", () => {
// What the lib does with each edit: remove, then add after the user's own entries.
const apply = (entries: string[], e: { add: string[]; remove: string[] }) => [
...entries.filter((x) => !e.remove.includes(x)),
...e.add,
];
const stale = BUILT_INS;
const first = listEdit(stale, setDecrypted(stale, [{ kind: "host", host: "a.com" }], true));
const second = listEdit(stale, setDecrypted(stale, [{ kind: "host", host: "b.com" }], true));
const saved = apply(apply([], first), second);
expect(saved).toEqual(["host:a.com", "host:b.com"]);
});
});
describe("the list's autocomplete", () => {
const source = filterCompletionSource(
decryptFilterOptions({
hosts: ["api.example.com", "www.example.org"],
apps: [
{ name: "Google Chrome", bundleId: "com.google.Chrome" },
{ name: "curl", bundleId: null },
],
}),
);
function complete(doc: string) {
const state = EditorState.create({ doc });
const result = source(new CompletionContext(state, doc.length, true));
if (result == null || result instanceof Promise) return null;
return { from: result.from, labels: result.options.map((o) => o.label) };
}
test("an empty input offers host:, app: and !", () => {
expect(complete("")).toEqual({ from: 0, labels: ["host", "app", "!"] });
expect(complete("ho")).toEqual({ from: 0, labels: ["host", "app", "!"] });
});
test("after ! it offers the fields negated", () => {
expect(complete("!")).toEqual({ from: 0, labels: ["!host", "!app"] });
expect(complete("!ap")).toEqual({ from: 0, labels: ["!host", "!app"] });
});
test("after host: the hosts seen, replacing only the value", () => {
expect(complete("host:")).toEqual({ from: 5, labels: ["api.example.com", "www.example.org"] });
expect(complete("!host:api")?.from).toBe(6);
});
test("after app: the apps seen, by name and bundle id", () => {
expect(complete("app:")).toEqual({
from: 4,
labels: ['"Google Chrome"', "com.google.Chrome", "curl"],
});
});
});
+394
View File
@@ -0,0 +1,394 @@
import type { DecryptListEntry, SeenTargets } from "@yaakapp-internal/proxy-lib";
import type { FilterOptions } from "@yaakapp-internal/ui/editor";
/**
* The decrypt list as the engine reads it: `host:` and `app:` entries, `*` for everything, any
* of them after `!` to exclude. `DecryptEntry` and `DecryptPolicy` in `crates/yaak-proxy`, which
* decide each connection, follow the same rules; this copy marks the sidebar and the detail.
*/
export const EVERYTHING = "*";
export interface ParsedEntry {
negated: boolean;
kind: "everything" | "host" | "app";
/** A host pattern, lowercased, or an app's name or bundle id as written */
pattern: string;
/** The port a host entry is limited to */
port: number | null;
}
/**
* An entry as typed: with its prefix, or a bare hostname, which is a `host:` entry. A URL is
* taken as its host. Null when it is not one.
*/
export function parseEntry(input: string): ParsedEntry | null {
let rest = input.trim();
const negated = rest.startsWith("!");
if (negated) rest = rest.slice(1).trimStart();
if (rest === "") return null;
if (rest === EVERYTHING) return { negated, kind: "everything", pattern: "", port: null };
if (/^app:/i.test(rest)) {
const app = unquote(rest.slice(4).trim());
return app === "" ? null : { negated, kind: "app", pattern: app, port: null };
}
const host = unquote((/^host:/i.test(rest) ? rest.slice(5) : rest).trim());
const parsed = parseHost(host);
return parsed == null ? null : { negated, kind: "host", ...parsed };
}
function unquote(s: string): string {
return s.length >= 2 && s.startsWith('"') && s.endsWith('"') ? s.slice(1, -1).trim() : s;
}
function parseHost(input: string): { pattern: string; port: number | null } | null {
let host = input;
const scheme = host.indexOf("://");
if (scheme !== -1) {
host = host.slice(scheme + 3).split(/[/?#]/)[0] ?? "";
host = host.slice(host.lastIndexOf("@") + 1);
}
let pattern: string;
let port: number | null = null;
if (host.startsWith("[")) {
const end = host.indexOf("]");
if (end === -1) return null;
pattern = host.slice(1, end);
const after = host.slice(end + 1);
if (after !== "") {
if (!after.startsWith(":")) return null;
port = parsePort(after.slice(1));
if (port == null) return null;
}
} else {
const colon = host.lastIndexOf(":");
const name = colon === -1 ? host : host.slice(0, colon);
// One colon is a port; more, a bare IPv6 address.
if (colon !== -1 && !name.includes(":")) {
port = parsePort(host.slice(colon + 1));
if (port == null) return null;
pattern = name;
} else {
pattern = host;
}
}
pattern = pattern.replace(/\.+$/, "").toLowerCase();
if (pattern === "" || !/^[a-z0-9\-._*:]+$/.test(pattern)) return null;
return { pattern, port };
}
function parsePort(s: string): number | null {
if (!/^\d+$/.test(s)) return null;
const n = Number(s);
return n <= 65535 ? n : null;
}
/** The entry as stored: `host:api.example.com`, `!app:Slack`, `*` */
export function formatEntry(e: ParsedEntry): string {
const not = e.negated ? "!" : "";
if (e.kind === "everything") return `${not}${EVERYTHING}`;
if (e.kind === "app") return `${not}app:${e.pattern}`;
if (e.port == null) return `${not}host:${e.pattern}`;
const host = e.pattern.includes(":") ? `[${e.pattern}]` : e.pattern;
return `${not}host:${host}:${e.port}`;
}
/** An entry as typed, normalized as the engine stores it, or null when it is not one */
export function normalizeEntry(input: string): string | null {
const parsed = parseEntry(input);
return parsed == null ? null : formatEntry(parsed);
}
/** How the list names an entry: `*` is Everything, anything else as written */
export function entryLabel(entry: string): string {
if (entry === EVERYTHING) return "Everything";
if (entry === `!${EVERYTHING}`) return "Nothing";
return entry;
}
/** What a connection is: where it goes and, when known, the app that sent it */
export interface DecryptQuery {
host: string;
port?: number | null;
app?: { name: string; bundleId: string | null } | null;
}
function glob(pattern: string, text: string): boolean {
let pi = 0;
let ti = 0;
let star: [number, number] | null = null;
while (ti < text.length) {
if (pi < pattern.length && pattern[pi] === "*") {
star = [pi, ti];
pi++;
} else if (pi < pattern.length && pattern[pi] === text[ti]) {
pi++;
ti++;
} else if (star != null) {
pi = star[0] + 1;
ti = star[1] + 1;
star = [star[0], star[1] + 1];
} else {
return false;
}
}
return pattern
.slice(pi)
.split("")
.every((c) => c === "*");
}
/** `*.example.com` matches `example.com` too, as the search's `@host` does */
function hostMatches(pattern: string, host: string): boolean {
const h = host
.replace(/^\[|\]$/g, "")
.replace(/\.+$/, "")
.toLowerCase();
return glob(pattern, h) || (pattern.startsWith("*.") && glob(pattern.slice(2), h));
}
function matches(e: ParsedEntry, q: DecryptQuery): boolean {
switch (e.kind) {
case "everything":
return true;
case "host":
return (e.port == null || e.port === (q.port ?? 443)) && hostMatches(e.pattern, q.host);
case "app": {
if (q.app == null) return false;
const p = e.pattern.toLowerCase();
return (
glob(p, q.app.name.toLowerCase()) ||
(q.app.bundleId != null && glob(p, q.app.bundleId.toLowerCase()))
);
}
}
}
function specificity(e: ParsedEntry): number {
if (e.kind === "everything") return 0;
if (e.kind === "app") return Number.POSITIVE_INFINITY;
// A site's `*.` counts for nothing, as `*.apple.com` matches `apple.com` itself.
const pattern = e.pattern.startsWith("*.") ? e.pattern.slice(2) : e.pattern;
return pattern.replaceAll("*", "").length + (e.port == null ? 0 : 1);
}
/**
* Whether the list decrypts `q`: a positive entry matches and no negative one does, wherever
* each sits. A built-in exclusion yields to a positive entry at least as specific as itself.
*/
export function decrypts(list: DecryptListEntry[], q: DecryptQuery): boolean {
const parsed = list.flatMap((e) => {
const p = parseEntry(e.entry);
return p == null ? [] : [{ ...p, builtIn: e.builtIn }];
});
let best = -1;
for (const e of parsed) {
if (!e.negated && matches(e, q)) best = Math.max(best, specificity(e));
}
if (best < 0) return false;
return !parsed.some((e) => e.negated && matches(e, q) && (!e.builtIn || specificity(e) > best));
}
/** Some entry decrypts something: the list is not only exclusions */
export function decryptsAnything(list: DecryptListEntry[]): boolean {
return list.some((e) => !e.entry.trim().startsWith("!"));
}
/** What a sidebar row or the detail's buttons decrypt: a host, a site, or an app */
export type DecryptSubject =
| { kind: "host"; host: string }
| { kind: "site"; site: string }
| { kind: "app"; name: string; bundleId: string | null };
/** The entry that names `subject` alone: `host:api.example.com`, `host:*.example.com`, `app:Slack` */
export function subjectEntry(subject: DecryptSubject): string {
switch (subject.kind) {
case "host":
return normalizeEntry(`host:${subject.host}`) ?? `host:${subject.host}`;
case "site":
return `host:*.${subject.site.toLowerCase()}`;
case "app":
return `app:${subject.name}`;
}
}
/** The connection a subject stands for, as the list judges it */
export function subjectQuery(subject: DecryptSubject): DecryptQuery {
switch (subject.kind) {
case "host": {
const parsed = parseHost(subject.host);
return { host: parsed?.pattern ?? subject.host, port: parsed?.port ?? 443 };
}
case "site":
return { host: subject.site };
case "app":
// No host matches an empty one, so only `*` and app entries decide.
return { host: "", app: { name: subject.name, bundleId: subject.bundleId } };
}
}
/**
* An exclusion of the user's that matches `q`, which no entry added beats: Decrypt cannot help
* until it is edited. Null when there is none.
*/
export function blockingExclusion(
list: DecryptListEntry[],
q: DecryptQuery,
builtIns = false,
): string | null {
for (const e of list) {
if (e.builtIn && !builtIns) continue;
const parsed = parseEntry(e.entry);
if (parsed?.negated && matches(parsed, q)) return e.entry;
}
return null;
}
/**
* What keeps Decrypt on `subject` from working: an exclusion of the user's that matches it,
* other than its own exact one, which Decrypt removes. Null when Decrypt works.
*/
export function blockerOf(list: DecryptListEntry[], subjects: DecryptSubject[]): string | null {
const own = new Set(subjects.map((s) => `!${subjectEntry(s)}`));
const rest = list.filter((e) => !own.has(e.entry));
for (const subject of subjects) {
const blocker = blockingExclusion(rest, subjectQuery(subject));
if (blocker != null) return blocker;
}
return null;
}
/** What the Not decrypted detail offers for one tunnelled connection */
export interface DetailActions {
/** The connection is decrypted from the next one on already */
listed: boolean;
/** Decrypt Host would decrypt it */
host: boolean;
/** Decrypt App would decrypt it */
app: boolean;
/** Neither would: the exclusion that keeps it out */
blocked: string | null;
}
/**
* Each button judged on its own: whether decrypting the host, or the app, would decrypt this
* connection, with its host, port and app together. A button whose change something else
* still excludes is not offered; with neither, the exclusion is named.
*/
export function detailActions(
list: DecryptListEntry[],
host: string,
app: { name: string; bundleId: string | null } | null,
): DetailActions {
const hostSubject: DecryptSubject = { kind: "host", host };
const q = { ...subjectQuery(hostSubject), app };
if (decrypts(list, q)) return { listed: true, host: false, app: false, blocked: null };
const works = (subject: DecryptSubject) => decrypts(setDecrypted(list, [subject], true), q);
const hostWorks = works(hostSubject);
const appWorks = app != null && works({ kind: "app", ...app });
const blocked =
hostWorks || appWorks ? null : (blockingExclusion(list, q) ?? blockingExclusion(list, q, true));
return { listed: false, host: hostWorks, app: appWorks, blocked };
}
/** The list decrypts `subject`'s connections, as its sidebar row marks it */
export function isDecrypted(list: DecryptListEntry[], subject: DecryptSubject): boolean {
return decrypts(list, subjectQuery(subject));
}
/**
* The entries after Decrypt or Stop Decrypting on `subject`, to save whole. Decrypt drops an
* exclusion of the subject the user added, then adds its entry if it is still not decrypted.
* Stop drops its entry, then excludes it if something broader, `*` say, still decrypts it.
*/
export function toggleDecrypt(list: DecryptListEntry[], subject: DecryptSubject): string[] {
return setDecrypted(list, [subject], !isDecrypted(list, subject)).map((e) => e.entry);
}
/**
* The list with every one of `subjects` decrypted (`on`) or not, each as [`toggleDecrypt`]
* changes it, those already so left alone: several sidebar rows at once.
*/
export function setDecrypted(
list: DecryptListEntry[],
subjects: DecryptSubject[],
on: boolean,
): DecryptListEntry[] {
let next = list;
for (const subject of subjects) {
if (isDecrypted(next, subject) === on) continue;
const entry = subjectEntry(subject);
const drop = on ? `!${entry}` : entry;
next = next.filter((e) => e.builtIn || e.entry !== drop);
if (isDecrypted(next, subject) === on) continue;
// Something the user excluded more broadly still keeps it out; adding would change nothing.
if (on && blockingExclusion(next, subjectQuery(subject)) != null) continue;
const add = on ? entry : `!${entry}`;
next = [...next.filter((e) => !e.builtIn), { entry: add, builtIn: false }, ...builtIns(next)];
}
return next;
}
/**
* The sidebar menu's row for the selected rows that can be decrypted: Stop Decrypting when every
* one of them is, else Decrypt. Null when none can.
*/
export function decryptMenuAction(
list: DecryptListEntry[],
subjects: DecryptSubject[],
): { label: "Decrypt" | "Stop Decrypting"; on: boolean } | null {
if (subjects.length === 0) return null;
const on = !subjects.every((s) => isDecrypted(list, s));
return { label: on ? "Decrypt" : "Stop Decrypting", on };
}
function builtIns(list: DecryptListEntry[]): DecryptListEntry[] {
return list.filter((e) => e.builtIn);
}
/**
* What turns `before` into `after`, as `edit_decrypt_list` takes it: the entries to add and to
* remove, applied to the list as it is when they land, so edits made together each keep the
* other's.
*/
export function listEdit(
before: DecryptListEntry[],
after: DecryptListEntry[],
): { add: string[]; remove: string[] } {
const was = new Set(before.map((e) => e.entry));
const now = new Set(after.map((e) => e.entry));
return {
add: after.filter((e) => !was.has(e.entry)).map((e) => e.entry),
remove: before.filter((e) => !now.has(e.entry)).map((e) => e.entry),
};
}
/** The edit that adds `*`, or takes it out, as the first-run card's choice makes it */
export function everythingEdit(on: boolean): { add: string[]; remove: string[] } {
return on ? { add: [EVERYTHING], remove: [] } : { add: [], remove: [EVERYTHING] };
}
/** Whether the list decrypts everything, as the first-run card's choice reads it */
export function decryptsEverything(list: DecryptListEntry[]): boolean {
return list.some((e) => e.entry === EVERYTHING);
}
/**
* What the list's input suggests: `host:`, `app:` and `!` to start an entry; after `host:` the
* hosts seen in the capture, after `app:` the apps seen, by name and bundle id.
*/
export function decryptFilterOptions(seen: SeenTargets | null | undefined): FilterOptions {
const apps = new Set<string>();
for (const app of seen?.apps ?? []) {
apps.add(app.name);
if (app.bundleId != null) apps.add(app.bundleId);
}
return {
fieldPrefix: "",
replaceValueOnly: true,
negation: { prefix: "!", info: "Exclude" },
fields: [
{ name: "host", values: seen?.hosts ?? [], info: "Host or *.site" },
{ name: "app", values: [...apps], info: "App name or bundle id" },
],
};
}
+19 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, test } from "vite-plus/test";
import { setupIncomplete } from "./firstRun";
import { decryptStep, setupIncomplete } from "./firstRun";
describe("setupIncomplete", () => {
const done = { trusted: true, systemProxySupported: true, systemProxyEverOn: true };
@@ -25,3 +25,21 @@ describe("setupIncomplete", () => {
expect(setupIncomplete({ ...done, systemProxySupported: null, trusted: false })).toBe(false);
});
});
describe("decryptStep", () => {
const builtIns = [{ entry: "!host:*.apple.com", builtIn: true }];
test("picks hosts as they appear by default, after the certificate", () => {
expect(decryptStep(builtIns, false)).toEqual({ choice: "pick", state: "todo" });
expect(decryptStep(builtIns, true)).toEqual({ choice: "pick", state: "next" });
});
test("is done once everything, or a host, is on the list", () => {
const everything = [{ entry: "*", builtIn: false }, ...builtIns];
expect(decryptStep(everything, true)).toEqual({ choice: "everything", state: "done" });
const host = [{ entry: "host:api.example.com", builtIn: false }];
expect(decryptStep(host, true)).toEqual({ choice: "pick", state: "done" });
// An exclusion alone decrypts nothing.
expect(decryptStep([{ entry: "!host:a.com", builtIn: false }], true).state).toBe("next");
});
});
+21
View File
@@ -1,3 +1,6 @@
import type { DecryptListEntry } from "@yaakapp-internal/proxy-lib";
import { decryptsEverything } from "./decrypt";
/** What decides whether setup is done, as the app last read it */
export interface SetupState {
/** The certificate is trusted, or null until read */
@@ -19,3 +22,21 @@ export function setupIncomplete(s: SetupState): boolean {
if (!s.trusted) return true;
return s.systemProxySupported && !s.systemProxyEverOn;
}
/** The first-run card's "Choose what to decrypt" step, as the decrypt list has it */
export interface DecryptStep {
/** Everything is decrypted, `*` on the list; else hosts are picked as they appear */
choice: "everything" | "pick";
state: "todo" | "next" | "done";
}
/**
* Picking hosts as they appear is the default and needs nothing done, so the step waits on the
* certificate like the others and is done once a choice is on the list: everything, or any host
* or app picked already.
*/
export function decryptStep(list: DecryptListEntry[], trusted: boolean): DecryptStep {
const choice = decryptsEverything(list) ? "everything" : "pick";
const picked = list.some((e) => !e.builtIn && !e.entry.startsWith("!"));
return { choice, state: picked ? "done" : trusted ? "next" : "todo" };
}
+1
View File
@@ -58,6 +58,7 @@ const flow: Flow = {
grpcMethod: null,
grpcStatus: null,
grpcMessage: null,
tunnelled: false,
};
function bytes(text: string): FlowBodyData {
+10
View File
@@ -229,6 +229,16 @@ describe("parseSearch", () => {
expect(parseSearch("@is:system", true)).toEqual({ system: true });
});
test("keeps or drops HTTPS passed through undecrypted", () => {
expect(parseSearch("@is:tunnelled")).toEqual({ tunnelled: true });
expect(parseSearch("-@is:tunnelled stripe")).toEqual({ q: "stripe", tunnelled: false });
const tunnel = { url: "https://a.com", method: "CONNECT", tunnelled: true } as Flow;
const decrypted = { url: "https://a.com/x", method: "GET", tunnelled: false } as Flow;
expect(matchesQuery(tunnel, { tunnelled: true })).toBe(true);
expect(matchesQuery(decrypted, { tunnelled: true })).toBe(false);
expect(matchesQuery(decrypted, { tunnelled: false })).toBe(true);
});
test("round-trips what the sidebar writes", () => {
const text = [
formatFieldFilter("app", "Google Chrome"),
+7 -2
View File
@@ -5,7 +5,7 @@ import { getDomain } from "tldts";
* A search over every flow in the database: the search box's terms, its field terms, and
* whether System's flows are hidden, as `list_flows` takes them.
*/
export type FlowQuery = Pick<FlowFilter, "q" | "under" | "app" | "system" | "any">;
export type FlowQuery = Pick<FlowFilter, "q" | "under" | "app" | "system" | "tunnelled" | "any">;
/** A word of the search box: a free term, or `@field:value`, maybe negated with `-` */
export interface SearchToken {
@@ -56,7 +56,8 @@ export function formatFieldFilter(field: string, value: string, negated = false)
* not every pairing of their apps and hosts. Within a clause, `@app` terms match any of their
* apps; `@host` terms any of their hosts, each with the `@path` terms after it; `@is:system`
* keeps only macOS's daemons and `-@is:system` drops them, as hiding System does when the
* clause says neither. Other words match the URL, the method, the status or the type.
* clause says neither. `@is:tunnelled` keeps only HTTPS passed through undecrypted, and
* `-@is:tunnelled` drops it. Other words match the URL, the method, the status or the type.
*/
export function parseSearch(text: string, hideSystem = false): FlowQuery | null {
const clauses = clausesOf(text);
@@ -77,6 +78,7 @@ function parseClause(tokens: SearchToken[], hideSystem: boolean): FlowQuery | nu
// Each host with the paths written after it.
const hosts: { host: string; paths: string[] }[] = [];
let system: boolean | undefined = hideSystem ? false : undefined;
let tunnelled: boolean | undefined;
for (const t of tokens) {
if (t.field === "app" && !t.negated && t.value !== "") apps.push(t.value);
else if (t.field === "host" && !t.negated && t.value !== "") {
@@ -91,6 +93,7 @@ function parseClause(tokens: SearchToken[], hideSystem: boolean): FlowQuery | nu
host.paths.push(path);
}
} else if (t.field === "is" && t.value.toLowerCase() === "system") system = !t.negated;
else if (t.field === "is" && t.value.toLowerCase() === "tunnelled") tunnelled = !t.negated;
else if (t.field == null && !t.negated) words.push(t.value);
// Fields and exclusions the query language will add are ignored until it lands.
}
@@ -105,6 +108,7 @@ function parseClause(tokens: SearchToken[], hideSystem: boolean): FlowQuery | nu
...(under.length > 0 ? { under } : {}),
...(apps.length > 0 ? { app: apps } : {}),
...(system == null ? {} : { system }),
...(tunnelled == null ? {} : { tunnelled }),
};
return Object.keys(query).length === 0 ? null : query;
}
@@ -190,6 +194,7 @@ export function matchesQuery(flow: Flow, query: FlowQuery): boolean {
if (query.under != null && !query.under.some((node) => isUnder(flow.url, node))) return false;
if (query.app != null && !query.app.some((app) => matchesApp(flow, app))) return false;
if (query.system != null && isSystemFlow(flow) !== query.system) return false;
if (query.tunnelled != null && flow.tunnelled !== query.tunnelled) return false;
// One of the groups, each judged whole, as the database judges them.
if (query.any != null && query.any.length > 0) {
return query.any.some((group) => matchesQuery(flow, group));
+38
View File
@@ -103,6 +103,44 @@ describe("buildSidebarTree", () => {
});
});
describe("decrypting from the sidebar", () => {
const tunnel = flow("https://bank.example.com", {
...slack,
method: "CONNECT",
tunnelled: true,
});
const root = buildSidebarTree([...flows, tunnel], 5);
const items = itemsById(root);
test("Not decrypted follows All traffic while there are tunnelled flows", () => {
expect((root.children ?? []).slice(0, 2).map((c) => shape(c)[0])).toEqual([
"All traffic 5",
"Not decrypted 1",
]);
expect(items.get("tunnelled")?.query).toBe("@is:tunnelled");
expect(itemsById(buildSidebarTree(flows, 4)).has("tunnelled")).toBe(false);
});
test("hosts, sites and apps name what their menu's Decrypt covers", () => {
expect(items.get("host:bank.example.com")?.decrypt).toEqual({
kind: "host",
host: "bank.example.com",
});
expect(items.get("site:example.com")?.decrypt).toEqual({ kind: "site", site: "example.com" });
expect(items.get("app:Slack|host:edgeapi.slack.com")?.decrypt).toEqual({
kind: "host",
host: "edgeapi.slack.com",
});
expect(items.get("app:Slack")?.decrypt).toEqual({
kind: "app",
name: "Slack",
bundleId: "com.slack",
});
expect(items.get("path:api.github.com/repos")?.decrypt).toBeUndefined();
expect(items.get("domains")?.decrypt).toBeUndefined();
});
});
describe("selection and the search text", () => {
test("selects rows under different apps as groups of their own", () => {
const items = itemsById(buildSidebarTree(flows, 4));
+36 -3
View File
@@ -1,5 +1,6 @@
import type { Flow } from "@yaakapp-internal/proxy-lib";
import type { TreeNode } from "@yaakapp-internal/ui";
import type { DecryptSubject } from "./decrypt";
import {
appKeyOf,
folderOf,
@@ -10,7 +11,7 @@ import {
tokenize,
} from "./search";
export type SidebarKind = "all" | "group" | "app" | "site" | "host" | "path";
export type SidebarKind = "all" | "tunnelled" | "group" | "app" | "site" | "host" | "path";
/** A row of the sidebar: All traffic, a group, an app, or a site, host or path under one */
export interface SidebarItem {
@@ -27,6 +28,8 @@ export interface SidebarItem {
appPath?: string;
/** What selecting the row writes into the search box; empty for all traffic */
query: string;
/** What Decrypt in the row's menu decrypts: its host, site or app */
decrypt?: DecryptSubject;
}
/** The ids of All traffic and the groups */
@@ -34,6 +37,7 @@ export const ALL_ID = "all";
export const APPS_ID = "apps";
export const DOMAINS_ID = "domains";
export const SYSTEM_ID = "system";
export const TUNNELLED_ID = "tunnelled";
/** A row a flow sits under, with what makes it, so a rebuild only looks it up */
interface PlaceRow {
@@ -41,6 +45,7 @@ interface PlaceRow {
kind: "site" | "host" | "path";
label: string;
query: string;
decrypt?: DecryptSubject;
}
/**
@@ -72,8 +77,15 @@ function placeOf(flow: Flow): Place {
kind: "site",
label: site,
query: formatFieldFilter("host", `*.${site}`),
decrypt: { kind: "site", site },
},
{
id: `host:${host}`,
kind: "host",
label: host,
query: hostQuery,
decrypt: { kind: "host", host },
},
{ id: `host:${host}`, kind: "host", label: host, query: hostQuery },
];
let p = "";
for (const segment of segments) {
@@ -121,6 +133,7 @@ function child(parent: Trie, row: PlaceRow): Trie {
item: { id: row.id, kind: row.kind, label: row.label, count: 0, query: row.query },
children: new Map(),
};
if (row.decrypt != null) node.item.decrypt = row.decrypt;
parent.children.set(row.id, node);
}
node.item.count++;
@@ -162,7 +175,8 @@ function group(id: string, label: string): Trie {
/**
* The sidebar: All traffic, then Apps, each app opening to its own sites, hosts and paths, then
* Domains by site, host and path, then System, macOS's daemons, apart from the apps. A group with
* nothing in it is left out. `total` is All traffic's count: every flow it covers in the
* nothing in it is left out. Not decrypted, after All traffic, gathers the HTTPS passed through
* undecrypted, when there is any. `total` is All traffic's count: every flow it covers in the
* database.
*/
export function buildSidebarTree(flows: Flow[], total: number): TreeNode<SidebarItem> {
@@ -177,9 +191,11 @@ export function buildSidebarTree(flows: Flow[], total: number): TreeNode<Sidebar
const domains = group(DOMAINS_ID, "Domains");
const system = { ...group(SYSTEM_ID, "System") };
system.item.query = formatFieldFilter("is", "system");
let tunnelled = 0;
for (const flow of flows) {
const place = placeOf(flow);
if (flow.tunnelled) tunnelled++;
domains.item.count++;
addPlace(domains, place.rows);
if (place.app == null) continue;
@@ -195,6 +211,9 @@ export function buildSidebarTree(flows: Flow[], total: number): TreeNode<Sidebar
count: 0,
query: appQueryFor(place.app, place.system),
};
if (flow.clientName != null) {
item.decrypt = { kind: "app", name: flow.clientName, bundleId: flow.clientBundleId };
}
if (folder != null) item.sublabel = folder;
if (flow.clientPath != null) item.appPath = flow.clientPath;
app = { item, children: new Map() };
@@ -214,6 +233,20 @@ export function buildSidebarTree(flows: Flow[], total: number): TreeNode<Sidebar
depth: 1,
draggable: false,
});
if (tunnelled > 0) {
root.children?.push({
item: {
id: TUNNELLED_ID,
kind: "tunnelled",
label: "Not decrypted",
count: tunnelled,
query: formatFieldFilter("is", "tunnelled"),
},
parent: root,
depth: 1,
draggable: false,
});
}
for (const g of [apps, domains, system]) {
if (g.children.size === 0) continue;
const node: TreeNode<SidebarItem> = {