From e76fd472aefbfa4e5684bf29d4d7b8a4dc2fb4fd Mon Sep 17 00:00:00 2001 From: cc Date: Fri, 20 Nov 2026 13:44:40 +0100 Subject: [PATCH] feat(find): show values and filter binaries by value - Each binary's value is shown in the tree (hidden on phones); a value shared by every binary is stated once in the header instead. - "Value" (or =) opens a typeahead of this key's values with faceted counts. Arrays match by "contains", scalars by "equals"; several picks must all match. Matches are highlighted and listed first in each row. - Picks show on their own row under the key and persist in ?v=. - Works with version compare: lost binaries filter by their old value. Co-Authored-By: Claude Opus 5.5 --- src/app/os/find/page.tsx | 133 +++++++++++++---- src/components/filesystem.tsx | 21 ++- src/components/keyboard-shortcuts.tsx | 10 +- src/components/value-filter.tsx | 205 ++++++++++++++++++++++++++ src/components/value-preview.tsx | 95 ++++++++++++ src/lib/entitlement-value.ts | 81 ++++++++++ 6 files changed, 513 insertions(+), 32 deletions(-) create mode 100644 src/components/value-filter.tsx create mode 100644 src/components/value-preview.tsx create mode 100644 src/lib/entitlement-value.ts diff --git a/src/app/os/find/page.tsx b/src/app/os/find/page.tsx index ca1226f..f9af538 100644 --- a/src/app/os/find/page.tsx +++ b/src/app/os/find/page.tsx @@ -16,7 +16,7 @@ import { } from "lucide-react"; import Link from "next/link"; import { redirect, useRouter, useSearchParams } from "next/navigation"; -import { useEffect, useMemo, useState } from "react"; +import { useCallback, useEffect, useMemo, useState } from "react"; import { BetaBadge } from "@/components/beta-badge"; import FileSystem, { type PathStatus } from "@/components/filesystem"; @@ -24,8 +24,10 @@ import { HeaderPortal } from "@/components/header-portal"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Skeleton } from "@/components/ui/skeleton"; +import { ValueConditions, ValueFilter } from "@/components/value-filter"; import { useQueryFilter } from "@/hooks/use-query-filter"; import { createEngine } from "@/lib/engine"; +import { atomOf, isUniform, matchesAtoms } from "@/lib/entitlement-value"; import { KEY_TRANSITION_NAME, type KeysReturn, @@ -65,18 +67,14 @@ function keysUrlFor(os: string, ns: string) { return `/os/keys?${query.toString()}`; } -/** Paths for a key in a build; a key absent from the build has none. */ -async function pathsForKey(group: string, build: string, key: string) { +/** Binaries with a key in a build, mapped to their values (empty if none). */ +async function valuesForKey(group: string, build: string, key: string) { const engine = await createEngine(group); - try { - return await engine.getPathsForKey(build, key); - } catch (error) { - if (error instanceof Error && error.message.startsWith("key not found")) - return []; - throw error; - } + return engine.getValuesForKey(build, key); } +const NO_VALUES = new Map(); + export default function FindByKey() { const params = useSearchParams(); const router = useRouter(); @@ -85,6 +83,11 @@ export default function FindByKey() { const [group, build] = os ? os.split("/") : ["", ""]; const compareWith = params.get("diff"); + // ?v=a&v=b: binaries whose value contains both atoms. Local state (like + // "Changed only"), so quick successive picks never read a stale URL. + const [selectedAtoms, setSelectedAtomsState] = useState(() => + params.getAll("v"), + ); useEffect(() => { if (os && key) { @@ -97,9 +100,12 @@ export default function FindByKey() { } const [loading, setLoading] = useState(true); - const [paths, setPaths] = useState([]); + const [values, setValues] = useState(NO_VALUES); const [versions, setVersions] = useState([]); - const [comparePaths, setComparePaths] = useState(null); + const [compareValues, setCompareValues] = useState | null>(null); const [compareLoading, setCompareLoading] = useState(false); const [compareError, setCompareError] = useState(false); const [changesOnly, setChangesOnlyState] = useState( @@ -113,18 +119,18 @@ export default function FindByKey() { let cancelled = false; setLoading(true); Promise.all([ - pathsForKey(group, build, key), + valuesForKey(group, build, key), createEngine(group).then((engine) => engine.listOS().catch(() => [] as OS[]), ), ]) .then(([result, list]) => { if (cancelled) return; - setPaths(result); + setValues(result); setVersions([...list].sort(compareOSVersion)); }) .catch(() => { - if (!cancelled) setPaths([]); + if (!cancelled) setValues(NO_VALUES); }) .finally(() => { if (!cancelled) setLoading(false); @@ -144,17 +150,17 @@ export default function FindByKey() { useEffect(() => { let cancelled = false; if (!activeCompare) { - setComparePaths(null); + setCompareValues(null); setCompareLoading(false); setCompareError(false); return; } - setComparePaths(null); + setCompareValues(null); setCompareLoading(true); setCompareError(false); - pathsForKey(group, versionTag(activeCompare), key) + valuesForKey(group, versionTag(activeCompare), key) .then((result) => { - if (!cancelled) setComparePaths(result); + if (!cancelled) setCompareValues(result); }) .catch(() => { if (!cancelled) setCompareError(true); @@ -167,17 +173,43 @@ export default function FindByKey() { }; }, [group, key, activeCompare]); - const diffReady = Boolean(activeCompare) && comparePaths !== null; + const paths = useMemo(() => [...values.keys()], [values]); + const diffReady = Boolean(activeCompare) && compareValues !== null; const { added, removed } = useMemo(() => { - if (!diffReady || !comparePaths) return { added: [], removed: [] }; - const current = new Set(paths); - const base = new Set(comparePaths); + if (!diffReady || !compareValues) return { added: [], removed: [] }; return { - added: paths.filter((path) => !base.has(path)), - removed: comparePaths.filter((path) => !current.has(path)), + added: paths.filter((path) => !compareValues.has(path)), + removed: [...compareValues.keys()].filter((path) => !values.has(path)), }; - }, [comparePaths, diffReady, paths]); + }, [compareValues, diffReady, paths, values]); + + // A lost binary shows (and filters by) its value in the compared build. + const valueFor = useCallback( + (path: string) => + values.has(path) ? values.get(path) : compareValues?.get(path), + [compareValues, values], + ); + + // Every binary's value, for the value filter's suggestions. + const allValues = useMemo( + () => [...paths, ...removed].map(valueFor), + [paths, removed, valueFor], + ); + // `true` everywhere: say it once instead of on every row. + const uniformValue = useMemo( + () => (isUniform(allValues) ? allValues[0] : undefined), + [allValues], + ); + const hasValues = allValues.length > 0 && uniformValue === undefined; + + const setSelectedAtoms = (atoms: string[]) => { + setSelectedAtomsState(atoms); + const next = new URLSearchParams(window.location.search); + next.delete("v"); + for (const atom of atoms) next.append("v", atom); + window.history.replaceState(null, "", `?${next.toString()}`); + }; const showChanges = changesOnly && diffReady; @@ -188,7 +220,11 @@ export default function FindByKey() { const all = showChanges ? [...added, ...removed] : [...paths, ...removed]; const kw = debouncedKeyword.toLowerCase(); return { - list: kw ? all.filter((path) => path.toLowerCase().includes(kw)) : all, + list: all.filter( + (path) => + (!kw || path.toLowerCase().includes(kw)) && + matchesAtoms(valueFor(path), selectedAtoms), + ), statusOf: (path: string): PathStatus | undefined => addedSet.has(path) ? "added" @@ -196,7 +232,15 @@ export default function FindByKey() { ? "removed" : undefined, }; - }, [added, debouncedKeyword, paths, removed, showChanges]); + }, [ + added, + debouncedKeyword, + paths, + removed, + selectedAtoms, + showChanges, + valueFor, + ]); const setParam = (name: string, value: string | null) => { const next = new URLSearchParams(params.toString()); @@ -219,7 +263,7 @@ export default function FindByKey() { return () => clearTimeout(timer); }, [copied]); - const isFiltering = debouncedKeyword.length > 0; + const isFiltering = debouncedKeyword.length > 0 || selectedAtoms.length > 0; // Narrowed views (filter, changes only) open every folder; otherwise the // tree starts with top-level folders open, as before. const narrowed = isFiltering || showChanges; @@ -439,9 +483,27 @@ export default function FindByKey() { )} )} + {uniformValue !== undefined && ( + <> + , all{" "} + + {typeof uniformValue === "string" + ? `"${uniformValue}"` + : atomOf(uniformValue)} + + + )} )} + {!loading && hasValues && ( + + )} + {compareLoading && ( Comparing… )} @@ -516,6 +578,15 @@ export default function FindByKey() { + {!loading && hasValues && selectedAtoms.length > 0 && ( +
+ +
+ )} + {loading ? (
No binaries found with this entitlement.

) : showChanges && !isFiltering ? (

No binaries gained or lost this key.

+ ) : selectedAtoms.length > 0 && !debouncedKeyword ? ( +

No binaries have a value containing all of the selected.

) : (

No binaries match "{keyword}"

)} @@ -560,6 +633,8 @@ export default function FindByKey() { osFor={(path) => statusOf(path) === "removed" ? compareOs : undefined } + valueFor={hasValues ? valueFor : undefined} + highlight={selectedAtoms} /> )}
diff --git a/src/components/filesystem.tsx b/src/components/filesystem.tsx index 7d64463..a1a8025 100644 --- a/src/components/filesystem.tsx +++ b/src/components/filesystem.tsx @@ -20,6 +20,7 @@ import { useState, } from "react"; +import { ValuePreview } from "@/components/value-preview"; import filesToTree, { type TreeWithFullPath } from "@/lib/tree"; import Link from "next/link"; @@ -34,9 +35,14 @@ export type PathStatus = "added" | "removed"; interface Marks { status?: (path: string) => PathStatus | undefined; osFor?: (path: string) => string | undefined; + /** Shows each binary's entitlement value next to its name. */ + valueFor?: (path: string) => unknown; + /** Atoms to mark in the values (the active value filter). */ + highlight?: readonly string[]; } const MarksContext = createContext({}); +const NO_HIGHLIGHT: readonly string[] = []; function countMarks(item: TreeWithFullPath, status: Marks["status"]) { let added = 0; @@ -128,11 +134,19 @@ const FileItem = memo(function FileItem({ className={cn( "font-mono text-sm hover:underline truncate", !mark && "text-muted-foreground hover:text-foreground", + marks.valueFor && "sm:max-w-[60%] sm:shrink-0", )} title={fullPath} > {name} + {marks.valueFor && ( + + )} ); }); @@ -327,13 +341,18 @@ const FileSystem = memo(function FileSystem({ expandAll = null, status, osFor, + valueFor, + highlight, }: { list: string[]; os: string; expandAll?: boolean | null; } & Marks) { const tree = useMemo(() => filesToTree(list), [list]); - const marks = useMemo(() => ({ status, osFor }), [status, osFor]); + const marks = useMemo( + () => ({ status, osFor, valueFor, highlight }), + [status, osFor, valueFor, highlight], + ); return (
diff --git a/src/components/keyboard-shortcuts.tsx b/src/components/keyboard-shortcuts.tsx index dd979e4..2b4e531 100644 --- a/src/components/keyboard-shortcuts.tsx +++ b/src/components/keyboard-shortcuts.tsx @@ -18,6 +18,7 @@ import { * / focus the page filter Esc clear it, then leave it * j / k next / previous item ? this help * g h|k|f go home / keys / files v version picker + * = value filter (find page) * * Lists opt in by marking focusable rows with `data-nav-item`. Widgets that * own their keys (the namespace tree, file trees) handle them first and call @@ -30,6 +31,9 @@ export const NAV_ITEM_ATTR = "data-nav-item"; /** Marks the button that opens the version picker. */ export const VERSION_PICKER_ATTR = "data-version-picker"; +/** Marks the button that opens the value filter. */ +export const VALUE_FILTER_ATTR = "data-value-filter"; + const GOTO_WINDOW_MS = 1200; function isTyping(target: EventTarget | null) { @@ -149,9 +153,10 @@ export function KeyboardShortcuts({ os }: { os: string }) { case "g": gotoAt = performance.now(); return; - case "v": { + case "v": + case "=": { const picker = document.querySelector( - `[${VERSION_PICKER_ATTR}]`, + `[${event.key === "v" ? VERSION_PICKER_ATTR : VALUE_FILTER_ATTR}]`, ); if (!picker) return; event.preventDefault(); @@ -226,6 +231,7 @@ const SHORTCUTS: { title: string; items: [string[], string][] }[] = [ [["/"], "Filter"], [["Esc"], "Clear / leave filter"], [["v"], "Switch version"], + [["="], "Filter by value"], [["?"], "Show shortcuts"], ], }, diff --git a/src/components/value-filter.tsx b/src/components/value-filter.tsx new file mode 100644 index 0000000..bbcee2d --- /dev/null +++ b/src/components/value-filter.tsx @@ -0,0 +1,205 @@ +"use client"; + +import { Braces, Check, X } from "lucide-react"; +import { useMemo, useState } from "react"; + +import { VALUE_FILTER_ATTR } from "@/components/keyboard-shortcuts"; +import { + Command, + CommandEmpty, + CommandInput, + CommandItem, + CommandList, +} from "@/components/ui/command"; +import { + Popover, + PopoverContent, + PopoverTrigger, +} from "@/components/ui/popover"; +import { countAtoms, matchesAtoms } from "@/lib/entitlement-value"; +import { cn } from "@/lib/utils"; + +/** Rendering thousands of cmdk items is slow; typing narrows the rest. */ +const MAX_SUGGESTIONS = 150; + +/** + * "Value contains …" filter with suggestions drawn from this key's values. + * Selecting several atoms means all of them (AND); the counts are faceted, + * so they always say how many binaries would remain after adding that atom. + */ +export function ValueFilter({ + values, + selected, + onChange, +}: { + /** Every binary's value for the key. */ + values: unknown[]; + selected: string[]; + onChange: (selected: string[]) => void; +}) { + const [open, setOpen] = useState(false); + const [query, setQuery] = useState(""); + + const facets = useMemo( + () => countAtoms(values.filter((value) => matchesAtoms(value, selected))), + [values, selected], + ); + + const suggestions = useMemo(() => { + const q = query.trim().toLowerCase(); + const rest = facets.filter(({ atom }) => !selected.includes(atom)); + if (!q) return rest; + // Prefix matches first, then anywhere; each keeps the count order. + const prefix = []; + const inner = []; + for (const facet of rest) { + const index = facet.atom.toLowerCase().indexOf(q); + if (index === 0) prefix.push(facet); + else if (index > 0) inner.push(facet); + } + return [...prefix, ...inner]; + }, [facets, query, selected]); + + const toggle = (atom: string) => { + onChange( + selected.includes(atom) + ? selected.filter((a) => a !== atom) + : [...selected, atom], + ); + setQuery(""); + }; + + return ( + + + + + + + { + // Backspace on an empty query drops the last condition. + if (e.key === "Backspace" && !query && selected.length > 0) { + e.preventDefault(); + onChange(selected.slice(0, -1)); + } + }} + /> + + + {facets.length === 0 ? "No binaries match." : "No such value."} + + {/* Hidden while typing, so Enter picks a match, not these. */} + {!query && + selected.map((atom) => ( + toggle(atom)} + className="gap-2" + > + + + {atom} + + + ))} + {suggestions.slice(0, MAX_SUGGESTIONS).map(({ atom, count }) => ( + toggle(atom)} + className="gap-2" + > + + + {atom} + + + {count} + + + ))} + {suggestions.length > MAX_SUGGESTIONS && ( +
+ {suggestions.length - MAX_SUGGESTIONS} more — type to narrow +
+ )} +
+
+
+
+ ); +} + +/** + * The active value conditions, on their own row under the key header so + * adding one never reflows the header controls. + */ +export function ValueConditions({ + selected, + onChange, +}: { + selected: string[]; + onChange: (selected: string[]) => void; +}) { + if (selected.length === 0) return null; + return ( +
+ Value contains + {selected.map((atom, i) => ( + + {i > 0 && and} + + {atom} + + + + ))} + +
+ ); +} diff --git a/src/components/value-preview.tsx b/src/components/value-preview.tsx new file mode 100644 index 0000000..ae039b0 --- /dev/null +++ b/src/components/value-preview.tsx @@ -0,0 +1,95 @@ +import { atomOf } from "@/lib/entitlement-value"; +import { cn } from "@/lib/utils"; + +const TITLE_LIMIT = 4000; + +function titleFor(value: unknown) { + const json = JSON.stringify(value, null, 2); + return json.length > TITLE_LIMIT ? `${json.slice(0, TITLE_LIMIT)}\n…` : json; +} + +function Atom({ atom, hit }: { atom: string; hit: boolean }) { + return ( + + {atom} + + ); +} + +/** + * One-line summary of an entitlement value, for a tree row. Array items and + * dict keys that match the active value filter come first and are marked, so + * the reason a binary matched is visible even when the list is truncated. + */ +export function ValuePreview({ + value, + highlight, + className, +}: { + value: unknown; + highlight: readonly string[]; + className?: string; +}) { + const hits = new Set(highlight); + const isList = Array.isArray(value); + const isDict = !isList && value !== null && typeof value === "object"; + + let body: React.ReactNode; + let count: number | null = null; + if (isList || isDict) { + const items = isList + ? (value as unknown[]).map((item) => + item !== null && typeof item === "object" + ? JSON.stringify(item) + : atomOf(item), + ) + : Object.keys(value as object); + count = items.length; + const ordered = [ + ...items.filter((item) => hits.has(item)), + ...items.filter((item) => !hits.has(item)), + ]; + body = ( + <> + {isList ? "[" : "{"} + {ordered.map((item, i) => ( + // biome-ignore lint/suspicious/noArrayIndexKey: items may repeat + + {i > 0 && ", "} + + + ))} + {isList ? "]" : "}"} + + ); + } else { + const atom = atomOf(value); + body = ( + + ); + } + + return ( + + {body} + {count !== null && count > 1 && ( + + {count} + + )} + + ); +} diff --git a/src/lib/entitlement-value.ts b/src/lib/entitlement-value.ts new file mode 100644 index 0000000..335e8ce --- /dev/null +++ b/src/lib/entitlement-value.ts @@ -0,0 +1,81 @@ +/** + * Entitlement values as filterable "atoms": the scalars a value is made of. + * + * true -> ["true"] + * "group.com.apple.notes" -> ["group.com.apple.notes"] + * ["kTCCServiceCamera", ...] -> one atom per item + * {"a": true, "b": ["x"]} -> "a", "b", "x" (dict keys and leaf values) + * + * Most interesting values are arrays (tcc.allow, mach-lookup names, keychain + * groups), so filtering by atom reads as "contains", and for scalars it reads + * as "equals". Strings are bare; other scalars are their JSON ("true", "1"). + */ + +export function atomOf(value: unknown): string { + return typeof value === "string" ? value : JSON.stringify(value); +} + +function collect(value: unknown, out: Set) { + if (Array.isArray(value)) { + for (const item of value) collect(item, out); + } else if (value !== null && typeof value === "object") { + for (const [key, item] of Object.entries(value)) { + out.add(key); + collect(item, out); + } + } else { + out.add(atomOf(value)); + } +} + +const atomCache = new WeakMap>(); + +/** Distinct atoms of a value (cached for arrays and dicts). */ +export function valueAtoms(value: unknown): Set { + if (value === null || typeof value !== "object") { + return new Set([atomOf(value)]); + } + let atoms = atomCache.get(value); + if (!atoms) { + atoms = new Set(); + collect(value, atoms); + atomCache.set(value, atoms); + } + return atoms; +} + +/** Whether a value contains every selected atom. */ +export function matchesAtoms(value: unknown, selected: readonly string[]) { + if (selected.length === 0) return true; + const atoms = valueAtoms(value); + return selected.every((atom) => atoms.has(atom)); +} + +export interface AtomCount { + atom: string; + count: number; +} + +/** How many of `values` contain each atom, most common first. */ +export function countAtoms(values: Iterable): AtomCount[] { + const counts = new Map(); + for (const value of values) { + for (const atom of valueAtoms(value)) { + counts.set(atom, (counts.get(atom) ?? 0) + 1); + } + } + return [...counts] + .map(([atom, count]) => ({ atom, count })) + .sort((a, b) => b.count - a.count || a.atom.localeCompare(b.atom)); +} + +/** Whether every value is the same, e.g. `true` everywhere. */ +export function isUniform(values: Iterable) { + let first: string | undefined; + for (const value of values) { + const json = JSON.stringify(value); + if (first === undefined) first = json; + else if (json !== first) return false; + } + return true; +}