Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 98419195c833422a3aebffa8807b4941ea2ad604
parent 9e8f687cf202be5c7a9908519e70d640df6b6cc9
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 13 Nov 2026 03:55:52 -0500

Merge lane/privacy: a privacy settings group and an audit for what the apps show -- settings.privacy (displayPaths, hideHost, hideUser, hidePrivateSites, aliases, maskEmail, useSourceRules) changes only what is drawn: home and mount paths, the hostname, the username, e-mail addresses and private sites in pickers and lists, on the first set of editor and umtool pages; the operator's private rule files, when asked for, are applied on the server only and never reach a page, a log or an error; an operator rule that is too costly or cannot be compiled hides more, never less; archilyzer privacy audit walks both apps' pages and fails on a denied literal, naming the rule by number and never the text, and says so when it could not look; off by default, with every page as before

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
MCOMMANDS.md | 1+
MSETTINGS.md | 31+++++++++++++++++++++++++++++++
Mcommon/bin/archilyzer.ts | 33+++++++++++++++++++++++++++++++++
Acommon/bin/privacy-audit.ts | 129+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/components/PrivacyProvider.tsx | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/privacy/compile.ts | 513+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/privacy/display.test.ts | 168+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/privacy/display.ts | 452+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/privacy/noOperatorNames.test.ts | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/privacy/privacy-server.test.ts | 117+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/privacy/privacy-server.ts | 180+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/privacy/regexSafety.ts | 231+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/privacy/routes.ts | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/privacy/safety.test.ts | 365+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/privacySettings.ts | 189+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/scrubRuleLine.ts | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/settingsDocs.ts | 8++++++++
Mcommon/lib/settingsSchema.test.ts | 6+++++-
Mcommon/lib/settingsSchema.ts | 5+++++
Acommon/publish/privacyAudit.test.ts | 319+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/publish/privacyAudit.ts | 524+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/publish/scrubRuleLine.test.ts | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/publish/source.ts | 27++++++++-------------------
Mcommon/publish/sourceAudit.ts | 12++++--------
Mcommon/views/channelRow.ts | 8++++++--
Mcommon/views/pipeline/stageStatus.ts | 11+++++++++--
Meditor/CHANGELOG.md | 12++++++++++++
Meditor/app/channels/[slug]/page.tsx | 8++++++++
Aeditor/app/channels/components/SiteMembershipsSection.test.ts | 29+++++++++++++++++++++++++++++
Meditor/app/channels/components/SiteMembershipsSection.tsx | 57+++++++++++++++++++++++++++++++++++----------------------
Meditor/app/channels/page.tsx | 29+++++++++++++++++++++++------
Meditor/app/components/SiteScopeSelect.tsx | 15+++++++++++++--
Meditor/app/layout.tsx | 33+++++++++++++++++++++++++++------
Meditor/app/page.tsx | 3+++
Meditor/app/saved-videos/page.tsx | 3++-
Meditor/app/settings/page.tsx | 3++-
Meditor/app/storage/components/SavedVideosStoreCard.tsx | 10+++++++---
Meditor/app/storage/components/StorageLocationsTable.tsx | 11++++++++---
Aeditor/e2e/privacy-audit.spec.ts | 327+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/e2e/servers.ts | 5+++++
Msettings.json.example | 9+++++++++
Mumtool/app/create/page.tsx | 7++++++-
Mumtool/app/jobs/page.tsx | 3++-
Mumtool/app/layout.tsx | 7++++++-
Mumtool/app/page.tsx | 4+++-
Mumtool/app/projects/page.tsx | 6+++++-
Mumtool/app/research/archive/page.tsx | 7+++++--
Mumtool/app/research/page.tsx | 4++--
Mumtool/app/work/page.tsx | 7++++++-
Mumtool/components/CopyButton.tsx | 12+++++++++---
Mumtool/components/projects/TakeVariants.tsx | 4+++-
Mumtool/components/projects/TakesBench.tsx | 4+++-
Mumtool/components/projects/inspector/ProvenanceInspector.tsx | 5++++-
Mumtool/components/queue/QueuePanel.tsx | 14+++++++++-----
Mumtool/components/queue/RenderRecord.tsx | 16+++++++++++++---
Mumtool/components/research/BoardView.tsx | 5++++-
Mumtool/components/system/Maintenance.tsx | 15++++++++-------
Mumtool/components/system/ToolsPanel.tsx | 7+++++--
Aumtool/e2e/privacy-audit.spec.ts | 253+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/inbox.ts | 9+++++++--
Aumtool/lib/privacy.test.ts | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/privacy.ts | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/privacySources.test.ts | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/research/sources.ts | 27+++++++++++++++++++++++++++
Mumtool/package.json | 2+-
Mumtool/playwright.config.ts | 4++++
66 files changed, 4761 insertions(+), 113 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -53,6 +53,7 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `archilyzer reports to-manifest` | `<report.json> --out <manifest.json> [--channels-dir <dir>] [--site-origin <url>]` | a starter report-to-video manifest from a report (a chapter card per section, a claim's still and clips stamped with its verdict, its posts) | | `archilyzer source publish` | `[--force] [--check] [--keep-scratch]` | the scrubbed git mirror, raw tree, history pages (stagit, when installed) and tarball into homepage/public, behind the denied-literal gate (--check: audit and count, write nothing) | | `archilyzer source audit` | `[<git dir>]` | the denied-literal gate (+ gitleaks) over a git dir; default the published homepage/public/source/archilyzer.git | +| `archilyzer privacy audit` | `--denylist <file> [--scrub <file>] [--editor <url>] [--umtool <url>] [--settings <file>] [--max-per-route N] [--allow-unreached <pattern>[,…]] [--url <path>[,…]] [--strict] [--json]` | every page of a RUNNING editor and/or umtool (routes from their app/ dirs; dynamic ones from the links found), drawn by a browser with JavaScript off (ssr) and on (live) — the document, open shadow roots and same-origin frames — searched for the denied literals (plain, percent-encoded and JSON-escaped) in text nodes and joined element text, title/aria-label/alt/placeholder, field values, option labels, the title and the URL (links' hrefs warn only, unless --strict). NOT read: canvas, CSS content, hover-only or other-tab/query states, scripts (the browser's privacy rules carry the values they hide there). Names a literal by its line and length and a hit by route and selector, never by text; reports settings.privacy rules that do not compile (--settings, default this checkout's). --url adds paths to visit (a route that needs a query or an id no page links to; `editor /x` or `umtool /x` names the app). Exit 1 on a hit, 3 when INCOMPLETE (a page did not load or answered ≥ 400 — a static route that 404s without its query counts, whatever --allow-unreached says — a route not reached and not excused by --allow-unreached, or no page), 2 on usage. Point it at a fixture or your own instance; it reads only the files you name | | `archilyzer deploy site` | `<id> [--preview <branch>]` | alias: publish deploy &lt;id&gt; \[--preview &lt;branch&gt;\] — ship the site's bundle to its Pages project (default id: SITE\_ID) | | `archilyzer deploy hub` | `[--preview <branch>]` | alias: publish hub --deploy-only \[--preview &lt;branch&gt;\] — ship the hub's bundle to homepage.json's Pages project | | `archilyzer deploy homepage` | `[--preview <branch>]` | alias: publish homepage --deploy-only \[--preview &lt;branch&gt;\] — ship homepage/out to the Pages project archilyzer | diff --git a/SETTINGS.md b/SETTINGS.md @@ -60,6 +60,7 @@ A copied example PINS every default it spells — including each lane's `autoQue | [`jobs`](#jobs) | object — see below | | [`serviceCookies`](#servicecookies) | object — see below | | [`lookouts`](#lookouts) | object — see below | +| [`privacy`](#privacy) | object — see below | ## `adminTitle` @@ -1452,3 +1453,33 @@ Default: "items": [] } ``` + +## `privacy` + +What the editor's and umtool's pages SHOW of this machine (demo epic D4): local paths with the home directory as `~` or masked, the hostname as a fixed word, private sites left out of the pickers, e-mail addresses masked, and the operator's own display aliases in the source mirror's scrub format. Display only — nothing stored, logged, sent to a job or written to a record changes, and copy buttons copy the real path. Every default is today's behaviour: with the block absent or at its defaults the pages are byte-identical. `archilyzer privacy audit` checks the rendered pages against a denylist. Set with `pnpm ops settings --json '{"patch":{"privacy":{"displayPaths":"home"}}}'`. See PrivacySettings and common/lib/privacy/. + +#### `privacy` + +| Key | Default | Description | +|---|---|---| +| `displayPaths` | `"full"` | How a page shows a local path. `"full"` (default): as it is. `"home"`: the home directory as `~`, and the user's name in a removable-media mount (`/run/media/<user>/…`, `/media/<user>/…`) as `user`. `"masked"`: the home directory as `/home/user`, a storage location's root (and its volume's mountpoint) as `[<its label>]`, any other removable-media mount (`/media/<user>/<volume>`, `/run/media/…`, `/mnt/<uuid>`) as `/media/drive`, and a configured volume's UUID, in any case, as `[volume]`. Either mode also catches the path JSON-escaped (`\/home\/u`) and percent-encoded (`%2Fhome%2Fu`), and a `file://` URL keeps its shape (`file:///home/user/…`); a path ends at punctuation (`/home/u.` is the home dir, `/home/u.bak` is not). Display only: copy buttons copy the real path. While any key is on, the editor's and umtool's pages carry the rules their browser applies — the values they hide included — in the page's script payload (see `useSourceRules`). | +| `hideHost` | `false` | Show this machine's hostname (os.hostname(), its short form and ARCHILYZER_HOST_ID; three characters or more) as the word `host` wherever a page draws it as text. Matched whole-word, in any case, so a hostname inside another word is left alone (a hostname that is itself an ordinary word is replaced where it stands alone); links and other attributes a page needs to work are never rewritten. Default false. | +| `hideUser` | `false` | Show this account's user name (three characters or more) as the word `user` wherever a page draws it as a whole word, in any case — a log line's `by: … (name)`, a path segment under `/run/media/`. A name inside another word is left alone. Default false. | +| `hidePrivateSites` | `false` | Leave the sites marked private (site.json `audience: "private"`) out of the lists and pickers a page DRAWS: the editor's site-scope picker, /channels' Focus bar and a channel's site memberships (a hidden membership is still saved as it was), umtool's home, /projects, /work and its research source pickers (a project is hidden when it belongs to a private site's article). A private site that is the current choice is shown as "A private site". Only what is drawn: every lookup, default and allow-list keeps the private sites, so a case on a private site's source keeps reading it. Not access control: a private site's own pages still open by URL. An article's own `audience` is a different notion and hides nothing. If the sites cannot be read, umtool hides every site's pieces (fail closed). Default false. | +| `aliases` | `[]` | Display rules in the SOURCE MIRROR's scrub format (common/lib/scrubRuleLine.ts): one rule per entry — `lhs==>rhs` (literal), `literal:lhs==>rhs`, `regex:pattern==>rhs` (`\1` in rhs is group 1) or `glob:pattern==>rhs`; with no `==>` the match shows as `***REMOVED***`. Applied to displayed text after the path and host rules. A `regex:` or `glob:` rule must be cheap to run on every render: at most ONE unbounded or large quantifier (`*`, `+`, `{n,}`, `{n,m}` with m > 64, lazy forms too; it then repeats at most 256 times, and where the pattern could match past that the rest of the line is hidden), no backreference, no lookahead or lookbehind, no repeated group holding a quantifier or an alternation, at most four optional groups in a row, quantifier ranges and alternation branches multiplying to at most 1,024 and a match of at most 2,048 characters — so a glob has at most one `*`. A rule that breaks this, or does not compile, is not applied: it runs in FALLBACK — on each line holding one of its certain literal fragments (three characters or more that every match contains), the text from that fragment to the line's end (the whole line, where the fragment does not start the match) is shown as `[hidden]`; with no such fragment, every non-empty line is — and it is reported by its number in the server log and in `archilyzer privacy audit`. A rule that takes over 50 ms on one 4,096-character window is disabled into the same fallback for the rest of the process. One display call spends at most 150 ms on all operator rules together: past that, the text a rule has not read is shown as `[hidden]`, one per line (the rule stays on; the built-in path, host, user and e-mail rules always run on all of it). Rules run per line; a line over 4,096 characters is read in overlapping windows. Set with `pnpm ops settings --json '{"patch":{"privacy":{"aliases":["old==>new"]}}}'`. Default []. | +| `maskEmail` | `false` | Show every e-mail address a page draws as text as `[email]` (mailto links keep working). Default false. | +| `useSourceRules` | `false` | Also apply the source mirror's private rule files (SOURCE_SCRUB_FILE, default `~/.config/archilyzer/source-scrub.txt`, as aliases; SOURCE_DENYLIST_FILE's literals shown as `[hidden]`). Read by the SERVER only: their rules are applied where a page is rendered on the server and are never sent to a browser, a response, a log or an error (a client-rendered panel does not get them). A missing file is a server-log warning naming its path and error code, and nothing else — `archilyzer privacy audit` is the check that the rules took. Default false. AFTER TURNING PRIVACY ON, RELOAD THE OPEN PAGES: a client-rendered panel on a page already open stays unmasked until it is loaded again (a change while on, or turning it off, reaches them on the next navigation). NOTE, for every rule but these: the browser applies the rules itself, so the page it receives CARRIES the values they hide (the home dir, the hostname, the user name, the volume UUIDs and roots, each alias's left side) in its script payload — view-source shows them; the audit reads only what a page draws, not its scripts. | + +Default: + +```json +{ + "displayPaths": "full", + "hideHost": false, + "hideUser": false, + "hidePrivateSites": false, + "aliases": [], + "maskEmail": false, + "useSourceRules": false +} +``` diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -604,6 +604,39 @@ export const COMMANDS: Command[] = [ }, }, { + path: ["privacy", "audit"], + usage: + "--denylist <file> [--scrub <file>] [--editor <url>] [--umtool <url>] [--settings <file>] [--max-per-route N] [--allow-unreached <pattern>[,…]] [--url <path>[,…]] [--strict] [--json] every page of a RUNNING editor and/or umtool (routes from their app/ dirs; dynamic ones from the links found), drawn by a browser with JavaScript off (ssr) and on (live) — the document, open shadow roots and same-origin frames — searched for the denied literals (plain, percent-encoded and JSON-escaped) in text nodes and joined element text, title/aria-label/alt/placeholder, field values, option labels, the title and the URL (links' hrefs warn only, unless --strict). NOT read: canvas, CSS content, hover-only or other-tab/query states, scripts (the browser's privacy rules carry the values they hide there). Names a literal by its line and length and a hit by route and selector, never by text; reports settings.privacy rules that do not compile (--settings, default this checkout's). --url adds paths to visit (a route that needs a query or an id no page links to; `editor /x` or `umtool /x` names the app). Exit 1 on a hit, 3 when INCOMPLETE (a page did not load or answered ≥ 400 — a static route that 404s without its query counts, whatever --allow-unreached says — a route not reached and not excused by --allow-unreached, or no page), 2 on usage. Point it at a fixture or your own instance; it reads only the files you name", + flags: { + denylist: "string", + scrub: "string", + editor: "string", + umtool: "string", + settings: "string", + "max-per-route": "string", + "allow-unreached": "string", + url: "string", + strict: "boolean", + json: "boolean", + }, + run: async ({ flags }) => { + const str = (k: string) => (typeof flags[k] === "string" ? (flags[k] as string) : undefined); + const n = str("max-per-route"); + return (await import("./privacy-audit")).main({ + denylist: str("denylist"), + scrub: str("scrub"), + editor: str("editor"), + umtool: str("umtool"), + settings: str("settings"), + maxPerRoute: n !== undefined && Number.isFinite(Number(n)) && Number(n) > 0 ? Math.floor(Number(n)) : undefined, + allowUnreached: (str("allow-unreached") ?? "").split(",").map((x) => x.trim()).filter(Boolean), + seedPaths: (str("url") ?? "").split(",").map((x) => x.trim()).filter(Boolean), + strict: flags.strict === true, + json: flags.json === true, + }); + }, + }, + { path: ["deploy", "site"], usage: "<id> [--preview <branch>] alias: publish deploy <id> [--preview <branch>] — ship the site's bundle to its Pages project (default id: SITE_ID)", diff --git a/common/bin/privacy-audit.ts b/common/bin/privacy-audit.ts @@ -0,0 +1,129 @@ +// `archilyzer privacy audit` — the privacy audit (lib/privacy/audit.ts) over a +// running editor and/or umtool, against a denylist the caller names. +// +// archilyzer privacy audit --editor <url> --umtool <url> --denylist <file> +// [--scrub <file>] [--settings <file>] [--max-per-route N] [--strict] [--json] +// [--allow-unreached <pattern>[,<pattern>…]] [--url <path>[,<path>…]] +// +// The literals are the denylist's lines (`i:` = any case) plus, with --scrub, +// every scrub rule's literal left side — the source mirror's two formats, read +// by its own parsers. `--settings` (default: the settings file this checkout +// reads) is compiled the way the apps compile it, so a privacy rule that does +// not compile is reported by its number. Exit 0 clean and complete, 1 hits, +// 2 usage, 3 incomplete (a page did not load or answered ≥ 400, a route was +// not reached and not excused by --allow-unreached, or no page was audited). +// +// It runs against the URLs it is given and nothing else. The report names a +// literal by its line and length, never by its characters. + +import { readFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { getPaths } from "../lib/paths"; +import { settingsFromFile } from "../lib/settings"; +import { parseDenylist, dedupeLiterals, type Literal } from "../publish/sourceAudit"; +import { parseScrubRules } from "../publish/source"; +import { compilePrivacy, problemLine } from "../lib/privacy/compile"; +import { hostnames, tildify } from "../lib/privacy/privacy-server"; +import { auditExitCode, formatPrivacyReport, privacyReportJson, runPrivacyAudit, type AuditBrowser, type AuditTarget } from "../publish/privacyAudit"; +import { importPlaywright } from "../social/playwrightRuntime"; + +export type PrivacyAuditCliOpts = { + editor?: string; + umtool?: string; + denylist?: string; + scrub?: string; + settings?: string; + maxPerRoute?: number; + strict?: boolean; + json?: boolean; + allowUnreached?: string[]; + seedPaths?: string[]; + log?: (line: string) => void; +}; + +/** The literal list from the two files (either may be absent). */ +export function auditLiterals(opts: { denylist?: string; scrub?: string }): Literal[] { + const list: Literal[] = []; + if (opts.denylist) list.push(...parseDenylist(readFileSync(opts.denylist, "utf8"))); + if (opts.scrub) { + // "/" as the home dir: the built-in home rule is the apps' displayPaths + // business, and a denylist that wants the home dir names it. + const scrub = parseScrubRules(readFileSync(opts.scrub, "utf8"), "/"); + list.push(...scrub.denied.map((d) => ({ bytes: Buffer.from(d.text, "utf8"), ci: false, from: d.from }))); + } + return dedupeLiterals(list); +} + +/** What the target's settings.privacy would report about its own rules. */ +export function ruleProblemsOf(settingsFile: string): string[] { + try { + const s = settingsFromFile(settingsFile); + const paths = getPaths(); + const read = (f: string) => { + try { + return readFileSync(f, "utf8"); + } catch { + return null; + } + }; + const { problems } = compilePrivacy({ + privacy: s.privacy, + homeDir: os.homedir(), + hostnames: hostnames(), + locations: s.storage.locations, + scrubText: s.privacy.useSourceRules ? read(paths.sourceScrubFile) : null, + denyText: s.privacy.useSourceRules ? read(paths.sourceDenylistFile) : null, + }); + return problems.map(problemLine); + } catch { + return []; + } +} + +export async function main(opts: PrivacyAuditCliOpts): Promise<number> { + const log = opts.log ?? ((l: string) => console.log(l)); + if (!opts.editor && !opts.umtool) { + log("privacy audit: name at least one of --editor <url> / --umtool <url>"); + return 2; + } + if (!opts.denylist && !opts.scrub) { + log("privacy audit: name the literals: --denylist <file> (and/or --scrub <file>)"); + return 2; + } + let literals: Literal[]; + try { + literals = auditLiterals(opts); + } catch (err) { + // A read error names the file by path; a scrub refusal by line number. + const e = err as NodeJS.ErrnoException; + log(`privacy audit: ${e.code ? `cannot read ${tildify(e.path ?? "")} (${e.code})` : e.message}`); + return 2; + } + if (!literals.length) { + log("privacy audit: the denylist names no literal"); + return 2; + } + const root = getPaths().monorepoRoot; + const targets: AuditTarget[] = []; + if (opts.editor) targets.push({ app: "editor", baseUrl: opts.editor, appDir: path.join(root, "editor", "app") }); + if (opts.umtool) targets.push({ app: "umtool", baseUrl: opts.umtool, appDir: path.join(root, "umtool", "app") }); + const { chromium } = await importPlaywright(); + const browser = await chromium.launch({ headless: true }); + try { + const result = await runPrivacyAudit({ + targets, + literals, + browser: browser as unknown as AuditBrowser, + maxPerRoute: opts.maxPerRoute, + ruleProblems: ruleProblemsOf(opts.settings ?? getPaths().settingsFile), + allowUnreached: opts.allowUnreached, + seedPaths: opts.seedPaths, + }); + if (opts.json) log(JSON.stringify(privacyReportJson(result, literals, { strict: opts.strict }), null, 2)); + else for (const l of formatPrivacyReport(result, literals, { strict: opts.strict })) log(l); + return auditExitCode(result, opts.strict); + } finally { + await browser.close(); + } +} diff --git a/common/components/PrivacyProvider.tsx b/common/components/PrivacyProvider.tsx @@ -0,0 +1,57 @@ +"use client"; + +// THE BROWSER'S DISPLAYERS (demo epic D4): `useDisplay()` gives a client +// component the same `displayPath` / `displayText` pair the server has +// (lib/privacy/privacy-server.ts), bound to the rules the root layout hands +// <PrivacyProvider> — `clientPrivacyRules()`, which never holds a rule from +// the operator's private files (those apply only where a page renders on the +// server). +// +// No provider, no rules: the identity. The root layouts render the provider +// ONLY while settings.privacy is active, so a page with the block absent +// carries no extra element and no extra prop. +// +// KEEPING THE RULES CURRENT (review round 1, S8a). A client-side navigation +// does not re-render the root layout, so a changed `privacy` block would +// leave client panels on the old rules. While the provider is mounted, a +// navigation asks the router to refresh (at most once every REFRESH_MS), +// which re-renders the layout with the rules as they are now — a change, or +// privacy turned OFF, reaches the client panels on the next page. Turning it +// ON from off reaches them at the next full load (in the editor, also at its +// auto-refresh tick, which re-renders the layout too). +// +// The rules here CARRY the values they hide (the home dir, the hostname, the +// user name, the volume UUIDs and roots, every alias's left side): they are +// in the page's script payload, which view-source shows. The audit reads only +// what is drawn. SETTINGS.md says so too. + +import { createContext, useContext, useEffect, useMemo, useRef, type ReactNode } from "react"; +import { usePathname, useRouter } from "next/navigation"; +import { displayersOf, IDENTITY, type PrivacyRules } from "../lib/privacy/display"; + +const PrivacyContext = createContext<PrivacyRules | null>(null); + +export const REFRESH_MS = 10_000; + +export function PrivacyProvider({ rules, children }: { rules: PrivacyRules; children: ReactNode }) { + const router = useRouter(); + const pathname = usePathname(); + const first = useRef(true); + const last = useRef(0); + useEffect(() => { + if (first.current) { + first.current = false; + last.current = Date.now(); + return; + } + if (Date.now() - last.current < REFRESH_MS) return; + last.current = Date.now(); + router.refresh(); + }, [pathname, router]); + return <PrivacyContext.Provider value={rules}>{children}</PrivacyContext.Provider>; +} + +export function useDisplay(): typeof IDENTITY { + const rules = useContext(PrivacyContext); + return useMemo(() => displayersOf(rules), [rules]); +} diff --git a/common/lib/privacy/compile.ts b/common/lib/privacy/compile.ts @@ -0,0 +1,513 @@ +// settings.privacy → the rule list the displayers apply (display.ts). Pure: +// the server (privacy-server.ts) and `archilyzer privacy audit` hand it what +// they read — the settings block, the home dir, the hostnames, the storage +// locations and, only when `useSourceRules` is on, the TEXT of the operator's +// two private rule files — and it answers rules plus problems. +// +// THE ORDER IS THE SOURCE MIRROR'S: the path rules first (as the mirror's +// built-in home rule is first), then the host, then the operator's aliases, +// then the private scrub rules and the denylist, then e-mail addresses. +// +// A PROBLEM NEVER QUOTES A RULE. It names the rule's source and line number +// ("aliases line 3", "scrub line 2", as sourceAudit.ts names a literal) and +// what is wrong; a RegExp's own error message is never kept, because V8's +// quotes the pattern. +// +// FAIL CLOSED. A regex or glob that does not compile, or that could backtrack +// without bound (a quantified group holding a quantifier or an alternation, +// or more than two unbounded quantifiers), is not applied — its LITERAL +// FRAGMENTS (runs of three or more plain characters) are shown as `[hidden]` +// instead, and the problem is reported by number. + +import { DEFAULT_PRIVACY_SETTINGS, PRIVACY_ALIAS_MAX_CHARS, type PrivacySettings } from "../privacySettings"; +import { SCRUB_REMOVED, isScrubSkip, operatorLines, splitScrubLine, type ScrubLine } from "../scrubRuleLine"; +import type { PrivacyRules, PrivacyStep } from "./display"; +import { analyzeRegex } from "./regexSafety"; + +/** The home dir in "masked" mode: the source mirror's HOME_REPLACEMENT. */ +export const MASKED_HOME = "/home/user"; +export const HOST_WORD = "host"; +export const EMAIL_WORD = "[email]"; +export const HIDDEN_WORD = "[hidden]"; +export const DRIVE_WORD = "/media/drive"; +export const VOLUME_WORD = "[volume]"; +export const USER_WORD = "user"; + +export type PrivacyLocation = { + id: string; + label: string; + root: string; + volume?: { uuid?: string; mountpoint?: string }; +}; + +export type PrivacyCompileInput = { + privacy: PrivacySettings | null | undefined; + homeDir: string; + hostnames: readonly string[]; + // The account's name (os.userInfo().username); default the home dir's last segment. + username?: string | null; + locations: readonly PrivacyLocation[]; + // The private files' text, read by the server only when useSourceRules. + scrubText?: string | null; + denyText?: string | null; +}; + +export type PrivacyProblem = { source: "aliases" | "scrub" | "denylist"; line: number; what: string }; + +export function problemLine(p: PrivacyProblem): string { + return `${p.source} line ${p.line}: ${p.what}`; +} + +export const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&"); +const escapeReplacement = (s: string) => s.replace(/\$/g, "$$$$"); + +// After a path: not more of a name. Before a hostname: not part of a word. +// A path ends where a name cannot go on: `/home/u.` and `/home/u,` end at +// the punctuation, `/home/u.bak` and `/home/u2` are other names. +const PATH_END = "(?![A-Za-z0-9_-]|\\.[A-Za-z0-9_-])"; +const WORD_START = "(?<![A-Za-z0-9_-])"; +const WORD_END = "(?![A-Za-z0-9_-])"; + +/** Python `re.sub` template → a JS replacement string. */ +export function pythonReplacement(rhs: string): string { + let out = ""; + for (let i = 0; i < rhs.length; i++) { + const c = rhs[i]; + if (c === "$") { + out += "$$"; + continue; + } + if (c !== "\\" || i === rhs.length - 1) { + out += c; + continue; + } + const rest = rhs.slice(i + 1); + const g = /^g<([A-Za-z_][A-Za-z0-9_]*|\d+)>/.exec(rest); + if (g) { + out += /^\d+$/.test(g[1]) ? `$${g[1]}` : `$<${g[1]}>`; + i += g[0].length; + continue; + } + const d = /^\d{1,2}/.exec(rest); + if (d) { + out += `$${d[0]}`; + i += d[0].length; + continue; + } + const e = rest[0]; + out += e === "n" ? "\n" : e === "t" ? "\t" : e === "\\" ? "\\" : `\\${e}`; + i += 1; + } + return out; +} + +/** A Python regex as a JS source + flags, or null when it uses what JS lacks. */ +export function pythonRegex(src: string): { re: string; flags: string } | null { + let flags = "g"; + let re = src; + const lead = /^\(\?([aiLmsux]+)\)/.exec(re); + if (lead) { + for (const f of lead[1]) { + if (f === "i" || f === "m" || f === "s") flags += f; + else if (f !== "u" && f !== "a") return null; + } + re = re.slice(lead[0].length); + } + re = re + .replace(/\(\?P<([A-Za-z_][A-Za-z0-9_]*)>/g, "(?<$1>") + .replace(/\(\?P=([A-Za-z_][A-Za-z0-9_]*)\)/g, "\\k<$1>") + .replace(/\\A/g, "^") + .replace(/\\Z/g, "$"); + if (/\(\?[aiLmsux]+\)/.test(re)) return null; + return { re, flags: [...new Set(flags)].join("") }; +} + +/** fnmatch.translate, as git-filter-repo uses it for `glob:`. */ +export function globRegex(glob: string): string { + let out = ""; + for (let i = 0; i < glob.length; i++) { + const c = glob[i]; + if (c === "*") out += ".*"; + else if (c === "?") out += "."; + else if (c === "[") { + const j = glob.indexOf("]", i + 2); + if (j === -1) out += "\\["; + else { + let body = glob.slice(i + 1, j).replace(/\\/g, "\\\\"); + if (body.startsWith("!")) body = `^${body.slice(1)}`; + else if (body.startsWith("^")) body = `\\${body}`; + out += `[${body}]`; + i = j; + } + } else out += escapeRegExp(c); + } + return out; +} + +/** + * Would regexSafety.ts refuse this JS regex source? (The rule, M1 of the + * review: one unbounded-or-large quantifier at most, no backreference, no + * repeated group holding a quantifier or an alternation, a bounded range + * product and match length.) + */ +export function riskyRegex(re: string): boolean { + return !analyzeRegex(re).ok; +} + +export type Fragment = { text: string; lead: boolean }; + +/** + * The CERTAIN literal fragments of a regex or glob (review round 3, M2): runs + * of three or more plain characters that EVERY match contains — outside + * character classes, quantifier bodies, group syntax and escapes, not made + * optional by a quantifier, not in a branch of an alternation. `lead`: the + * fragment is where every match starts (nothing variable before it), so a + * match containing it starts there. A rule in fallback (display.ts) hides, + * on each line where a fragment occurs, from a leading one to the end of the + * line — or the WHOLE line for a fragment that is not leading; a rule with no + * certain fragment hides every non-empty line it runs on. + */ +export function certainFragments(pattern: string, kind: "regex" | "glob"): Fragment[] { + if (kind === "glob") { + const out: Fragment[] = []; + let run = ""; + let runAt = 0; + const flush = () => { + if (run.length >= 3) out.push({ text: run, lead: runAt === 0 }); + run = ""; + }; + for (let i = 0; i < pattern.length; i++) { + const c = pattern[i]; + if (c === "*" || c === "?" || c === "[") { + flush(); + if (c === "[") { + const j = pattern.indexOf("]", i + 2); + if (j === -1) break; + i = j; + } + continue; + } + if (run === "") runAt = i; + run += c; + } + flush(); + return dedupeFragments(out); + } + type Frame = { runs: Array<Fragment & { pos: number }>; alt: boolean }; + const stack: Frame[] = [{ runs: [], alt: false }]; + let run = ""; + let runAt = -1; + // Where the first matched character of the pattern is (after any leading + // `^` and group openings): a fragment there leads every match. + let leadAt = -1; + let variableSeen = false; + const top = () => stack[stack.length - 1]; + const flush = () => { + if (run.length >= 3) top().runs.push({ text: run, lead: runAt === leadAt && !variableSeen, pos: runAt }); + run = ""; + }; + const quantAfter = (i: number): { min: number; len: number } | null => { + const c = pattern[i]; + let q: { min: number; len: number } | null = null; + if (c === "*") q = { min: 0, len: 1 }; + else if (c === "+") q = { min: 1, len: 1 }; + else if (c === "?") q = { min: 0, len: 1 }; + else if (c === "{") { + const m = /^\{(\d+)(,\d*)?\}/.exec(pattern.slice(i)); + if (m) q = { min: Number(m[1]), len: m[0].length }; + } + if (q && pattern[i + q.len] === "?") q.len++; + return q; + }; + for (let i = 0; i < pattern.length; i++) { + const c = pattern[i]; + if (c === "\\") { + flush(); + variableSeen = true; + if (leadAt === -1) leadAt = -2; + const n = pattern[i + 1]; + i += n === "x" ? 3 : n === "u" ? (pattern[i + 2] === "{" ? Math.max(1, pattern.indexOf("}", i) - i) : 5) : 1; + const q = quantAfter(i + 1); + if (q) i += q.len; + continue; + } + if (c === "[") { + flush(); + if (leadAt === -1) leadAt = -2; + variableSeen = true; + let j = i + 1; + if (pattern[j] === "^") j++; + if (pattern[j] === "]") j++; + while (j < pattern.length && pattern[j] !== "]") j += pattern[j] === "\\" ? 2 : 1; + i = j; + const q = quantAfter(i + 1); + if (q) i += q.len; + continue; + } + if (c === "(") { + flush(); + const m = /^\(\?(?::|=|!|<=|<!|<[A-Za-z_][A-Za-z0-9_]*>)/.exec(pattern.slice(i)); + i += m ? m[0].length - 1 : 0; + stack.push({ runs: [], alt: false }); + continue; + } + if (c === ")") { + flush(); + const f = stack.length > 1 ? stack.pop()! : { runs: [], alt: false }; + const q = quantAfter(i + 1); + if (q) i += q.len; + // Kept only when every match goes through the group's text. + if (!f.alt && !(q && q.min === 0)) top().runs.push(...f.runs); + else variableSeen = true; + continue; + } + if (c === "|") { + flush(); + top().alt = true; + continue; + } + if (c === "." || c === "^" || c === "$") { + flush(); + if (c === ".") { + variableSeen = true; + if (leadAt === -1) leadAt = -2; + const q = quantAfter(i + 1); + if (q) i += q.len; + } + continue; + } + const q = quantAfter(i + 1); + if (q) { + // The character before a quantifier: optional (min 0) is not certain; + // a repeat ends the run (`ab+c` holds "ab", then "c"). + if (run === "" && leadAt === -1) leadAt = i; + if (run === "") runAt = i; + if (q.min > 0) run += c; + flush(); + variableSeen = true; + i += q.len; + continue; + } + if (leadAt === -1) leadAt = i; + if (run === "") runAt = i; + run += c; + } + flush(); + // An unclosed group (a rule that does not compile): its text counts. + while (stack.length > 1) { + const f = stack.pop()!; + if (!f.alt) top().runs.push(...f.runs); + } + if (stack[0].alt) return []; + return dedupeFragments(stack[0].runs.map(({ text, lead }) => ({ text, lead }))); +} + +function dedupeFragments(list: Fragment[]): Fragment[] { + const seen = new Map<string, Fragment>(); + for (const f of list) { + const prev = seen.get(f.text); + if (!prev) seen.set(f.text, { ...f }); + else prev.lead = prev.lead || f.lead; + } + return [...seen.values()]; +} + +/** The certain fragments' texts (the probes' and the tests' view). */ +export function literalFragments(pattern: string, kind: "regex" | "glob"): string[] { + return certainFragments(pattern, kind).map((f) => f.text); +} + +type LineSource = "aliases" | "scrub"; + +function compileScrubLine( + line: ScrubLine, + where: { source: LineSource; n: number; tooLong?: boolean }, + secret: boolean, + steps: PrivacyStep[], + problems: PrivacyProblem[], +): void { + const mark = secret ? ({ secret: true } as const) : {}; + const why = `${where.source} line ${where.n}`; + const hideFragments = (what: string) => { + const frags: Fragment[] = + line.kind === "regex" || line.kind === "glob" + ? certainFragments(line.pattern, line.kind) + : line.pattern.length >= 3 + ? [{ text: line.pattern, lead: true }] + : []; + problems.push({ + source: where.source, + line: where.n, + what: `${what}; ${ + frags.length + ? `it runs in fallback: on every line holding one of its ${frags.length} certain literal fragment${frags.length === 1 ? "" : "s"}, the text from that fragment (or the whole line, where the fragment does not start the match) is shown as [hidden]` + : "it runs in fallback: it has no certain literal fragment, so every line it would run on is shown as [hidden]" + }`, + }); + // A REFUSED step: display.ts never runs its pattern, only its fallback — + // the fragments, or the whole line when there are none (never a no-op). + steps.push({ + re: "(?!)", + flags: "g", + to: HIDDEN_WORD, + why: `${why} (fallback)`, + bounded: true, + refused: true, + fallback: frags.map((f) => ({ re: escapeRegExp(f.text), lead: f.lead })), + ...mark, + }); + }; + if (where.tooLong) return hideFragments(`is longer than ${PRIVACY_ALIAS_MAX_CHARS.toLocaleString("en-US")} characters`); + if (line.kind === "plain" || line.kind === "literal") { + steps.push({ + re: escapeRegExp(line.pattern), + flags: "g", + to: line.replacement === null ? SCRUB_REMOVED : escapeReplacement(line.replacement), + why, + ...mark, + }); + return; + } + const js = line.kind === "glob" ? { re: globRegex(line.pattern), flags: "gs" } : pythonRegex(line.pattern); + if (!js) return hideFragments(`does not compile (${line.kind}: a Python-only construct)`); + try { + new RegExp(js.re, js.flags); + } catch { + return hideFragments(`does not compile (${line.kind})`); + } + const verdict = analyzeRegex(js.re); + if (!verdict.ok) return hideFragments(`is refused as possibly slow (${line.kind}: ${verdict.why})`); + try { + new RegExp(verdict.source, js.flags); + } catch { + return hideFragments(`does not compile (${line.kind})`); + } + const to = line.replacement === null ? SCRUB_REMOVED : line.kind === "regex" ? pythonReplacement(line.replacement) : escapeReplacement(line.replacement); + // What the rule falls back to if display.ts finds it slow at run time. + const fallback = certainFragments(line.pattern, line.kind).map((f) => ({ re: escapeRegExp(f.text), lead: f.lead })); + steps.push({ + re: verdict.source, + flags: js.flags, + to, + why, + bounded: true, + maxLen: verdict.maxLen, + fallback, + ...(verdict.capTrigger !== null ? { capAt: verdict.capTrigger } : {}), + ...(verdict.capProbe !== null ? { capProbe: verdict.capProbe } : {}), + ...mark, + }); +} + +function compileScrubLines( + lines: readonly string[], + source: LineSource, + secret: boolean, + steps: PrivacyStep[], + problems: PrivacyProblem[], +): void { + lines.forEach((raw, i) => { + if (isScrubSkip(raw)) return; + const split = splitScrubLine(raw, i + 1); + if (!split.ok) { + problems.push({ source, line: i + 1, what: "has an empty left side; it matches nothing" }); + return; + } + // The aliases' own cap (the sanitizer drops a longer alias) holds for a + // scrub-file line too: a longer one runs in fallback only. + compileScrubLine(split.line, { source, n: i + 1, tooLong: raw.length > PRIVACY_ALIAS_MAX_CHARS }, secret, steps, problems); + }); +} + +/** The denylist's line format (sourceAudit.ts parseDenylist): `i:` = any case. */ +function compileDenylist(text: string, steps: PrivacyStep[]): void { + operatorLines(text).forEach((raw, i) => { + const line = raw.trim(); + if (line === "" || line.startsWith("#")) return; + const ci = line.startsWith("i:"); + const lit = ci ? line.slice(2).trim() : line; + if (!lit) return; + steps.push({ re: escapeRegExp(lit), flags: ci ? "gi" : "g", to: HIDDEN_WORD, why: `denylist line ${i + 1}`, secret: true }); + }); +} + +const cleanPath = (p: string | undefined) => (p ?? "").trim().replace(/\/+$/, ""); + +// A path's own forms as a page may carry them: plain, JSON-escaped +// (`\/home\/u`) and percent-encoded (`%2Fhome%2Fu`, either case). +function pathForms(p: string): Array<{ re: string; flags: string; enc: (s: string) => string }> { + const json = p.replace(/\//g, "\\/"); + const pct = p.replace(/\//g, "%2F"); + const out: Array<{ re: string; flags: string; enc: (s: string) => string }> = [ + { re: escapeRegExp(p), flags: "g", enc: (s) => s }, + ]; + if (json !== p) out.push({ re: escapeRegExp(json), flags: "g", enc: (s) => s.replace(/\//g, "\\/") }); + if (pct !== p) out.push({ re: escapeRegExp(pct).replace(/%2F/g, "%2[Ff]"), flags: "g", enc: (s) => s.replace(/\//g, "%2F") }); + return out; +} + +export function compilePrivacy(input: PrivacyCompileInput): { rules: PrivacyRules | null; problems: PrivacyProblem[] } { + const p = input.privacy ?? DEFAULT_PRIVACY_SETTINGS; + const steps: PrivacyStep[] = []; + const problems: PrivacyProblem[] = []; + const home = cleanPath(input.homeDir); + const homeOk = home.length > 1 && home !== MASKED_HOME; + // The user's name as the home dir and the media mounts spell it. + const user = (input.username ?? (homeOk ? home.split("/").pop() : "") ?? "").trim(); + + if (p.displayPaths === "masked") { + const roots: Array<{ root: string; label: string }> = []; + for (const l of input.locations) { + const label = (l.label || l.id).trim(); + for (const r of [cleanPath(l.root), cleanPath(l.volume?.mountpoint)]) { + if (r.length > 1 && label) roots.push({ root: r, label }); + } + } + roots.sort((a, b) => b.root.length - a.root.length); + const seen = new Set<string>(); + for (const r of roots) { + if (seen.has(r.root)) continue; + seen.add(r.root); + for (const f of pathForms(r.root)) { + steps.push({ re: f.re + PATH_END, flags: f.flags, to: escapeReplacement(`[${r.label}]`), why: "location root" }); + } + } + } + if (p.displayPaths !== "full" && homeOk) { + // A file:// URL keeps a path's shape in either mode: `file:///home/user/…`. + steps.push({ re: `file://${escapeRegExp(home)}${PATH_END}`, flags: "g", to: `file://${MASKED_HOME}`, why: "home dir (file url)" }); + for (const f of pathForms(home)) { + steps.push({ re: f.re + PATH_END, flags: f.flags, to: escapeReplacement(f.enc(p.displayPaths === "home" ? "~" : MASKED_HOME)), why: "home dir" }); + } + } + if (p.displayPaths === "masked") { + steps.push({ re: "(?:/run)?/media/[^/\\s\"'<>]+/[^/\\s\"'<>]+", flags: "g", to: DRIVE_WORD, why: "removable-media mount" }); + steps.push({ re: "/mnt/[0-9A-Fa-f]{4,}(?:-[0-9A-Fa-f]{2,})+" + PATH_END, flags: "g", to: DRIVE_WORD, why: "uuid mount" }); + const uuids = [...new Set(input.locations.map((l) => (l.volume?.uuid ?? "").trim()).filter((u) => u.length >= 4))]; + for (const u of uuids) steps.push({ re: `(?<![0-9A-Za-z-])${escapeRegExp(u)}(?![0-9A-Za-z-])`, flags: "gi", to: VOLUME_WORD, why: "volume uuid" }); + } else if (p.displayPaths === "home" && user.length >= 1) { + // "home": a removable-media mount names the user too — that segment only. + steps.push({ re: `(/(?:run/)?media/)${escapeRegExp(user)}(?=/|$)`, flags: "g", to: "$1user", why: "media mount user" }); + } + if (p.hideHost) { + const names = [...new Set(input.hostnames.flatMap((h) => [h.trim(), h.trim().split(".")[0]]))] + .filter((h) => h.length >= 3 && h.toLowerCase() !== "localhost" && h.toLowerCase() !== HOST_WORD) + .sort((a, b) => b.length - a.length); + if (names.length) { + steps.push({ re: `${WORD_START}(?:${names.map(escapeRegExp).join("|")})${WORD_END}`, flags: "gi", to: HOST_WORD, why: "hostname" }); + } + } + if (p.hideUser && user.length >= 3 && user.toLowerCase() !== USER_WORD) { + steps.push({ re: `${WORD_START}${escapeRegExp(user)}${WORD_END}`, flags: "gi", to: USER_WORD, why: "user name" }); + } + compileScrubLines(p.aliases, "aliases", false, steps, problems); + if (p.useSourceRules) { + if (input.scrubText) compileScrubLines(operatorLines(input.scrubText), "scrub", true, steps, problems); + if (input.denyText) compileDenylist(input.denyText, steps); + } + if (p.maskEmail) { + // Linear, by code (display.ts maskEmails): no regex scans for it. + steps.push({ re: "@", flags: "g", to: EMAIL_WORD, why: "e-mail", kind: "email" }); + } + return { rules: steps.length ? { v: 1, steps } : null, problems }; +} diff --git a/common/lib/privacy/display.test.ts b/common/lib/privacy/display.test.ts @@ -0,0 +1,168 @@ +// The displayers' engine and compiler (demo epic D4): identity at the +// defaults, the path / host / alias / e-mail rules, fail-closed broken rules, +// the regex bound, and secret steps kept off the client. +// +// Run with: node_modules/.bin/tsx --test common/lib/privacy/display.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { DEFAULT_PRIVACY_SETTINGS, sanitizePrivacy, privacyActive, type PrivacySettings } from "../privacySettings"; +import { compilePrivacy, literalFragments, pythonReplacement, riskyRegex, type PrivacyCompileInput } from "./compile"; +import { applyPrivacy, displayersOf, IDENTITY, PRIVACY_REGEX_MAX_INPUT, publicRules } from "./display"; + +const HOME = "/home/someone"; +const base = (privacy: Partial<PrivacySettings>, extra: Partial<PrivacyCompileInput> = {}): PrivacyCompileInput => ({ + privacy: { ...DEFAULT_PRIVACY_SETTINGS, ...privacy }, + homeDir: HOME, + hostnames: ["boxen"], + locations: [{ id: "platter", label: "Platter", root: "/run/media/someone/1234-ABCD/archive", volume: { uuid: "1234-ABCD", mountpoint: "/run/media/someone/1234-ABCD" } }], + ...extra, +}); +const show = (privacy: Partial<PrivacySettings>, s: string, extra: Partial<PrivacyCompileInput> = {}) => + applyPrivacy(compilePrivacy(base(privacy, extra)).rules, s); + +const CORPUS = [ + `${HOME}/Projects/x/out.mp4`, + "held by pid 12 on boxen since 13:31", + "write to someone@example.com", + "/run/media/someone/1234-ABCD/archive/chan/media", + "", + "plain words", +]; + +test("defaults: no rules, and every displayer returns its input itself", () => { + assert.equal(privacyActive(DEFAULT_PRIVACY_SETTINGS), false); + assert.deepEqual(sanitizePrivacy(undefined), DEFAULT_PRIVACY_SETTINGS); + // Present but wrong is read STRICT, never as off (review round 1, S3). + assert.deepEqual(sanitizePrivacy({ displayPaths: "nope", hideHost: "yes", aliases: [1, "", "a==>b", "x\ny"] }), { + ...DEFAULT_PRIVACY_SETTINGS, + displayPaths: "masked", + hideHost: true, + aliases: ["a==>b", "xy"], + }); + const { rules, problems } = compilePrivacy(base({})); + assert.equal(rules, null); + assert.deepEqual(problems, []); + const d = displayersOf(rules); + assert.equal(d, IDENTITY); + for (const s of CORPUS) { + assert.equal(applyPrivacy(null, s), s); + assert.equal(d.displayPath(s), s); + assert.equal(d.displayText(s), s); + } +}); + +test("displayPaths home and masked; a longer name is not the home dir", () => { + assert.equal(show({ displayPaths: "home" }, `${HOME}/a`), "~/a"); + assert.equal(show({ displayPaths: "home" }, HOME), "~"); + assert.equal(show({ displayPaths: "home" }, `${HOME}x/a`), `${HOME}x/a`); + assert.equal(show({ displayPaths: "home" }, `${HOME}.bak`), `${HOME}.bak`); + assert.equal(show({ displayPaths: "masked" }, `see ${HOME}/a and ${HOME}`), "see /home/user/a and /home/user"); + // A trailing slash on the home dir is the same home dir. + assert.equal(show({ displayPaths: "home" }, `${HOME}/a`, { homeDir: `${HOME}/` }), "~/a"); + // A home of "/" (a container) rewrites nothing. + assert.equal(show({ displayPaths: "masked" }, "/srv/a", { homeDir: "/" }), "/srv/a"); +}); + +test("masked: a location root becomes its label (longest first), mounts and volume ids are hidden", () => { + const m = (s: string) => show({ displayPaths: "masked" }, s); + assert.equal(m("Media relocated to /run/media/someone/1234-ABCD/archive/chan/media."), "Media relocated to [Platter]/chan/media."); + assert.equal(m("/run/media/someone/1234-ABCD/other"), "[Platter]/other"); + assert.equal(m("/media/someone/USBSTICK/x"), "/media/drive/x"); + assert.equal(m("/mnt/0f3c2a1b-9d2e-4c11-8a77-0123456789ab/x"), "/media/drive/x"); + assert.equal(m("volume 1234-ABCD (ext4)"), "volume [volume] (ext4)"); + assert.equal(m("job 1234-ABCDE"), "job 1234-ABCDE"); + // "home" mode labels no root; the user's name in a media mount is `user`. + assert.equal(show({ displayPaths: "home" }, "/run/media/someone/1234-ABCD/archive/x"), "/run/media/user/1234-ABCD/archive/x"); +}); + +test("hideHost: whole word, any case, never inside another word", () => { + const h = (s: string, names = ["boxen"]) => show({ hideHost: true }, s, { hostnames: names }); + assert.equal(h("held on boxen since 13:31"), "held on host since 13:31"); + assert.equal(h("boxen.lan:3050"), "host.lan:3050"); + assert.equal(h("an oxen boxenly unboxen boxen-2 Boxen"), "an oxen boxenly unboxen boxen-2 host"); + // A hostname that is a common word is only replaced as that whole word. + assert.equal(h("the desk is a desktop; desk.", ["desk"]), "the host is a desktop; host."); + // The short form of a dotted name, and ARCHILYZER_HOST_ID-style extras. + assert.equal(h("on boxen and on boxen.example.org", ["boxen.example.org"]), "on host and on host"); + assert.equal(h("localhost:3001", ["localhost"]), "localhost:3001"); +}); + +test("aliases in the source mirror's four forms", () => { + const a = (aliases: string[], s: string) => show({ aliases }, s); + assert.equal(a(["secret-site==>demo-site"], "a secret-site b"), "a demo-site b"); + assert.equal(a(["literal:a.b==>c$1"], "xa.byaxb"), "xc$1yaxb"); + assert.equal(a(["regex:proj-(\\d+)==>project \\1"], "proj-42 proj-x"), "project 42 proj-x"); + assert.equal(a(["regex:(?P<w>sec)ret==>\\g<w>"], "secret"), "sec"); + assert.equal(a(["regex:(?i)ALPHA==>b"], "alpha Alpha"), "b b"); + assert.equal(a(["glob:priv*te==>p"], "a private b"), "a p b"); + assert.equal(a(["glob:p*e==>X"], "pie and pine"), "X"); + assert.equal(a(["glob:file?.txt==>f"], "file1.txt fileXX.txt"), "f fileXX.txt"); + assert.equal(a(["gone"], "is gone"), "is ***REMOVED***"); + assert.equal(a(["# comment", " ", "x==>y"], "x"), "y"); + assert.equal(pythonReplacement("a\\1$b\\g<2>\\n"), "a$1$$b$2\n"); +}); + +test("a broken or unbounded regex fails CLOSED: reported by number, its fragments hidden", () => { + const { rules, problems } = compilePrivacy(base({ aliases: ["ok==>fine", "regex:jeral(yzer-private==>x", "regex:(a+)+b==>c", "glob:x*y*z*w==>q"] })); + assert.deepEqual( + problems.map((p) => [p.source, p.line]), + [ + ["aliases", 2], + ["aliases", 3], + ["aliases", 4], + ], + ); + for (const p of problems) assert.ok(!/jeral|yzer|private/.test(p.what), "a problem never quotes the rule"); + // Rule 2's fragments are hidden; rule 3 has none, so every line it would run + // on is hidden whole (review round 2, M-C: a fallback is never a no-op). + assert.equal(applyPrivacy(rules, "ok jeralyzer-private"), "[hidden]"); + // Rule 2's certain fragments: "jeral" leads, "yzer-private" does not — a + // line holding a non-leading one is hidden whole (review round 3, M2). + const two = compilePrivacy(base({ aliases: ["ok==>fine", "regex:jeral(yzer-private==>x"] })); + assert.equal(applyPrivacy(two.rules, "ok jeralyzer-private"), "[hidden]"); + assert.equal(applyPrivacy(two.rules, "ok jeral then"), "fine [hidden]", "from a leading fragment to the line's end"); + assert.ok(riskyRegex("(a+)+")); + assert.ok(riskyRegex("(a|aa)*")); + assert.ok(riskyRegex("((ab)*c)+")); + assert.ok(riskyRegex("a*b*c*")); + assert.ok(!riskyRegex("proj-(\\d+)")); + assert.ok(!riskyRegex("(?:ab)?c+[x*+]")); + assert.ok(!riskyRegex("(a|b)?x")); + assert.deepEqual(literalFragments("jeral(yzer-private", "regex"), ["jeral", "yzer-private"]); + assert.deepEqual(literalFragments("abcd?ef", "regex"), ["abc"]); +}); + +test("an operator regex sees at most PRIVACY_REGEX_MAX_INPUT characters at a time", () => { + const rules = compilePrivacy(base({ aliases: ["regex:b(\\w)==>B\\1"] })).rules; + const long = "a".repeat(PRIVACY_REGEX_MAX_INPUT * 2 + 10) + "bc"; + const t0 = Date.now(); + assert.ok(applyPrivacy(rules, long).endsWith("aBc")); + assert.ok(Date.now() - t0 < 1000); + assert.equal(applyPrivacy(rules, "x bq\ny bz"), "x Bq\ny Bz"); +}); + +test("maskEmail", () => { + assert.equal(show({ maskEmail: true }, "mail a.b+c@mail.example.co.uk or x@y"), "mail [email] or x@y"); +}); + +test("useSourceRules: the files' rules are secret steps the client never gets", () => { + const input = base( + { useSourceRules: true, displayPaths: "home" }, + { scrubText: "\uFEFFMARKER-SCRUB==>alias\r\n# c\nregex:QQQ(ZZZ==>z\n", denyText: "MARKER-DENY\ni:marker-ci\n" }, + ); + const { rules, problems } = compilePrivacy(input); + assert.equal(applyPrivacy(rules, "MARKER-SCRUB MARKER-DENY Marker-CI"), "alias [hidden] [hidden]"); + assert.equal(applyPrivacy(rules, "x QQQZZZ"), "[hidden]", "the broken scrub rule's fallback: a line with a non-leading fragment, whole"); + assert.deepEqual(problems.map((p) => `${p.source}:${p.line}`), ["scrub:3"]); + assert.ok(!JSON.stringify(problems).includes("QQQ")); + assert.ok(!JSON.stringify(publicRules(rules)).includes("QQQ")); + const client = publicRules(rules); + assert.ok(client); + assert.ok(!JSON.stringify(client).includes("MARKER"), "no secret text reaches the client rules"); + assert.ok(!JSON.stringify(client).toLowerCase().includes("marker")); + assert.equal(applyPrivacy(client, `${HOME}/x`), "~/x"); + // Off: the files' text is not even compiled. + const off = compilePrivacy({ ...input, privacy: { ...input.privacy!, useSourceRules: false } }); + assert.ok(!JSON.stringify(off).includes("MARKER")); +}); diff --git a/common/lib/privacy/display.ts b/common/lib/privacy/display.ts @@ -0,0 +1,452 @@ +// THE DISPLAYERS' ENGINE (demo epic D4): a compiled rule list applied to a +// string a page is about to draw. Pure and client-safe — no node imports — so +// the editor and umtool call it on the server (privacy-server.ts) and in the +// browser (components/PrivacyProvider.tsx) alike. +// +// NULL RULES ARE THE IDENTITY: `applyPrivacy(null, s)` returns `s` itself, the +// same string, which is what keeps every page byte-identical while the +// `privacy` settings block is absent or at its defaults (compile.ts compiles +// null then). +// +// THREE KINDS OF STEP, three costs: +// - literal steps (paths, hostnames, a literal alias, a denylist line): one +// linear pass over the whole string; +// - the e-mail step: code, not a regex — every `@` is looked at once and the +// address around it walked by hand (maskEmails), linear in the input; +// - an OPERATOR's regex or glob (`bounded`): it passed regexSafety.ts's +// static rule, so its match is at most `maxLen` long. It runs per line in +// windows of PRIVACY_REGEX_MAX_INPUT that OVERLAP by more than `maxLen`; +// each window resumes where the last match ended, so the matches are the +// ones a whole-line scan would find and none straddling a cut is missed. +// A match long enough to have used its capped quantifier (`.*` is run as +// `.{0,256}`) to the cap hides the REST OF THE LINE with it. Each WINDOW +// is timed: a rule that ever takes longer than PRIVACY_RULE_SLOW_MS on one +// is disabled for the rest of the process and runs in FALLBACK, as a rule +// compile.ts refused does: its literal fragments shown as [hidden] — or, +// when it has none, every non-empty line it would run on. Never a no-op. +// `onSlowRule` hears it, by the rule's number. +// +// Display only. Nothing here is ever applied to a value that is stored, +// logged, sent to a job, written to a record, put in an href/src, or copied by +// a copy button. + +export type PrivacyStep = { + // A JS RegExp source and its flags (always global). + re: string; + flags: string; + // A JS replacement string ($1, $<name>, $$). + to: string; + // What the step is for, for a test, a warning or the audit: never its text. + why: string; + // From the operator's private rule files: never leaves the server. + secret?: true; + // An operator-written regex or glob: windowed, timed, disabled when slow. + bounded?: true; + // Its longest possible match (regexSafety.ts). + maxLen?: number; + // Its CERTAIN literal fragments (regex sources; compile.ts certainFragments) + // for when it runs in fallback: on a line holding one, the text from a + // leading fragment to the line's end — or the whole line, for a fragment + // that does not start every match — is shown as [hidden]; with none, every + // non-empty line it would run on is. + fallback?: Array<{ re: string; lead: boolean }>; + // Refused at compile time: its pattern never runs, only its fallback. + refused?: true; + // A match this long may have used its rewritten (capped) quantifier to the + // cap: the rest of the line is hidden with it (regexSafety.ts capTrigger). + capAt?: number; + // Where this matches, the operator's pattern may match PAST the cap: the + // line is hidden from there (regexSafety.ts capProbe). + capProbe?: string; + // Code rather than a regex: "email" masks addresses (re/flags unused). + kind?: "email"; +}; + +export type PrivacyRules = { v: 1; steps: PrivacyStep[] }; + +export type Displayer = (s: string) => string; + +/** The window an operator regex runs over at once (plus its overlaps). */ +export const PRIVACY_REGEX_MAX_INPUT = 4096; +/** One call of one operator rule longer than this disables the rule. */ +export const PRIVACY_RULE_SLOW_MS = 50; +export const HIDDEN = "[hidden]"; + +type Compiled = { + rx: RegExp; + to: string; + step: PrivacyStep; + bounded: boolean; + email: boolean; + overlap: number; + fallback: Array<{ rx: RegExp; lead: boolean }>; + capAt: number | null; + probe: RegExp | null; +}; + +const compiled = new WeakMap<PrivacyRules, Compiled[]>(); +// Rules disabled for being slow, for the rest of the process. +const disabled = new WeakSet<PrivacyStep>(); +let slowReporter: ((why: string, ms: number) => void) | null = null; + +/** Who hears that a rule was disabled (the server's log; the console otherwise). */ +export function onSlowRule(fn: ((why: string, ms: number) => void) | null): void { + slowReporter = fn; +} + +function stepsOf(rules: PrivacyRules): Compiled[] { + let c = compiled.get(rules); + if (!c) { + c = []; + for (const s of rules.steps) { + try { + const flags = s.flags.includes("g") ? s.flags : `${s.flags}g`; + c.push({ + rx: new RegExp(s.kind === "email" ? "@" : s.re, flags), + to: s.to, + step: s, + bounded: s.bounded === true, + email: s.kind === "email", + overlap: Math.max(64, (s.maxLen ?? 0) + 64), + capAt: typeof s.capAt === "number" ? s.capAt : null, + probe: s.capProbe ? new RegExp(s.capProbe, flags) : null, + fallback: (s.fallback ?? []).flatMap((f) => { + try { + return [{ rx: new RegExp(f.re, "g"), lead: f.lead === true }]; + } catch { + return []; + } + }), + }); + } catch { + // compile.ts only emits steps that compile; a hand-made rule list that + // does not is a programming error, and a step dropped here is one less + // rewrite — never an exception on a page. + } + } + compiled.set(rules, c); + } + return c; +} + +// ── e-mail, linear ─────────────────────────────────────────────────────────── + +// Character classes as lookup tables: 1 = a local-part character, 2 = a +// domain character (both: letters, digits, `.` and `-`). +const CLASS = new Uint8Array(128); +for (let c = 0; c < 128; c++) { + const ch = String.fromCharCode(c); + if (/[A-Za-z0-9.-]/.test(ch)) CLASS[c] = 3; + else if (/[_%+]/.test(ch)) CLASS[c] = 1; +} +const isLocal = (s: string, i: number) => { + const c = s.charCodeAt(i); + return c < 128 && (CLASS[c] & 1) !== 0; +}; +const isDomain = (s: string, i: number) => { + const c = s.charCodeAt(i); + return c < 128 && (CLASS[c] & 2) !== 0; +}; +const isAlpha = (c: number) => (c >= 65 && c <= 90) || (c >= 97 && c <= 122); + +/** Every e-mail address in `s` as `to`. Each character is looked at O(1) times. */ +export function maskEmails(s: string, to: string): string { + let at = s.indexOf("@"); + if (at === -1) return s; + const parts: string[] = []; + let pos = 0; // emitted up to here + let floor = 0; // a local part may not start before this + while (at !== -1) { + let a = at; + while (a > floor && at - a < 64 && isLocal(s, a - 1)) a--; + let b = at + 1; + let doubleDot = false; + while (b < s.length && b - at <= 253 && isDomain(s, b)) { + if (s.charCodeAt(b) === 46 && s.charCodeAt(b - 1) === 46) doubleDot = true; + b++; + } + let end = b; + // A domain never ends with a dot or a hyphen ("mail a@b.co." ends a sentence). + while (end > at + 1 && (s.charCodeAt(end - 1) === 46 || s.charCodeAt(end - 1) === 45)) end--; + let ok = a < at && end > at + 1 && !doubleDot; + if (ok) { + // The last label: 2–24 letters, after a dot that is not the domain's first character. + let t = end; + while (t > at + 1 && isAlpha(s.charCodeAt(t - 1))) t--; + const tld = end - t; + ok = tld >= 2 && tld <= 24 && t - 1 > at + 1 && s.charCodeAt(t - 1) === 46; + } + if (ok && a >= pos) { + parts.push(s.slice(pos, a), to); + pos = end; + floor = end; + } else { + floor = at + 1; + } + at = s.indexOf("@", Math.max(at + 1, floor)); + } + parts.push(s.slice(pos)); + return parts.join(""); +} + +// ── operator regexes, windowed ─────────────────────────────────────────────── + +/** One match's replacement, as String.replace builds it. */ +function applyTemplate(m: RegExpExecArray, to: string): string { + return to.replace(/\$(\$|&|\d{1,2}|<([^>]*)>)/g, (whole, t: string, name?: string) => { + if (t === "$") return "$"; + if (t === "&") return m[0]; + if (name !== undefined) return m.groups?.[name] ?? ""; + const n = Number(t); + if (n >= 1 && n < m.length) return m[n] ?? ""; + return whole; + }); +} + +/** What one displayText / displayPath call may spend on operator rules, in all. */ +export const PRIVACY_CALL_BUDGET_MS = 150; + +// One call's budget across every operator rule and window. +type Call = { deadline: number; spent: boolean }; + +class OutOfBudget extends Error { + constructor(readonly emitted: string) { + super("budget"); + } +} + +class Slow extends Error { + constructor(readonly ms: number) { + super("slow"); + } +} + +const now = () => (typeof performance !== "undefined" ? performance.now() : Date.now()); + +/** + * One line, in windows of PRIVACY_REGEX_MAX_INPUT that overlap by more than + * the rule's longest match. Each window resumes where the last match ended + * (rx.lastIndex), so the matches are the ones a whole-line scan finds; a match + * belongs to the window it starts in. A match long enough to have used the + * capped quantifier to its cap (capAt) hides the rest of the line with it. + * Each window is timed: one slower than PRIVACY_RULE_SLOW_MS throws Slow. + */ +function windows(line: string, overlap: number): Array<{ start: number; from: number; win: string; own0: number }> { + const W = PRIVACY_REGEX_MAX_INPUT; + const out = []; + for (let start = 0; start < line.length || start === 0; start += W) { + const from = Math.max(0, start - overlap); + out.push({ start, from, win: line.slice(from, start + W + overlap), own0: start - from }); + if (line.length === 0) break; + } + return out; +} + +/** Where the cap probe first matches in the line (the rule may match past its cap there), or null. */ +function probeAt(line: string, c: Compiled, call: Call): number | null { + if (!c.probe) return null; + const W = PRIVACY_REGEX_MAX_INPUT; + for (const w of windows(line, c.overlap)) { + // Out of the call's budget before the probe has looked everywhere: the + // line is hidden from the window it had not read (fail closed). + if (now() > call.deadline) { + call.spent = true; + return w.start; + } + const t0 = now(); + c.probe.lastIndex = w.own0; + const m = c.probe.exec(w.win); + const took = now() - t0; + if (took > PRIVACY_RULE_SLOW_MS) throw new Slow(took); + if (m && m.index < w.own0 + W) return w.from + m.index; + } + return null; +} + +function scanLine(line: string, c: Compiled, call: Call): string { + const W = PRIVACY_REGEX_MAX_INPUT; + const rx = c.rx; + const stopAt = probeAt(line, c, call); + let out = ""; + let pos = 0; + let rest = false; + for (const { from, win, own0 } of windows(line, c.overlap)) { + if (now() > call.deadline) { + // Out of the call's budget: what was read stays as it was drawn, the + // rest of this line is hidden. + call.spent = true; + throw new OutOfBudget(out + (line.slice(pos).trim() ? HIDDEN : line.slice(pos))); + } + rx.lastIndex = Math.max(0, pos - from); + const t0 = now(); + let m: RegExpExecArray | null; + let stop = false; + while ((m = rx.exec(win))) { + if (m[0] === "") { + rx.lastIndex++; + continue; + } + if (m.index >= own0 + W) break; // the next window's + const ms = from + m.index; + if (stopAt !== null && ms > stopAt) { + stop = true; + break; + } + out += line.slice(pos, ms) + applyTemplate(m, c.to); + pos = ms + m[0].length; + if (c.capAt !== null && m[0].length >= c.capAt) { + pos = line.length; + rest = true; + stop = true; + break; + } + if (stopAt !== null && ms === stopAt) { + stop = true; + break; + } + } + const took = now() - t0; + if (took > PRIVACY_RULE_SLOW_MS) throw new Slow(took); + if (stop) break; + } + if (stopAt !== null && !rest) { + // From the probe's match on, the line is hidden (whatever a match there + // already replaced stays replaced). + out += pos <= stopAt ? line.slice(pos, stopAt) + HIDDEN : HIDDEN; + return out; + } + return out + line.slice(pos); +} + +const hideLines = (lines: string[]) => lines.map((line) => (line.trim() ? HIDDEN : line)); + +/** Line by line; out of the call's budget, every line not yet read is hidden. */ +function boundedReplace(s: string, c: Compiled, call: Call): string { + const lines = s.split("\n"); + const out: string[] = []; + for (let i = 0; i < lines.length; i++) { + try { + out.push(scanLine(lines[i], c, call)); + } catch (err) { + if (!(err instanceof OutOfBudget)) throw err; + out.push(err.emitted, ...hideLines(lines.slice(i + 1))); + return out.join("\n"); + } + } + return out.join("\n"); +} + +/** + * A rule in FALLBACK (refused, or disabled for a slow window): on a line that + * holds one of its certain fragments, from a leading fragment's first + * occurrence to the line's end — or the whole line, for a fragment that does + * not start every match — is shown as [hidden]; a rule with no certain + * fragment hides every non-empty line. Never a no-op, never only the literal. + */ +function fallbackReplace(s: string, c: Compiled): string { + if (!c.fallback.length) return hideLines(s.split("\n")).join("\n"); + return s + .split("\n") + .map((line) => { + let from = -1; + for (const f of c.fallback) { + f.rx.lastIndex = 0; + const m = f.rx.exec(line); + if (!m) continue; + if (!f.lead) return HIDDEN; + if (from === -1 || m.index < from) from = m.index; + } + return from === -1 ? line : line.slice(0, from) + HIDDEN; + }) + .join("\n"); +} + +const budgetSaid = new Set<string>(); +let budgetReporter: ((why: string) => void) | null = null; + +/** Who hears that a rule ran out of a call's budget (once per rule per process). */ +export function onBudget(fn: ((why: string) => void) | null): void { + budgetReporter = fn; +} + +/** Forget which rules were told about the budget (tests). */ +export function resetBudgetNotes(): void { + budgetSaid.clear(); +} + +function runBounded(s: string, c: Compiled, call: Call): string { + if (c.step.refused || disabled.has(c.step)) return fallbackReplace(s, c); + const sayBudget = () => { + if (budgetSaid.has(c.step.why)) return; + budgetSaid.add(c.step.why); + const say = + budgetReporter ?? + ((why: string) => + console.warn( + `[privacy] ${why} ran out of one call's budget (${PRIVACY_CALL_BUDGET_MS} ms for every operator rule): the text it had not read is shown as [hidden], one per line; the rule stays on`, + )); + say(c.step.why); + }; + if (call.spent) { + // An operator rule that has not run on this call's text at all. + sayBudget(); + return hideLines(s.split("\n")).join("\n"); + } + try { + const out = boundedReplace(s, c, call); + if (call.spent) sayBudget(); + return out; + } catch (err) { + if (!(err instanceof Slow)) throw err; + disabled.add(c.step); + const say = + slowReporter ?? + ((why: string, t: number) => + console.warn( + `[privacy] ${why} took ${Math.round(t)} ms on one window; disabled, it now runs in fallback (on a line holding one of its certain fragments, from that fragment or the whole line; with none, every non-empty line, shown as [hidden])`, + )); + say(c.step.why, err.ms); + return fallbackReplace(s, c); + } +} + +/** Was this step disabled for being slow (tests)? */ +export function isDisabled(step: PrivacyStep): boolean { + return disabled.has(step); +} + +/** `s` as a page shows it under `rules`. Null rules: `s` itself. */ +export function applyPrivacy(rules: PrivacyRules | null | undefined, s: string): string { + if (!rules || typeof s !== "string" || s === "") return s; + let out = s; + // ORDER: the steps run in compile.ts's order (roots, home, mounts, volumes, + // host, user, aliases, the private files' rules, e-mail). The built-in and + // literal ones always run on all the text; only an operator regex or glob + // spends the call's budget, and one that finds it spent shows the text it + // could not read as [hidden] (one per non-empty line). The budget is the + // input's problem, not the rule's: it is not disabled for it. + const call: Call = { deadline: now() + PRIVACY_CALL_BUDGET_MS, spent: false }; + for (const c of stepsOf(rules)) { + if (c.email) out = maskEmails(out, c.to); + else if (c.bounded) out = runBounded(out, c, call); + else out = out.replace(c.rx, c.to); + } + return out; +} + +/** The two displayers bound to one rule list (identity for null). */ +export function displayersOf(rules: PrivacyRules | null | undefined): { displayPath: Displayer; displayText: Displayer } { + if (!rules) return IDENTITY; + const displayText: Displayer = (s) => applyPrivacy(rules, s); + return { displayPath: displayText, displayText }; +} + +const identity: Displayer = (s) => s; +export const IDENTITY: { displayPath: Displayer; displayText: Displayer } = { displayPath: identity, displayText: identity }; + +/** The rules a browser may hold: every secret step dropped. Null when none is left. */ +export function publicRules(rules: PrivacyRules | null | undefined): PrivacyRules | null { + if (!rules) return null; + const steps = rules.steps.filter((s) => !s.secret); + return steps.length ? { v: 1, steps } : null; +} diff --git a/common/lib/privacy/noOperatorNames.test.ts b/common/lib/privacy/noOperatorNames.test.ts @@ -0,0 +1,71 @@ +// THIS LANE'S FILES NEVER NAME THE MACHINE THEY WERE WRITTEN ON (review round +// 2, M-A). The repository's history is published by the source mirror; a test +// that spelled the account's user name or the hostname would publish it. This +// reads the privacy lane's own files and fails if any carries the CURRENT +// account's user name or this machine's hostname as a whole word — both +// computed now, at test time, and never printed: the failure names the file +// and which of the two, nothing else. A test that needs "the current user" +// must ask os.userInfo() at run time. +// +// Run with: node_modules/.bin/tsx --test common/lib/privacy/noOperatorNames.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readdirSync, readFileSync, statSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", ".."); + +// The lane's files: whole directories, and single files. +const DIRS = ["common/lib/privacy"]; +const FILES = [ + "common/lib/privacySettings.ts", + "common/lib/scrubRuleLine.ts", + "common/publish/scrubRuleLine.test.ts", + "common/publish/privacyAudit.ts", + "common/publish/privacyAudit.test.ts", + "common/bin/privacy-audit.ts", + "common/components/PrivacyProvider.tsx", + "editor/e2e/privacy-audit.spec.ts", + "umtool/e2e/privacy-audit.spec.ts", + "umtool/lib/privacy.ts", + "umtool/lib/privacy.test.ts", + "umtool/lib/research/privacySources.test.ts", + "editor/app/channels/components/SiteMembershipsSection.test.ts", +]; + +function files(): string[] { + const out: string[] = []; + for (const d of DIRS) { + for (const name of readdirSync(path.join(ROOT, d))) { + const rel = path.join(d, name); + if (statSync(path.join(ROOT, rel)).isFile()) out.push(rel); + } + } + return [...out, ...FILES]; +} + +const word = (name: string) => new RegExp(`(?<![A-Za-z0-9_-])${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![A-Za-z0-9_-])`, "i"); + +test("no file of the privacy lane names this account or this machine", () => { + let user = ""; + try { + user = os.userInfo().username; + } catch { + user = ""; + } + const names: Array<[string, string]> = []; + if (user.length >= 3) names.push(["the account's user name", user]); + const host = os.hostname(); + for (const h of new Set([host, host.split(".")[0]])) if (h.length >= 3 && h !== "localhost") names.push(["this machine's hostname", h]); + const bad: string[] = []; + const list = files(); + assert.ok(list.length > 10, "the lane's files were found"); + for (const rel of list) { + const text = readFileSync(path.join(ROOT, rel), "utf8"); + for (const [what, name] of names) if (word(name).test(text)) bad.push(`${rel}: ${what}`); + } + assert.deepEqual(bad, []); +}); diff --git a/common/lib/privacy/privacy-server.test.ts b/common/lib/privacy/privacy-server.test.ts @@ -0,0 +1,117 @@ +// The server's displayers over a TEMP settings file and TEMP private rule +// files (never the operator's): live settings, the useSourceRules opt-in, a +// marker planted in the rule files that never reaches the client rules, a +// warning or an error, and the memo following a change. +// +// Run with: node_modules/.bin/tsx --test common/lib/privacy/privacy-server.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, writeFileSync, utimesSync } from "node:fs"; +import os, { tmpdir } from "node:os"; +import path from "node:path"; + +const DIR = mkdtempSync(path.join(tmpdir(), "privacy-server-")); +const SETTINGS = path.join(DIR, "settings.json"); +const SCRUB = path.join(DIR, "scrub.txt"); +const DENY = path.join(DIR, "deny.txt"); +Object.assign(process.env, { SETTINGS_FILE: SETTINGS, SOURCE_SCRUB_FILE: SCRUB, SOURCE_DENYLIST_FILE: DENY }); + +const { currentPrivacy, displayPath, displayText, clientPrivacyRules, hidePrivateSites, resetPrivacyMemo } = await import("./privacy-server"); + +let tick = 0; +const write = (file: string, text: string) => { + writeFileSync(file, text); + // A distinct mtime per write, so the memo key moves even within a second. + tick += 10; + const t = new Date(Date.UTC(2026, 0, 1) + tick * 1000); + utimesSync(file, t, t); + resetPrivacyMemo(); +}; +const settings = (privacy: unknown) => write(SETTINGS, JSON.stringify(privacy === undefined ? {} : { privacy })); + +const HOME = os.homedir(); + +test("absent: identity, no client rules, nothing hidden", () => { + settings(undefined); + const s = `${HOME}/x on ${os.hostname()}`; + assert.equal(displayPath(s), s); + assert.equal(displayText(s), s); + assert.equal(clientPrivacyRules(), null); + assert.equal(hidePrivateSites(), false); + // At its defaults, explicitly: the same. + settings({ displayPaths: "full", hideHost: false, hidePrivateSites: false, aliases: [], maskEmail: false, useSourceRules: false }); + assert.equal(displayText(s), s); + assert.equal(clientPrivacyRules(), null); +}); + +test("live settings: home mode, hidePrivateSites", () => { + settings({ displayPaths: "home", hidePrivateSites: true }); + assert.equal(displayPath(`${HOME}/a/b`), "~/a/b"); + assert.equal(hidePrivateSites(), true); + assert.ok(clientPrivacyRules()); + settings({ hidePrivateSites: true }); + assert.equal(clientPrivacyRules(), null, "a filter flag alone sends no rules"); +}); + +test("useSourceRules: the files are applied on the server, never handed to the client, never quoted", () => { + const warnings: string[] = []; + write(SCRUB, "MARKER-SCRUB-7==>stand-in\nregex:MARKER-RX-(==>x\n"); + write(DENY, "MARKER-DENY-7\n"); + settings({ useSourceRules: true, displayPaths: "home" }); + const c = currentPrivacy({ warn: (l) => warnings.push(l) }); + assert.equal(displayText("a MARKER-SCRUB-7 b MARKER-DENY-7"), "a stand-in b [hidden]"); + const client = JSON.stringify(clientPrivacyRules()); + assert.ok(!client.includes("MARKER"), "the client rules carry no private text"); + assert.ok(!JSON.stringify(c.problems).includes("MARKER")); + assert.deepEqual(warnings, ["[privacy] scrub line 2: does not compile (regex); it runs in fallback: on every line holding one of its 1 certain literal fragment, the text from that fragment (or the whole line, where the fragment does not start the match) is shown as [hidden]"]); + for (const w of warnings) assert.ok(!w.includes("MARKER")); +}); + +test("useSourceRules with the files missing: a warning naming the path, nothing else", () => { + rmSync(SCRUB, { force: true }); + rmSync(DENY, { force: true }); + settings({ useSourceRules: true }); + const warnings: string[] = []; + currentPrivacy({ warn: (l) => warnings.push(l) }); + assert.equal(warnings.length, 2); + assert.match(warnings[0], /^\[privacy\] useSourceRules: no scrub rules at .*scrub\.txt \(ENOENT\)/); + assert.equal(displayText("plain"), "plain"); +}); + +test("the memo follows a settings change", () => { + settings({ displayPaths: "home" }); + assert.equal(displayPath(HOME), "~"); + settings({ displayPaths: "masked" }); + assert.equal(displayPath(HOME), HOME === "/home/user" ? HOME : "/home/user"); +}); + +test("a settings.json that does not parse: strict at boot, the last good rules after", () => { + // At boot (no good compile yet): strict, warned once. + write(SETTINGS, "{ not json"); + const warnings: string[] = []; + const c = currentPrivacy({ warn: (l) => warnings.push(l) }); + assert.equal(c.settings.displayPaths, "masked"); + assert.equal(c.settings.hideHost, true); + assert.match(warnings.join("\n"), /does not parse: privacy runs strict/); + assert.equal(displayPath(`${HOME}/x`), HOME === "/home/user" ? `${HOME}/x` : "/home/user/x"); + // After a good compile with privacy on, a broken file keeps it. + settings({ displayPaths: "home" }); + assert.equal(displayPath(`${HOME}/x`), "~/x"); + writeFileSync(SETTINGS, "{ broken"); + tick += 10; + const t = new Date(Date.UTC(2026, 0, 1) + tick * 1000); + utimesSync(SETTINGS, t, t); + // Let the one-second recheck pass without dropping the memo. + const until = Date.now() + 1100; + while (Date.now() < until) { + /* wait */ + } + assert.equal(displayPath(`${HOME}/x`), "~/x"); + // A missing file is the defaults: off. + rmSync(SETTINGS, { force: true }); + resetPrivacyMemo(); + assert.equal(displayPath(`${HOME}/x`), `${HOME}/x`); +}); + +test.after(() => rmSync(DIR, { recursive: true, force: true })); diff --git a/common/lib/privacy/privacy-server.ts b/common/lib/privacy/privacy-server.ts @@ -0,0 +1,180 @@ +// THE SERVER'S DISPLAYERS (demo epic D4): `displayPath(p)` and +// `displayText(s)` over settings.privacy, for any server component of the +// editor or umtool, plus the rules a browser may hold (`clientPrivacyRules`, +// for components/PrivacyProvider.tsx) and the private-site filter flag. +// +// THE OPERATOR'S PRIVATE RULE FILES (getPaths().sourceScrubFile and +// sourceDenylistFile — the source mirror's) are read here, and only here, and +// only while `privacy.useSourceRules` is on. Their rules are applied by THIS +// module's displayers and by nothing else: `clientPrivacyRules` drops them, no +// response carries them, and nothing logs them — a missing or unreadable file +// is a warning naming its (tildified) path, a broken rule is a warning naming +// its line number. +// +// Compiled once per change: the key is the settings file's and the rule +// files' mtime and size, re-checked at most once a second. + +import { statSync, readFileSync } from "node:fs"; +import os from "node:os"; +import { getPaths } from "../paths"; +import { getSettings } from "../settings"; +import { DEFAULT_PRIVACY_SETTINGS, STRICT_PRIVACY_SETTINGS, privacyActive, privacyProblems, type PrivacySettings } from "../privacySettings"; +import { compilePrivacy, problemLine, type PrivacyProblem } from "./compile"; +import { applyPrivacy, publicRules, type PrivacyRules } from "./display"; + +export type CompiledPrivacy = { + settings: PrivacySettings; + rules: PrivacyRules | null; + client: PrivacyRules | null; + problems: PrivacyProblem[]; +}; + +const INACTIVE: CompiledPrivacy = { settings: DEFAULT_PRIVACY_SETTINGS, rules: null, client: null, problems: [] }; + +const RECHECK_MS = 1000; + +let memo: { key: string; at: number; value: CompiledPrivacy } | null = null; + +const statKey = (file: string) => { + try { + const s = statSync(file); + return `${s.mtimeMs}:${s.size}`; + } catch { + return "-"; + } +}; + +export function tildify(p: string): string { + const home = os.homedir(); + return home.length > 1 && (p === home || p.startsWith(`${home}/`)) ? `~${p.slice(home.length)}` : p; +} + +export function userName(): string | null { + try { + return os.userInfo().username || null; + } catch { + return null; + } +} + +export function hostnames(): string[] { + return [os.hostname(), process.env.ARCHILYZER_HOST_ID ?? ""].filter(Boolean); +} + +function readPrivate(file: string, what: string, warn: (line: string) => void): string | null { + try { + return readFileSync(file, "utf8"); + } catch (err) { + const code = (err as NodeJS.ErrnoException).code ?? "unreadable"; + // The path names the file; nothing of its text is ever in a message. + warn(`[privacy] useSourceRules: no ${what} at ${tildify(file)} (${code}); its rules are not applied`); + return null; + } +} + +let warned = ""; + +/** Compile from the live settings (memoised). Never throws. */ +export function currentPrivacy(opts: { warn?: (line: string) => void } = {}): CompiledPrivacy { + const now = Date.now(); + if (memo && now - memo.at < RECHECK_MS) return memo.value; + const paths = getPaths(); + // Three stats at most once a second; the rule files' only matter while + // useSourceRules is on, but stating them is cheaper than reading settings. + const key = `${statKey(paths.settingsFile)}|${statKey(paths.sourceScrubFile)}|${statKey(paths.sourceDenylistFile)}|${paths.settingsFile}`; + if (memo && memo.key === key) { + memo.at = now; + return memo.value; + } + let value = INACTIVE; + const warnings: string[] = []; + // The raw file first (review round 1, S3): getSettings() reads a file that + // does not parse as an empty one — which would turn privacy OFF. While the + // last good compile had it on, its rules stand, and the server says why. + let raw: Record<string, unknown> | null = null; + try { + const parsed = JSON.parse(readFileSync(paths.settingsFile, "utf8")) as unknown; + raw = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : null; + } catch (err) { + if ((err as NodeJS.ErrnoException).code !== "ENOENT") raw = null; + else raw = {}; + } + if (raw === null && memo && privacyActive(memo.value.settings)) { + const w = `[privacy] ${tildify(paths.settingsFile)} does not parse; the last privacy rules stay until it does`; + if (w !== warned) (opts.warn ?? ((line: string) => console.warn(line)))(w); + warned = w; + memo = { key, at: now, value: memo.value }; + return memo.value; + } + let settings: PrivacySettings = DEFAULT_PRIVACY_SETTINGS; + if (raw === null) { + // The file is THERE and does not parse, with no good compile to keep (a + // boot, review round 2): strict, as an invalid privacy block is. + settings = STRICT_PRIVACY_SETTINGS; + warnings.push(`[privacy] ${tildify(paths.settingsFile)} does not parse: privacy runs strict (every hiding key on) until it does`); + } else { + try { + settings = getSettings().privacy ?? DEFAULT_PRIVACY_SETTINGS; + } catch { + settings = DEFAULT_PRIVACY_SETTINGS; + } + } + for (const p of privacyProblems(raw?.privacy)) warnings.push(`[privacy] settings.json privacy: ${p}`); + const warn = opts.warn ?? ((line: string) => console.warn(line)); + if (privacyActive(settings)) { + const locations = (() => { + try { + return getSettings().storage.locations; + } catch { + return []; + } + })(); + const scrubText = settings.useSourceRules ? readPrivate(paths.sourceScrubFile, "scrub rules", (l) => warnings.push(l)) : null; + const denyText = settings.useSourceRules ? readPrivate(paths.sourceDenylistFile, "denylist", (l) => warnings.push(l)) : null; + const { rules, problems } = compilePrivacy({ + privacy: settings, + homeDir: os.homedir(), + hostnames: hostnames(), + username: userName(), + locations, + scrubText, + denyText, + }); + for (const p of problems) warnings.push(`[privacy] ${problemLine(p)}`); + value = { settings, rules, client: publicRules(rules), problems }; + } + // Each distinct set of warnings is said once per process, not per render. + const said = warnings.join("\n"); + if (said && said !== warned) for (const w of warnings) warn(w); + warned = said; + memo = { key, at: now, value }; + return value; +} + +/** Drop the memo (tests). */ +export function resetPrivacyMemo(): void { + memo = null; + warned = ""; +} + +/** A local path as a page shows it. Identity while privacy is off. */ +export function displayPath(p: string): string { + const { rules } = currentPrivacy(); + return rules ? applyPrivacy(rules, p) : p; +} + +/** Text as a page shows it. Identity while privacy is off. */ +export function displayText(s: string): string { + const { rules } = currentPrivacy(); + return rules ? applyPrivacy(rules, s) : s; +} + +/** The rules a browser may hold — no secret step. Null while there are none. */ +export function clientPrivacyRules(): PrivacyRules | null { + return currentPrivacy().client; +} + +/** Are private sites to be left out of the lists and pickers? */ +export function hidePrivateSites(): boolean { + return currentPrivacy().settings.hidePrivateSites; +} diff --git a/common/lib/privacy/regexSafety.ts b/common/lib/privacy/regexSafety.ts @@ -0,0 +1,231 @@ +// IS AN OPERATOR'S REGEX SAFE TO RUN ON EVERY RENDER? (demo epic D4, review +// round 1, M1.) A conservative STATIC rule, checked once at compile time over +// the JS source a `regex:` or `glob:` display rule compiles to — the +// settings' aliases and the private scrub file's rules alike: +// +// - at most ONE unbounded-or-large quantifier (`*`, `+`, `{n,}`, `{n,m}` +// with m > 64, lazy forms included); +// - no backreference (`\1`, `\k<name>`); +// - no quantified group (one that may repeat) holding a quantifier or an +// alternation; +// - no lookahead or lookbehind (they read past a match, and so past the +// windows display.ts cuts a long line into); +// - the product of every quantifier's range (max − min + 1) AND of every +// alternation's number of branches at most QUANTIFIER_PRODUCT_MAX, so +// three `{0,64}` side by side, or twenty `(a|a)`, are refused too; +// - at most OPTIONAL_GROUPS_MAX optional groups in a row (`(a)?(b)?…`); +// - a match at most MATCH_MAX characters long: the one unbounded quantifier +// is REWRITTEN to at most UNBOUNDED_CAP repeats (`.*` → `.{0,256}`), and +// the longest possible match is computed and refused above MATCH_MAX — +// which is what lets display.ts cut a long line into overlapping windows +// that no match can straddle unseen. +// +// Anything else is refused; compile.ts then fails closed (the rule's literal +// fragments shown as [hidden], the rule reported by its number). display.ts +// also times every operator rule per call and disables one that is slow. +// +// Pure, no imports. + +export const UNBOUNDED_CAP = 256; +export const LARGE_QUANTIFIER = 64; +export const QUANTIFIER_PRODUCT_MAX = 1024; +export const MATCH_MAX = 2048; +export const OPTIONAL_GROUPS_MAX = 4; + +export type RegexVerdict = + // capTrigger: a match at least this long MAY have used the rewritten + // quantifier up to its cap — display.ts then hides to the end of the line, + // never showing the rest of what the operator's pattern would have matched. + // capProbe: the pattern up to and including the capped quantifier, that + // quantifier at EXACTLY its cap — where it matches, the operator's pattern + // may match past the cap, so display.ts hides from there to the line's end. + | { ok: true; source: string; maxLen: number; capTrigger: number | null; capProbe: string | null } + | { ok: false; why: string }; + +type Quant = { min: number; max: number; len: number; text: string }; + +function quantAt(re: string, i: number): Quant | null { + const c = re[i]; + let q: Quant | null = null; + if (c === "*") q = { min: 0, max: Infinity, len: 1, text: "*" }; + else if (c === "+") q = { min: 1, max: Infinity, len: 1, text: "+" }; + else if (c === "?") q = { min: 0, max: 1, len: 1, text: "?" }; + else if (c === "{") { + const m = /^\{(\d+)(,(\d*))?\}/.exec(re.slice(i)); + if (!m) return null; + const min = Number(m[1]); + const max = m[2] ? (m[3] === "" ? Infinity : Number(m[3])) : min; + q = { min, max, len: m[0].length, text: m[0] }; + } + if (q && re[i + q.len] === "?") q = { ...q, len: q.len + 1, text: q.text + "?" }; + return q; +} + +type Node = { maxLen: number; minLen: number; hasQuant: boolean; hasAlt: boolean; out: string }; + +class Refused extends Error {} + +/** The verdict on one JS regex source (no flags needed: `u` is never set). */ +export function analyzeRegex(re: string): RegexVerdict { + let i = 0; + let large = 0; + let product = 1; + // The capped quantifier's atom's shortest length, and its own minimum. + let capped: { atomMin: number; qMin: number } | null = null; + let probe: string | null = null; + // The capped term's own atom, until the probe is written; top-level branches. + let pendingProbeAtom: string | null = null; + let topBranches = 1; + // The groups open at this point: each one's prefix (what precedes it in its + // own sequence, plus its head) and whether it holds the capped quantifier. + const open: Array<{ prefix: string; holds: boolean }> = []; + const bound = (what: string) => { + if (product > QUANTIFIER_PRODUCT_MAX) throw new Refused(what); + }; + + const quantify = (atom: Node, q: Quant, isGroup: boolean): Node => { + const big = q.max === Infinity || q.max > LARGE_QUANTIFIER; + if (big) large++; + if (large > 1) throw new Refused("more than one unbounded or large quantifier"); + if (isGroup && q.max > 1 && (atom.hasQuant || atom.hasAlt)) { + throw new Refused("a repeated group holding a quantifier or an alternation"); + } + let max = q.max; + let text = q.text; + if (max === Infinity) { + if (q.min > UNBOUNDED_CAP) throw new Refused("an unbounded quantifier with a minimum above the cap"); + max = UNBOUNDED_CAP; + text = `{${q.min},${UNBOUNDED_CAP}}${q.text.endsWith("?") && q.text !== "?" ? "?" : ""}`; + // Its probe (capProbe) is the pattern up to it: well defined unless a + // group around it has another branch (refused when that group closes). + capped = { atomMin: atom.minLen, qMin: q.min }; + pendingProbeAtom = atom.out; + for (const o of open) o.holds = true; + } + product *= max - q.min + 1; + bound("the quantifiers' ranges and alternations multiply past the bound"); + return { maxLen: atom.maxLen * max, minLen: atom.minLen * q.min, hasQuant: true, hasAlt: atom.hasAlt, out: atom.out + text }; + }; + + const parseAlternation = (inGroup: boolean): Node => { + const alts: Node[] = [parseSequence()]; + while (re[i] === "|") { + i++; + alts.push(parseSequence()); + } + if (inGroup && re[i] !== ")") throw new Refused("an unclosed group"); + if (!inGroup) topBranches = alts.length; + if (alts.length > 1) { + product *= alts.length; + bound("the quantifiers' ranges and alternations multiply past the bound"); + } + return { + maxLen: Math.max(...alts.map((a) => a.maxLen)), + minLen: Math.min(...alts.map((a) => a.minLen)), + hasQuant: alts.some((a) => a.hasQuant), + hasAlt: alts.length > 1 || alts.some((a) => a.hasAlt), + out: alts.map((a) => a.out).join("|"), + }; + }; + + const parseSequence = (): Node => { + const node: Node = { maxLen: 0, minLen: 0, hasQuant: false, hasAlt: false, out: "" }; + let optionalRun = 0; + while (i < re.length && re[i] !== "|" && re[i] !== ")") { + const start = i; + let atom: Node; + let isGroup = false; + let quantifiable = true; + const c = re[i]; + if (c === "(") { + i++; + let head = "("; + if (/^\?(?:=|!|<=|<!)/.test(re.slice(i))) throw new Refused("a lookahead or lookbehind"); + const m = /^\?(?::|<[A-Za-z_][A-Za-z0-9_]*>)/.exec(re.slice(i)); + if (m) { + head += m[0]; + i += m[0].length; + } else if (re[i] === "?") throw new Refused("an unsupported group"); + open.push({ prefix: node.out + head, holds: false }); + const inner = parseAlternation(true); + const closed = open.pop()!; + if (closed.holds && inner.hasAlt && /\|/.test(inner.out)) { + // (A conservative test: any `|` in the group's own source.) + throw new Refused("an unbounded quantifier in one branch of an alternation"); + } + i++; // ")" + atom = { maxLen: inner.maxLen, minLen: inner.minLen, hasQuant: inner.hasQuant, hasAlt: inner.hasAlt, out: `${head}${inner.out})` }; + isGroup = true; + } else if (c === "[") { + let j = i + 1; + if (re[j] === "^") j++; + if (re[j] === "]") j++; + while (j < re.length && re[j] !== "]") j += re[j] === "\\" ? 2 : 1; + if (j >= re.length) throw new Refused("an unclosed character class"); + atom = { maxLen: 1, minLen: 1, hasQuant: false, hasAlt: false, out: re.slice(i, j + 1) }; + i = j + 1; + } else if (c === "\\") { + const n = re[i + 1]; + if (n === undefined) throw new Refused("a trailing backslash"); + if (/[1-9]/.test(n) || n === "k") throw new Refused("a backreference"); + let len = 2; + if (n === "x") len = 4; + else if (n === "u") len = re[i + 2] === "{" ? re.indexOf("}", i) - i + 1 : 6; + else if (n === "c") len = 3; + const width = n === "b" || n === "B" ? 0 : 1; + atom = { maxLen: width, minLen: width, hasQuant: false, hasAlt: false, out: re.slice(i, i + len) }; + i += len; + if (width === 0) quantifiable = false; + } else if (c === "^" || c === "$") { + atom = { maxLen: 0, minLen: 0, hasQuant: false, hasAlt: false, out: c }; + i++; + quantifiable = false; + } else if (c === "*" || c === "+" || c === "?") { + throw new Refused("a quantifier with nothing to repeat"); + } else { + atom = { maxLen: 1, minLen: 1, hasQuant: false, hasAlt: false, out: c }; + i++; + } + const q = quantAt(re, i); + if (q) { + if (!quantifiable) throw new Refused("a quantified assertion"); + i += q.len; + atom = quantify(atom, q, isGroup); + } + // More than OPTIONAL_GROUPS_MAX optional groups in a row: refused (each + // doubles the paths a failing match tries). + if (isGroup && q && q.min === 0) { + if (++optionalRun > OPTIONAL_GROUPS_MAX) throw new Refused(`more than ${OPTIONAL_GROUPS_MAX} optional groups in a row`); + } else optionalRun = 0; + if (i === start) throw new Refused("an unparsable pattern"); + node.maxLen += atom.maxLen; + node.minLen += atom.minLen; + node.hasQuant ||= atom.hasQuant; + node.hasAlt ||= atom.hasAlt; + if (pendingProbeAtom !== null) { + probe = `${open.map((o) => o.prefix).join("")}${node.out}${pendingProbeAtom}{${UNBOUNDED_CAP}}${")".repeat(open.length)}`; + pendingProbeAtom = null; + } + node.out += atom.out; + } + return node; + }; + + try { + const top = parseAlternation(false); + if (capped && topBranches > 1) throw new Refused("an unbounded quantifier in one branch of an alternation"); + if (i < re.length) throw new Refused("an unbalanced parenthesis"); + if (top.maxLen > MATCH_MAX) throw new Refused(`a match could be longer than ${MATCH_MAX.toLocaleString("en-US")} characters`); + if (top.maxLen === 0) throw new Refused("it can only match the empty string"); + // A match can only have used the capped quantifier up to its cap if it is + // at least the pattern's shortest match plus the cap's extra repeats of + // the atom's shortest form — a NECESSARY condition, so testing it never + // misses a capped match (it may also catch an uncapped long one: strict). + const c = capped as { atomMin: number; qMin: number } | null; + const capTrigger = c ? top.minLen + (UNBOUNDED_CAP - c.qMin) * Math.max(1, c.atomMin) : null; + return { ok: true, source: top.out, maxLen: top.maxLen, capTrigger, capProbe: c ? probe : null }; + } catch (err) { + if (err instanceof Refused) return { ok: false, why: err.message }; + return { ok: false, why: "an unparsable pattern" }; + } +} diff --git a/common/lib/privacy/routes.ts b/common/lib/privacy/routes.ts @@ -0,0 +1,71 @@ +// Every page route of a Next.js app, read off its `app/` directory (demo epic +// D4, the privacy audit's route list) — derived, never typed: a page added to +// either app is audited the next run without anyone listing it. +// +// A route is a directory holding a `page.{tsx,ts,jsx,js,mdx}`. Route groups +// `(x)` add no segment; `api/`, private `_x` folders, parallel `@slot`s and +// intercepting `(.)x` / `(..)x` routes are not pages of their own and are +// left out. A dynamic segment (`[x]`, `[...x]`, `[[...x]]`) makes the route a +// PATTERN, given concrete URLs by the audit's crawl (publish/privacyAudit.ts). +// +// SERVER ONLY (node:fs). + +import { readdirSync } from "node:fs"; +import path from "node:path"; + +export type AppRoute = { + // "/channels/[slug]/videos/[id]" — the app dir's own spelling. + pattern: string; + dynamic: boolean; + // Matches a URL pathname of this route (dynamic routes only need it). + match: RegExp; +}; + +const PAGE_FILES = new Set(["page.tsx", "page.ts", "page.jsx", "page.js", "page.mdx"]); + +const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&"); + +function segmentRegex(seg: string): { re: string; optional: boolean } { + let m = /^\[\[\.\.\.[^\]]+\]\]$/.exec(seg); + if (m) return { re: "(?:/.+)?", optional: true }; + m = /^\[\.\.\.[^\]]+\]$/.exec(seg); + if (m) return { re: "/.+", optional: false }; + m = /^\[[^\]]+\]$/.exec(seg); + if (m) return { re: "/[^/]+", optional: false }; + return { re: `/${escape(seg)}`, optional: false }; +} + +export function routeOf(segments: readonly string[]): AppRoute { + const pattern = `/${segments.join("/")}`; + const dynamic = segments.some((s) => s.startsWith("[")); + const body = segments.map((s) => segmentRegex(s).re).join(""); + return { pattern, dynamic, match: new RegExp(`^${body || "/"}/?$`) }; +} + +/** Every page route under `appDir`, sorted by pattern. */ +export function appRoutes(appDir: string): AppRoute[] { + const out: AppRoute[] = []; + const walk = (dir: string, segments: string[]) => { + let entries; + try { + entries = readdirSync(dir, { withFileTypes: true }); + } catch { + return; + } + if (entries.some((e) => e.isFile() && PAGE_FILES.has(e.name))) out.push(routeOf(segments)); + for (const e of entries) { + if (!e.isDirectory()) continue; + const n = e.name; + if (segments.length === 0 && n === "api") continue; + if (n.startsWith("_") || n.startsWith("@") || n.startsWith(".") || n === "node_modules") continue; + if (/^\(\.+\)/.test(n)) continue; + if (/^\(.*\)$/.test(n)) walk(path.join(dir, n), segments); + else walk(path.join(dir, n), [...segments, n]); + } + }; + walk(appDir, []); + const seen = new Set<string>(); + return out + .filter((r) => (seen.has(r.pattern) ? false : (seen.add(r.pattern), true))) + .sort((a, b) => a.pattern.localeCompare(b.pattern)); +} diff --git a/common/lib/privacy/safety.test.ts b/common/lib/privacy/safety.test.ts @@ -0,0 +1,365 @@ +// Review round 1 of lane/privacy: the regex rule (M1), the window cut (M3), +// fail-closed settings (S3), a linear maskEmail (S5), the engine's coverage +// (S6) and hideUser. Every slow-shape case is under a HARD time assertion. +// +// Run with: node_modules/.bin/tsx --test common/lib/privacy/safety.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { DEFAULT_PRIVACY_SETTINGS, STRICT_PRIVACY_SETTINGS, privacyProblems, sanitizePrivacy, type PrivacySettings } from "../privacySettings"; +import { certainFragments, compilePrivacy } from "./compile"; +import { applyPrivacy, isDisabled, onBudget, onSlowRule, PRIVACY_REGEX_MAX_INPUT, resetBudgetNotes, type PrivacyRules } from "./display"; +import { analyzeRegex, MATCH_MAX } from "./regexSafety"; + +const base = (privacy: Partial<PrivacySettings>, extra: Record<string, unknown> = {}) => + compilePrivacy({ + privacy: { ...DEFAULT_PRIVACY_SETTINGS, ...privacy }, + homeDir: "/home/zqu", + hostnames: ["zqbox.lan"], + username: "zqu", + locations: [{ id: "d", label: "Drive", root: "/run/media/zqu/BIG", volume: { uuid: "ABCD-1234", mountpoint: "/run/media/zqu/BIG" } }], + ...extra, + }); +const rulesOf = (aliases: string[], extra: Partial<PrivacySettings> = {}) => base({ ...extra, aliases }); +const applied = (r: ReturnType<typeof base>, n = 1) => r.rules?.steps.some((s) => s.why === `aliases line ${n}` && s.bounded && !s.refused) ?? false; +const timed = (fn: () => void) => { + const t0 = performance.now(); + fn(); + return performance.now() - t0; +}; +const INPUTS = ["a".repeat(4095), " ".repeat(4095), "a".repeat(5000), "a".repeat(100_000)]; + +// The reviewer's list (probes one.mts / scale.mts): each ran > 10 s on 4 KB. +const REFUSED = [ + ".*.*x", + "a*a*b", + "\\s*\\s*x", + "[a-z]*[a-z]*x", + "(.*)(.*)x", + "a+?a+?b", + "(a*)\\1*b", + "a{0,4096}a{0,4096}a{0,4096}x", + "a{1,9999}a{1,9999}b", + "(a+)+b", + "(a|aa)*b", + "((ab)*c)+", + "a{0,64}a{0,64}a{0,64}x", + "(?<x>a)\\k<x>", + // Review round 2 (M-B): alternation chains multiply; no lookaround at all. + "(a|a)".repeat(20) + "x", + "(a|b|c)(a|b|c)(a|b|c)(a|b|c)(a|b|c)(a|b|c)(a|b|c)", + "KEY(?=a{0,200}!)", + "(?<!x)KEY", + "KEY(?!y)", +]; + +test("M1: every slow shape is refused, fails closed to its fragments, and costs nothing", () => { + for (const p of REFUSED) { + const r = rulesOf([`regex:${p}==>R`]); + assert.equal(applied(r), false, `${p} must not be applied`); + assert.equal(r.problems.length, 1, `${p} is reported`); + assert.match(r.problems[0].what, /refused as possibly slow|does not compile/); + const ms = timed(() => INPUTS.forEach((s) => applyPrivacy(r.rules, s))); + assert.ok(ms < 1000, `${p}: ${ms.toFixed(0)} ms`); + } + // A glob of two stars is two unbounded quantifiers: refused too. + assert.equal(applied(rulesOf(["glob:*zz*==>G"])), false); +}); + +test("M1: the safe shapes are applied, rewritten to a bounded repeat, and fast on 100 KB", () => { + for (const p of ["proj-(\\d+)", "sec[a-z]+", "a.*b", "(?:ab)?c+", "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}", "(a|b)?x"]) { + const r = rulesOf([`regex:${p}==>R`]); + assert.equal(applied(r), true, p); + const ms = timed(() => INPUTS.forEach((s) => applyPrivacy(r.rules, s))); + assert.ok(ms < 1500, `${p}: ${ms.toFixed(0)} ms`); + } + const v = analyzeRegex(".*x"); + assert.ok(v.ok && v.source === ".{0,256}x" && v.maxLen === 257); + const lazy = analyzeRegex("a+?b"); + assert.ok(lazy.ok && lazy.source === "a{1,256}?b"); + assert.equal(analyzeRegex("[a-z]{64}".repeat(40)).ok, false, `a match longer than ${MATCH_MAX}`); + assert.equal(applied(rulesOf(["glob:priv*te==>p"])), true); +}); + +test("M1: the runtime backstop disables a rule slower than 50 ms on one call, by its number", () => { + const said: string[] = []; + onSlowRule((why) => said.push(why)); + try { + const r = rulesOf(["regex:zq.*qz==>R"]); + const step = r.rules!.steps.find((s) => s.why === "aliases line 1")!; + const big = "zq".repeat(400_000); + applyPrivacy(r.rules, big); + if (isDisabled(step)) { + assert.deepEqual(said, ["aliases line 1"]); + // Disabled: its fragments only, at once. + assert.ok(timed(() => applyPrivacy(r.rules, big)) < 200); + assert.equal(applyPrivacy(r.rules, "x zq.qz y"), "x zq.qz y", "no fragment of three characters to hide"); + } else { + // A machine fast enough that no call took 50 ms: nothing said. + assert.deepEqual(said, []); + } + // A hand-made step that is slow on any machine. + const slow: PrivacyRules = { + v: 1, + steps: [{ re: "(x+x+)+y", flags: "g", to: "R", why: "aliases line 9", bounded: true, maxLen: 64, fallback: [{ re: "SECRETWORD", lead: true }] }], + }; + applyPrivacy(slow, "x".repeat(28)); + assert.equal(isDisabled(slow.steps[0]), true); + assert.ok(said.includes("aliases line 9")); + assert.equal(applyPrivacy(slow, "a SECRETWORD b"), "a [hidden]", "fails closed: from its leading fragment to the line's end"); + } finally { + onSlowRule(null); + } +}); + +test("M3: nothing straddling a 4,096-character cut is shown raw", () => { + const N = PRIVACY_REGEX_MAX_INPUT; + const pad = (k: number) => "x".repeat(k); + const cases: Array<[string, ReturnType<typeof base>, string, string]> = [ + ["regex", rulesOf(["regex:SECRET[A-Z]+==>[r]"]), "SECRETWORD", "[r]"], + ["glob", rulesOf(["glob:SECRET*WORD==>[g]"]), "SECRETxWORD", "[g]"], + [ + "secret rule", + base({ useSourceRules: true }, { scrubText: "regex:SECRET[A-Z]+==>[s]\n", denyText: "" }), + "SECRETWORD", + "[s]", + ], + ["e-mail", base({ maskEmail: true }), "person@example.org", "[email]"], + ["hostname", base({ hideHost: true }), "zqbox", "host"], + ["home path", base({ displayPaths: "masked" }), "/home/zqu/a", "/home/user/a"], + ]; + for (const [name, r, secret, shown] of cases) { + for (let off = 1; off < secret.length; off++) { + const s = `${pad(N - off)} ${secret} ${pad(N)} ${secret} ${pad(20)}`; + const out = applyPrivacy(r.rules, s); + assert.ok(!out.includes(secret), `${name} straddling at ${off} is shown raw`); + if (name === "glob") { + // `SECRET*WORD` is `.*` inside: from its first match it could run to + // the line's last WORD, so the rest of the line is hidden (M-D). + assert.ok(out.endsWith(`${shown}[hidden]`), `${name} at ${off}: the rest of the line hidden`); + continue; + } + assert.equal(out.split(shown).length - 1, 2, `${name} at ${off}: both shown as ${shown}`); + assert.equal(out.length, s.length - 2 * (secret.length - shown.length), `${name} at ${off}: nothing else changed`); + } + } +}); + +test("S5: maskEmail is linear — 5 MB on one line in under a second", () => { + const r = base({ maskEmail: true }); + for (const big of ["a".repeat(5_000_000), "a@".repeat(2_500_000), `${"a.".repeat(2_000_000)}@b`, "@".repeat(5_000_000)]) { + const ms = timed(() => applyPrivacy(r.rules, big)); + assert.ok(ms < 1000, `${ms.toFixed(0)} ms`); + } + const m = (s: string) => applyPrivacy(r.rules, s); + assert.equal(m("a.b+tag@ex.com, ME@EX.ORG; mailto:me@ex.org."), "[email], [email]; mailto:[email]."); + assert.equal(m("me@localhost x@[127.0.0.1] @x.com a@b"), "me@localhost x@[127.0.0.1] @x.com a@b"); + assert.equal(m("a@b.co@c.org"), "[email]@c.org"); +}); + +test("S6: case, punctuation, JSON-escaped, percent-encoded and file:// forms; media mounts in home mode", () => { + const home = base({ displayPaths: "home", hideHost: true }); + const masked = base({ displayPaths: "masked", hideHost: true }); + const h = (s: string) => applyPrivacy(home.rules, s); + const m = (s: string) => applyPrivacy(masked.rules, s); + for (const [s, hs, ms] of [ + ["/home/zqu.", "~.", "/home/user."], + ["/home/zqu, /home/zqu) (/home/zqu)", "~, ~) (~)", "/home/user, /home/user) (/home/user)"], + ["/home/zqu.bak /home/zqu2/x", "/home/zqu.bak /home/zqu2/x", "/home/zqu.bak /home/zqu2/x"], + ['{"p":"\\/home\\/zqu\\/a"}', '{"p":"~\\/a"}', '{"p":"\\/home\\/user\\/a"}'], + ["%2Fhome%2Fzqu%2Fa %2fhome%2fzqu", "~%2Fa ~", "%2Fhome%2Fuser%2Fa %2Fhome%2Fuser"], + ["file:///home/zqu/a", "file:///home/user/a", "file:///home/user/a"], + ["/run/media/zqu/OTHER/x", "/run/media/user/OTHER/x", "/media/drive/x"], + ["ZQBOX Zqbox.local zqbox-2 zqbox_x", "host host.local zqbox-2 zqbox_x", "host host.local zqbox-2 zqbox_x"], + ["uuid abcd-1234 / ABCD-1234", "uuid abcd-1234 / ABCD-1234", "uuid [volume] / [volume]"], + ] as const) { + assert.equal(h(s), hs, `home: ${s}`); + assert.equal(m(s), ms, `masked: ${s}`); + } +}); + +test("hideUser: the bare user name as `user`, whole word, any case", () => { + const r = base({ hideUser: true }, { username: "zqu" }); + const u = (s: string) => applyPrivacy(r.rules, s); + assert.equal(u("by: umtool queue add (zqu); ZQU; zqu-2"), "by: umtool queue add (user); user; zqu-2"); + assert.equal(u("zquser zqus mzqu"), "zquser zqus mzqu", "a name inside another word is left alone"); + assert.equal(base({ hideUser: true }, { username: "al" }).rules, null, "shorter than three: no rule"); + assert.equal(base({ hideUser: false }, { username: "zqu" }).rules, null); +}); + +test("S3: a present but wrong privacy block fails CLOSED, named by key", () => { + assert.deepEqual(sanitizePrivacy(undefined), DEFAULT_PRIVACY_SETTINGS); + for (const bad of ["on", null, 1, ["masked"]]) { + assert.deepEqual(sanitizePrivacy(bad), STRICT_PRIVACY_SETTINGS, JSON.stringify(bad)); + assert.match(privacyProblems(bad)[0], /not an object/); + } + const s = sanitizePrivacy({ displayPaths: "Masked", hideHost: "yes", maskEmail: 0, aliases: "x==>y", junk: 1 }); + assert.equal(s.displayPaths, "masked"); + assert.equal(s.hideHost, true); + assert.equal(s.maskEmail, true); + assert.deepEqual(s.aliases, []); + assert.equal(s.hideUser, false, "an absent key keeps its default"); + assert.deepEqual(privacyProblems({ displayPaths: "Masked", hideHost: "yes", maskEmail: 0, aliases: "x==>y", junk: 1 }), [ + 'displayPaths is not "full", "home" or "masked": read as "masked"', + "hideHost is not true or false: read as true", + "maskEmail is not true or false: read as true", + "aliases is not a list: read as []", + "1 key is not a privacy key: ignored", + ]); + assert.deepEqual(privacyProblems(undefined), []); + assert.deepEqual(privacyProblems({ displayPaths: "home", hideHost: false }), []); +}); + +test("M-B: a scrub-file line over 1,000 characters runs in fallback only", () => { + const long = `regex:LONGRULE${"[a-z]".repeat(250)}==>x`; + const r = base({ useSourceRules: true }, { scrubText: `${long}\n`, denyText: "" }); + assert.equal(r.rules!.steps.some((s) => s.why === "scrub line 1" && !s.refused), false); + assert.match(r.problems[0].what, /longer than 1,000 characters; it runs in fallback/); + assert.equal(applyPrivacy(r.rules, "a LONGRULE b"), "a [hidden]", "from its leading fragment to the line's end"); +}); + +test("M-C: a rule in fallback with no literal fragment hides every line it would run on — never a no-op", () => { + const r = rulesOf(["regex:(a|b)+==>R"]); + assert.equal(applied(r), false); + assert.match(r.problems[0].what, /no certain literal fragment, so every line it would run on is shown as \[hidden\]/); + assert.equal(applyPrivacy(r.rules, "one\n\ntwo"), "[hidden]\n\n[hidden]"); + // Disabled at run time, the same: a hand-made slow step with no fragment. + const said: string[] = []; + onSlowRule((why) => said.push(why)); + try { + const slow: PrivacyRules = { v: 1, steps: [{ re: "(x+x+)+y", flags: "g", to: "R", why: "aliases line 7", bounded: true, maxLen: 64, fallback: [] }] }; + assert.equal(applyPrivacy(slow, "x".repeat(28)), "[hidden]"); + assert.deepEqual(said, ["aliases line 7"]); + assert.equal(applyPrivacy(slow, "a TOKEN b\nc"), "[hidden]\n[hidden]"); + } finally { + onSlowRule(null); + } +}); + +test("M-C: the backstop times one WINDOW, not one call — a cheap rule over megabytes stays on", () => { + const said: string[] = []; + onSlowRule((why) => said.push(why)); + try { + const r = rulesOf(["regex:[A-Z0-9]{20}==>[tok]"]); + const big = ("ABCDEFGHIJ0123456789 " + "x".repeat(200)).repeat(20_000); + const out = applyPrivacy(r.rules, big); + assert.ok(!out.includes("ABCDEFGHIJ0123456789")); + assert.deepEqual(said, []); + assert.equal(applyPrivacy(r.rules, "id ABCDEFGHIJ0123456789 end"), "id [tok] end"); + } finally { + onSlowRule(null); + } +}); + +test("M-D: a match that used the capped quantifier to its cap hides the rest of the line", () => { + const tail = "q".repeat(600) + "TAILSECRET"; + for (const a of ["regex:tok-.*==>[t]", "glob:tok-*==>[t]"]) { + const r = rulesOf([a]); + assert.equal(applyPrivacy(r.rules, `x tok-${tail}`), "x [t]", `${a}: cap hit at the end of the pattern`); + assert.equal(applyPrivacy(r.rules, `x tok-${tail}\nnext line`), "x [t]\nnext line", `${a}: only to the end of the line`); + assert.equal(applyPrivacy(r.rules, "x tok-short y"), "x [t]", `${a}: a short match, as before`); + } + // The cap hit in the MIDDLE of a pattern: the rest of the line goes too. + const mid = rulesOf(["regex:BEGIN.*END==>[m]"]); + // `BEGIN.*END` could match past its cap wherever `BEGIN` has 256 more + // characters after it: from there the line is hidden, whatever matched. + assert.equal(applyPrivacy(mid.rules, `a BEGIN${"z".repeat(300)}END tail SECRET`), "a [hidden]", "the pattern runs past the cap: hidden from BEGIN"); + assert.equal(applyPrivacy(mid.rules, `a BEGIN${"z".repeat(254)}END tail SECRET`), "a [m][hidden]", "a match within the cap, more after it: hidden from there"); + assert.equal(applyPrivacy(mid.rules, `a BEGIN${"z".repeat(10)}END tail`), "a [m] tail", "a short line: as before"); + // Inside a group, the same. + const grp = rulesOf(["regex:id-(\\d+)==>ID"]); + assert.equal(applyPrivacy(grp.rules, `x id-${"7".repeat(400)} SECRET`), "x ID", "a capped group match hides the rest of the line"); + assert.equal(applyPrivacy(grp.rules, "x id-42 y"), "x ID y"); +}); + +test("windows keep the whole-line match grid", () => { + const hex = "FAKE-TEST-VALUE".repeat(1024); + for (const n of [7, 13, 30]) { + const r = rulesOf([`regex:[0-9a-f]{${n}}==>H`]); + assert.equal(applyPrivacy(r.rules, hex), hex.replace(new RegExp(`[0-9a-f]{${n}}`, "g"), "H"), `{${n}}`); + } +}); + +test("round 3, M1: one call has a total budget — six cheap-per-window rules on a 5 MB line return in under a second, nothing raw", () => { + const said: string[] = []; + onBudget((why) => said.push(why)); + resetBudgetNotes(); + try { + const line = ("a".repeat(999) + "x").repeat(5000); + let disabledN = 0; + for (const a of ["glob:*x==>R", "regex:.*x==>R", "regex:a*x==>R", "regex:[a-z]{0,31}[a-z]{0,31}x==>R", "regex:(?i)A{0,31}a{0,31}x==>R", "regex:[a-z]+x==>R"]) { + const r = rulesOf([a]); + assert.equal(applied(r), true, `${a} is accepted`); + // Every rule here is "aliases line 1": the once-per-rule note is reset. + resetBudgetNotes(); + const t0 = performance.now(); + const out = applyPrivacy(r.rules, line); + const ms = performance.now() - t0; + assert.ok(ms < 1000, `${a}: ${ms.toFixed(0)} ms`); + assert.ok(!out.includes("x"), `${a}: no raw match of the rule is left`); + // The budget is the input's problem: it never disables the rule. (A + // machine so loaded that one 4 KB window took over 50 ms disables it by + // the OTHER backstop, which is fine — and then it is in fallback.) + const step = r.rules!.steps.find((x) => x.why === "aliases line 1")!; + const small = applyPrivacy(r.rules, "b ax c"); + if (isDisabled(step)) disabledN++; + if (!isDisabled(step)) assert.ok(small.includes("R") && !small.includes("x") && !small.includes("[hidden]"), `${a}: still on (${small})`); + else assert.ok(!small.includes("x"), `${a}: in fallback, nothing raw`); + } + // The rules that do not end early on their cap probe run out of the + // call's budget and say so by number — or, on a machine loaded enough + // that one window took over 50 ms, are disabled by the window backstop. + assert.ok(said.length + disabledN >= 1, `budget notes ${said.length}, disabled ${disabledN}`); + for (const w of said) assert.match(w, /^aliases line 1$/); + } finally { + onBudget(null); + resetBudgetNotes(); + } +}); + +test("round 3, M1: page-sized strings never touch the budget", () => { + const said: string[] = []; + onBudget((why) => said.push(why)); + resetBudgetNotes(); + try { + const r = rulesOf(["regex:proj-(\\d+)==>P", "regex:sec[a-z]+==>S", "glob:tok-*==>T", "regex:[A-Z0-9]{20}==>K", "regex:a.*b==>A"]); + for (let i = 0; i < 200; i++) { + const s = `row ${i}: proj-${i} secret ${"word ".repeat(20)} ABCDEFGHIJ0123456789 /home/zqu/x a then b ${"z".repeat(i % 50)}`; + applyPrivacy(r.rules, s); + } + assert.deepEqual(said, []); + } finally { + onBudget(null); + resetBudgetNotes(); + } +}); + +test("round 3, M2: a refused rule's fallback shows no part of the token", () => { + for (const [p, sample, token] of [ + ["([A-Z0-9]{2}|[a-z])+", "id QW12 x", "QW12"], + ["([A-F0-9]{8}-)+[A-F0-9]{4}", "vol ABCD1234-ABCD1234-EF01 x", "ABCD1234"], + ["(\\d{3}-)+\\d{4}", "tel 555-123-4567 x", "4567"], + ["(tok_[a-z0-9]+)+", "key tok_abc123 x", "abc123"], + ] as const) { + const r = rulesOf([`regex:${p}==>T`]); + assert.equal(applied(r), false, `${p} is refused`); + const out = applyPrivacy(r.rules, sample); + assert.ok(!out.includes(token), `${p}: ${out}`); + assert.ok(!out.includes("tok_") && !/\d{3}/.test(out), `${p}: no part of it`); + } + // Fragments come only from literal runs every match holds. + assert.deepEqual(certainFragments("([A-F0-9]{8}-)+[A-F0-9]{4}", "regex"), []); + assert.deepEqual(certainFragments("(tok_[a-z0-9]+)+", "regex"), [{ text: "tok_", lead: true }]); + assert.deepEqual(certainFragments("x[0-9]+-tok", "regex"), [{ text: "-tok", lead: false }]); + assert.deepEqual(certainFragments("(?:ab)?cde|zzz", "regex"), []); + assert.deepEqual(certainFragments("SECRET*WORD", "glob"), [ + { text: "SECRET", lead: true }, + { text: "WORD", lead: false }, + ]); +}); + +test("round 3: more than four optional groups in a row are refused", () => { + assert.equal(analyzeRegex("(a)?(b)?(c)?(d)?x").ok, true); + assert.equal(analyzeRegex("(a)?(b)?(c)?(d)?(e)?x").ok, false); + assert.equal(analyzeRegex("(a)?(b)?(c)?(d)?y(e)?x").ok, true, "a required atom between ends the run"); +}); diff --git a/common/lib/privacySettings.ts b/common/lib/privacySettings.ts @@ -0,0 +1,189 @@ +// settings.privacy — what the two apps' pages SHOW of the machine they run on +// (demo epic D4, lib/privacy/). Display only: nothing stored, logged to disk, +// sent to a job or written to a record changes; a "copy path" button still +// copies the real path. Pure: the type, its defaults, the sanitizer +// settingsSchema.ts runs it through and the per-field docs SETTINGS.md renders. +// +// EVERY DEFAULT IS TODAY'S BEHAVIOUR. With the block absent or at its defaults +// lib/privacy/compile.ts compiles NO rules, every displayer returns its input +// unchanged and no provider is rendered — the pages are byte-identical. + +import type { FieldDocs } from "./fieldDocs"; + +export type DisplayPathsMode = "full" | "home" | "masked"; + +export const DISPLAY_PATHS_MODES: readonly DisplayPathsMode[] = ["full", "home", "masked"]; + +export type PrivacySettings = { + displayPaths: DisplayPathsMode; + hideHost: boolean; + hideUser: boolean; + hidePrivateSites: boolean; + aliases: string[]; + maskEmail: boolean; + useSourceRules: boolean; +}; + +export const DEFAULT_PRIVACY_SETTINGS: PrivacySettings = { + displayPaths: "full", + hideHost: false, + hideUser: false, + hidePrivateSites: false, + aliases: [], + maskEmail: false, + useSourceRules: false, +}; + +// An alias line longer than this is dropped by the sanitizer: an operator's +// display rule is a name and its stand-in, not a document. +export const PRIVACY_ALIAS_MAX_CHARS = 1000; +export const PRIVACY_ALIASES_MAX = 200; + +export const PRIVACY_SETTINGS_FIELD_DOCS: FieldDocs<PrivacySettings> = { + displayPaths: + "How a page shows a local path. `\"full\"` (default): as it is. `\"home\"`: the home directory as `~`, and the " + + "user's name in a removable-media mount (`/run/media/<user>/…`, `/media/<user>/…`) as `user`. `\"masked\"`: the " + + "home directory as `/home/user`, a storage location's root (and its volume's mountpoint) as `[<its label>]`, any " + + "other removable-media mount (`/media/<user>/<volume>`, `/run/media/…`, `/mnt/<uuid>`) as `/media/drive`, and a " + + "configured volume's UUID, in any case, as `[volume]`. Either mode also catches the path JSON-escaped " + + "(`\\/home\\/u`) and percent-encoded (`%2Fhome%2Fu`), and a `file://` URL keeps its shape (`file:///home/user/…`); " + + "a path ends at punctuation (`/home/u.` is the home dir, `/home/u.bak` is not). Display only: copy buttons copy " + + "the real path. While any key is on, the editor's and umtool's pages carry the rules their browser applies — " + + "the values they hide included — in the page's script payload (see `useSourceRules`).", + hideHost: + "Show this machine's hostname (os.hostname(), its short form and ARCHILYZER_HOST_ID; three characters or more) " + + "as the word `host` wherever a page draws it as text. Matched whole-word, in any case, so a hostname inside " + + "another word is left alone (a hostname that is itself an ordinary word is replaced where it stands alone); " + + "links and other attributes a page needs to work are never rewritten. Default false.", + hideUser: + "Show this account's user name (three characters or more) as the word `user` wherever a page draws it as a " + + "whole word, in any case — a log line's `by: … (name)`, a path segment under `/run/media/`. A name inside " + + "another word is left alone. Default false.", + hidePrivateSites: + "Leave the sites marked private (site.json `audience: \"private\"`) out of the lists and pickers a page DRAWS: " + + "the editor's site-scope picker, /channels' Focus bar and a channel's site memberships (a hidden membership is " + + "still saved as it was), umtool's home, /projects, /work and its research source pickers (a project is hidden " + + "when it belongs to a private site's article). A private site that is the current choice is shown as \"A " + + "private site\". Only what is drawn: every lookup, default and allow-list keeps the private sites, so a case " + + "on a private site's source keeps reading it. Not access control: a private site's own pages still open by " + + "URL. An article's own `audience` is a different notion and hides nothing. If the sites cannot be read, umtool " + + "hides every site's pieces (fail closed). Default false.", + aliases: + "Display rules in the SOURCE MIRROR's scrub format (common/lib/scrubRuleLine.ts): one rule per entry — " + + "`lhs==>rhs` (literal), `literal:lhs==>rhs`, `regex:pattern==>rhs` (`\\1` in rhs is group 1) or " + + "`glob:pattern==>rhs`; with no `==>` the match shows as `***REMOVED***`. Applied to displayed text after the " + + "path and host rules. A `regex:` or `glob:` rule must be cheap to run on every render: at most ONE unbounded " + + "or large quantifier (`*`, `+`, `{n,}`, `{n,m}` with m > 64, lazy forms too; it then repeats at most 256 times, " + + "and where the pattern could match past that the rest of the line is hidden), no backreference, no lookahead " + + "or lookbehind, no repeated group holding a quantifier or an alternation, at most four optional groups in a " + + "row, quantifier ranges and alternation branches multiplying to at most 1,024 and a match of at most 2,048 " + + "characters — so a glob has at most one `*`. A rule that breaks this, or does not compile, is not applied: it " + + "runs in FALLBACK — on each line holding one of its certain literal fragments (three characters or more that " + + "every match contains), the text from that fragment to the line's end (the whole line, where the fragment " + + "does not start the match) is shown as `[hidden]`; with no such fragment, every non-empty line is — and it is " + + "reported by its number in the server log and in `archilyzer privacy audit`. A rule that takes over 50 ms on " + + "one 4,096-character window is disabled into the same fallback for the rest of the process. One display call " + + "spends at most 150 ms on all operator rules together: past that, the text a rule has not read is shown as " + + "`[hidden]`, one per line (the rule stays on; the built-in path, host, user and e-mail rules always run on all " + + "of it). Rules run per line; a line over 4,096 characters is read in overlapping windows. Set with " + + + "`pnpm ops settings --json '{\"patch\":{\"privacy\":{\"aliases\":[\"old==>new\"]}}}'`. Default [].", + maskEmail: "Show every e-mail address a page draws as text as `[email]` (mailto links keep working). Default false.", + useSourceRules: + "Also apply the source mirror's private rule files (SOURCE_SCRUB_FILE, default " + + "`~/.config/archilyzer/source-scrub.txt`, as aliases; SOURCE_DENYLIST_FILE's literals shown as `[hidden]`). " + + "Read by the SERVER only: their rules are applied where a page is rendered on the server and are never sent " + + "to a browser, a response, a log or an error (a client-rendered panel does not get them). A missing file is " + + "a server-log warning naming its path and error code, and nothing else — `archilyzer privacy audit` is the " + + "check that the rules took. Default false. AFTER TURNING PRIVACY ON, RELOAD THE OPEN PAGES: a client-rendered " + + "panel on a page already open stays unmasked until it is loaded again (a change while on, or turning it off, " + + "reaches them on the next navigation). NOTE, for every rule but these: the browser applies the rules " + + "itself, so the page it receives CARRIES the values they hide (the home dir, the hostname, the user name, " + + "the volume UUIDs and roots, each alias's left side) in its script payload — view-source shows them; the " + + "audit reads only what a page draws, not its scripts.", +}; + +export function isDisplayPathsMode(v: unknown): v is DisplayPathsMode { + return v === "full" || v === "home" || v === "masked"; +} + +// FAIL CLOSED (review round 1, S3). A block that is ABSENT is today's +// behaviour; one that is PRESENT but is not an object, or a key with a value +// it cannot take, is read as the STRICTEST valid value — never silently as +// "off": `"displayPaths": "Masked"` is "masked", `"hideHost": "yes"` is true, +// `"privacy": "on"` turns every hiding key on. privacyProblems() names what +// was wrong, by key, for the server's one warning. +export const STRICT_PRIVACY_SETTINGS: PrivacySettings = { + displayPaths: "masked", + hideHost: true, + hideUser: true, + hidePrivateSites: true, + aliases: [], + maskEmail: true, + useSourceRules: true, +}; + +const BOOLEAN_KEYS = ["hideHost", "hideUser", "hidePrivateSites", "maskEmail", "useSourceRules"] as const; + +function cleanAliases(v: unknown): string[] { + return Array.isArray(v) + ? v + .filter((a): a is string => typeof a === "string") + .map((a) => a.replace(/\r?\n/g, "")) + .filter((a) => a.trim() !== "" && a.length <= PRIVACY_ALIAS_MAX_CHARS) + .slice(0, PRIVACY_ALIASES_MAX) + : []; +} + +export function sanitizePrivacy(value: unknown): PrivacySettings { + if (value === undefined) return { ...DEFAULT_PRIVACY_SETTINGS, aliases: [] }; + if (!value || typeof value !== "object" || Array.isArray(value)) return { ...STRICT_PRIVACY_SETTINGS, aliases: [] }; + const r = value as Record<string, unknown>; + const mode = (v: unknown): DisplayPathsMode => { + if (v === undefined) return DEFAULT_PRIVACY_SETTINGS.displayPaths; + return isDisplayPathsMode(v) ? v : "masked"; + }; + const bool = (k: (typeof BOOLEAN_KEYS)[number]) => (r[k] === undefined ? DEFAULT_PRIVACY_SETTINGS[k] : r[k] !== false); + return { + displayPaths: mode(r.displayPaths), + hideHost: bool("hideHost"), + hideUser: bool("hideUser"), + hidePrivateSites: bool("hidePrivateSites"), + aliases: cleanAliases(r.aliases), + maskEmail: bool("maskEmail"), + useSourceRules: bool("useSourceRules"), + }; +} + +/** What a present `privacy` block got wrong, by key name — never by value. */ +export function privacyProblems(value: unknown): string[] { + if (value === undefined) return []; + if (!value || typeof value !== "object" || Array.isArray(value)) return ["the block is not an object: every hiding key is read as on"]; + const r = value as Record<string, unknown>; + const out: string[] = []; + if (r.displayPaths !== undefined && !isDisplayPathsMode(r.displayPaths)) out.push("displayPaths is not \"full\", \"home\" or \"masked\": read as \"masked\""); + for (const k of BOOLEAN_KEYS) if (r[k] !== undefined && typeof r[k] !== "boolean") out.push(`${k} is not true or false: read as true`); + if (r.aliases !== undefined) { + if (!Array.isArray(r.aliases)) out.push("aliases is not a list: read as []"); + else if (cleanAliases(r.aliases).length !== r.aliases.length) out.push("aliases has entries that are not rules (not text, empty, or too long): dropped"); + } + // Unknown keys by COUNT: a key's name is the operator's text. + const known = new Set<string>(["displayPaths", "aliases", ...BOOLEAN_KEYS]); + const unknown = Object.keys(r).filter((k) => !known.has(k)).length; + if (unknown) out.push(`${unknown} key${unknown === 1 ? " is" : "s are"} not a privacy key: ignored`); + return out; +} + +/** Is anything on? False is today's behaviour exactly. */ +export function privacyActive(p: PrivacySettings | null | undefined): boolean { + if (!p) return false; + return ( + p.displayPaths !== "full" || + p.hideHost || + p.hideUser || + p.hidePrivateSites || + p.aliases.length > 0 || + p.maskEmail || + p.useSourceRules + ); +} diff --git a/common/lib/scrubRuleLine.ts b/common/lib/scrubRuleLine.ts @@ -0,0 +1,62 @@ +// ONE LINE OF THE SOURCE MIRROR'S SCRUB FORMAT, split — the pure half of +// parseScrubRules (common/publish/source.ts), moved here unchanged so the +// display rules (lib/privacy/compile.ts, settings.privacy.aliases) read the +// same format with the same parser, in any runtime: no node imports. +// +// A line is `lhs==>rhs` (split at the LAST `==>`, as git-filter-repo splits +// it), `literal:lhs==>rhs`, `regex:…==>…` or `glob:…==>…`; a line with no +// `==>` is replaced by filter-repo's `***REMOVED***`. Lines whose first +// non-blank character is `#` are comments. An empty left side is an error. + +export const SCRUB_REMOVED = "***REMOVED***"; + +export type ScrubLineKind = "plain" | "literal" | "regex" | "glob"; + +export type ScrubLine = { + kind: ScrubLineKind; + // The left side with its prefix removed (plain: the whole left side). + pattern: string; + // The right side, or null when the line has no `==>`. + replacement: string | null; +}; + +export type ScrubLineResult = { ok: true; line: ScrubLine } | { ok: false; error: string }; + +/** + * An operator file's text as lines: a UTF-8 byte-order mark at the start is + * dropped and CRLF endings become LF. An editor that writes either must not + * turn the first rule (and the denial it implies) into one that never matches. + */ +export function operatorLines(text: string): string[] { + return text.replace(/^\uFEFF/, "").split("\n").map((l) => l.replace(/\r$/, "")); +} + +/** A blank line or a comment: no rule. */ +export function isScrubSkip(line: string): boolean { + const t = line.trim(); + return t === "" || t.startsWith("#"); +} + +/** One (non-skip) line, split. `n` is its 1-based line number, for the error. */ +export function splitScrubLine(line: string, n: number): ScrubLineResult { + const i = line.lastIndexOf("==>"); + const lhs = i === -1 ? line : line.slice(0, i); + const replacement = i === -1 ? null : line.slice(i + 3); + for (const prefix of ["regex:", "glob:", "literal:"] as const) { + if (lhs.startsWith(prefix)) { + if (lhs.length === prefix.length) { + return { ok: false, error: `scrub line ${n} has an empty left side — it would match nothing and deny nothing` }; + } + return { ok: true, line: { kind: prefix.slice(0, -1) as ScrubLineKind, pattern: lhs.slice(prefix.length), replacement } }; + } + } + if (i === 0) { + return { ok: false, error: `scrub line ${n} has an empty left side — it would match nothing and deny nothing` }; + } + return { ok: true, line: { kind: "plain", pattern: lhs, replacement } }; +} + +/** The literal a line denies by implication ("" for regex and glob lines). */ +export function scrubLineDenied(line: ScrubLine): string { + return line.kind === "plain" || line.kind === "literal" ? line.pattern : ""; +} diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts @@ -17,6 +17,7 @@ import { JOBS_SETTINGS_FIELD_DOCS, LOOKOUTS_SETTINGS_FIELD_DOCS, LOOKOUT_ITEM_FIELD_DOCS, + PRIVACY_SETTINGS_FIELD_DOCS, SERVICE_COOKIES_SETTINGS_FIELD_DOCS, VOICE_CONVERT_SETTINGS_FIELD_DOCS, VOICE_ENHANCE_SETTINGS_FIELD_DOCS, @@ -372,6 +373,13 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings, }, { path: "lookouts.items[]", docs: LOOKOUT_ITEM_FIELD_DOCS }, ], + privacy: [ + { + path: "privacy", + docs: PRIVACY_SETTINGS_FIELD_DOCS, + defaults: fromObject(d.privacy), + }, + ], }; } diff --git a/common/lib/settingsSchema.test.ts b/common/lib/settingsSchema.test.ts @@ -38,6 +38,7 @@ import type { ClipsSettings } from "./clipSettings"; import type { JobsSettings } from "./jobsSettings"; import type { ServiceCookiesSettings } from "./serviceCookieSettings"; import type { LookoutsSettings } from "./lookoutSettings"; +import type { PrivacySettings } from "./privacySettings"; import type { VoiceSettings } from "./voiceSettings"; import type { GenerationSettings } from "./generationSettings"; import type { @@ -138,13 +139,15 @@ type PreSchemaSiteSettings = { serviceCookies: ServiceCookiesSettings; // Saved lookouts (lane/lookout). lookouts: LookoutsSettings; + // What the pages show of this machine (demo epic D4). + privacy: PrivacySettings; }; // Bracketed so the conditional does not distribute (see commit 8c43231). type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false; const shapeUnchanged: Same<SiteSettings, PreSchemaSiteSettings> = true; -test("SiteSettings keeps its 47 fields, in file order", () => { +test("SiteSettings keeps its 48 fields, in file order", () => { assert.equal(shapeUnchanged, true); assert.deepEqual(Object.keys(siteSettingsSchema.shape), [ "adminTitle", @@ -195,6 +198,7 @@ test("SiteSettings keeps its 47 fields, in file order", () => { "jobs", "serviceCookies", "lookouts", + "privacy", ]); // A parsed object carries every key, in that order — writeSettings writes // exactly this, so the order is the on-disk order. diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -86,6 +86,7 @@ import { sanitizeRemoteArchives, type RemoteArchive } from "./remoteArchives"; import { sanitizeClips, type ClipsSettings } from "./clipSettings"; import { sanitizeJobs, type JobsSettings } from "./jobsSettings"; import { sanitizeLookouts, type LookoutsSettings } from "./lookoutSettings"; +import { sanitizePrivacy, type PrivacySettings } from "./privacySettings"; import { sanitizeServiceCookies, type ServiceCookiesSettings } from "./serviceCookieSettings"; import { sanitizeGeneration, type GenerationSettings } from "./generationSettings"; export { @@ -117,6 +118,7 @@ export { CLIPS_SETTINGS_FIELD_DOCS, type ClipsSettings } from "./clipSettings"; export { JOBS_SETTINGS_FIELD_DOCS, type JobsSettings } from "./jobsSettings"; export { LOOKOUTS_SETTINGS_FIELD_DOCS, LOOKOUT_ITEM_FIELD_DOCS, type LookoutsSettings, type LookoutItem } from "./lookoutSettings"; export { SERVICE_COOKIES_SETTINGS_FIELD_DOCS, type ServiceCookiesSettings } from "./serviceCookieSettings"; +export { PRIVACY_SETTINGS_FIELD_DOCS, type PrivacySettings } from "./privacySettings"; import { DEFAULT_COOKIE_MODE, isCookieMode, @@ -2082,6 +2084,9 @@ export const siteSettingsSchema = z.object({ lookouts: settingsField((v): LookoutsSettings => sanitizeLookouts(v)).describe( "Saved lookouts (lane/lookout): each names channels, a number of days back and an optional prompt, and a run reads those channels' recent transcripts — by air date, duplicate uploads and stream cut-downs folded in — and answers with video ideas. OFF and empty by default; nothing a lookout writes is published. `pnpm ops get lookouts` is the readout, `pnpm ops lookout-run --json '{\"id\":\"…\",\"dryRun\":true}'` lists what one would read. See LookoutsSettings and common/lib/lookoutSettings.ts.", ), + privacy: settingsField((v): PrivacySettings => sanitizePrivacy(v)).describe( + "What the editor's and umtool's pages SHOW of this machine (demo epic D4): local paths with the home directory as `~` or masked, the hostname as a fixed word, private sites left out of the pickers, e-mail addresses masked, and the operator's own display aliases in the source mirror's scrub format. Display only — nothing stored, logged, sent to a job or written to a record changes, and copy buttons copy the real path. Every default is today's behaviour: with the block absent or at its defaults the pages are byte-identical. `archilyzer privacy audit` checks the rendered pages against a denylist. Set with `pnpm ops settings --json '{\"patch\":{\"privacy\":{\"displayPaths\":\"home\"}}}'`. See PrivacySettings and common/lib/privacy/.", + ), }); export type SiteSettings = z.infer<typeof siteSettingsSchema>; diff --git a/common/publish/privacyAudit.test.ts b/common/publish/privacyAudit.test.ts @@ -0,0 +1,319 @@ +// The privacy audit's route list (routes.ts) and its crawl and report +// (privacyAudit.ts), over a temp app dir and a FAKE browser — the real one runs in +// the two apps' privacy-audit e2e specs. The report is searched for every +// literal: it must never carry one, nor the URL or selector around one. +// +// Run with: node_modules/.bin/tsx --test common/publish/privacyAudit.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { parseDenylist } from "./sourceAudit"; +import { appRoutes } from "../lib/privacy/routes"; +import { auditExitCode, formatPrivacyReport, incompleteReasons, literalForms, privacyReportJson, runPrivacyAudit, failingHits, type AuditBrowser } from "./privacyAudit"; +import { main as cliMain, auditLiterals } from "../bin/privacy-audit"; + +const DIR = mkdtempSync(path.join(tmpdir(), "privacy-audit-")); +const APP = path.join(DIR, "app"); +for (const d of [ + "", + "jobs", + "(group)/grouped", + "sites/[site]", + "sites/[site]/[...rest]", + "docs/[[...slug]]", + "api/thing", + "_private", + "@modal/x", + "jobs/(.)peek", + "jobs/no-page", +]) { + mkdirSync(path.join(APP, d), { recursive: true }); + if (d !== "jobs/no-page") writeFileSync(path.join(APP, d, d === "api/thing" ? "route.ts" : "page.tsx"), ""); +} + +test("appRoutes: pages only, groups folded, api/_x/@slot/intercepts left out", () => { + const r = appRoutes(APP); + assert.deepEqual( + r.map((x) => x.pattern), + ["/", "/docs/[[...slug]]", "/grouped", "/jobs", "/sites/[site]", "/sites/[site]/[...rest]"], + ); + const m = (p: string) => r.filter((x) => x.match.test(p)).map((x) => x.pattern); + assert.deepEqual(m("/sites/abc"), ["/sites/[site]"]); + assert.deepEqual(m("/sites/abc/x/y"), ["/sites/[site]/[...rest]"]); + assert.deepEqual(m("/docs"), ["/docs/[[...slug]]"]); + assert.deepEqual(m("/docs/a/b"), ["/docs/[[...slug]]"]); + assert.deepEqual(m("/"), ["/"]); +}); + +const SECRET = "SEKRITNAME"; +const LITERALS = parseDenylist(`# fixture\n${SECRET}\ni:other-word\n`); + +// What each URL draws, per pass. The live pass of /sites/<SECRET> holds the +// literal in an aria-label and an option; / links to it and to /sites/b. +type Item = { where: string; selector: string; text: string; href?: string; joined?: boolean }; +const PAGES: Record<string, { live: Item[]; ssr: Item[] }> = { + "/": { + live: [ + { where: "text", selector: "main > p", text: "hello" }, + { where: "href", selector: "a", text: `/sites/${SECRET}`, href: `http://x.test/sites/${SECRET}` }, + { where: "href", selector: "a:nth-of-type(2)", text: "/sites/b", href: "http://x.test/sites/b" }, + { where: "href", selector: "a:nth-of-type(3)", text: "/sites/c", href: "http://x.test/sites/c" }, + ], + ssr: [], + }, + [`/sites/${SECRET}`]: { + live: [ + { where: "aria-label", selector: "dd[data-x]", text: `path /a/${SECRET}/b` }, + { where: "option", selector: "select > option:nth-of-type(2)", text: `${SECRET} (x)` }, + { where: "text", selector: "p", text: "Other-Word" }, + ], + ssr: [{ where: "aria-label", selector: "dd[data-x]", text: `path /a/${SECRET}/b` }], + }, + "/sites/b": { live: [{ where: "title", selector: "span", text: "clean" }], ssr: [] }, +}; + +const fakeBrowser = (): AuditBrowser => ({ + newContext: async (opts) => ({ + close: async () => {}, + newPage: async () => { + let at = ""; + return { + goto: async (url: string) => { + at = url; + return { status: () => (new URL(url).pathname in PAGES ? 200 : 404) }; + }, + url: () => at, + waitForTimeout: async () => {}, + close: async () => {}, + evaluate: async () => { + const p = PAGES[decodeURI(new URL(at).pathname)]; + return p ? (opts.javaScriptEnabled ? p.live : p.ssr) : []; + }, + }; + }, + }), +}); + +test("the crawl reaches dynamic routes by links, at most maxPerRoute each, and counts live and ssr", async () => { + const result = await runPrivacyAudit({ + targets: [{ app: "fx", baseUrl: "http://x.test/", appDir: APP }], + literals: LITERALS, + browser: fakeBrowser(), + maxPerRoute: 2, + }); + const visited = result.pages.map((p) => p.route); + assert.equal(visited.filter((r) => r === "/sites/[site]").length, 2, "two of the three links followed"); + assert.deepEqual( + result.notReached.map((r) => r.route), + ["/docs/[[...slug]]", "/sites/[site]/[...rest]"], + ); + // The two static routes the fake answers 404 bare, with no link carrying a + // query to them: their 404 stands (never "clean", never excusable). + assert.deepEqual(result.pages.filter((p) => p.status === 404).map((p) => p.route).sort(), ["/grouped", "/jobs"]); + const where = (pass: string) => failingHits(result).filter((h) => h.pass === pass).map((h) => `${h.where}:${h.lit}`).sort(); + assert.deepEqual(where("live"), ["aria-label:0", "option:0", "text:1", "url:0"]); + assert.deepEqual(where("ssr"), ["aria-label:0", "url:0"]); + assert.equal(result.hits.filter((h) => h.where === "href").length, 1, "the link is a warn-only href hit"); + + const report = formatPrivacyReport(result, LITERALS).join("\n"); + const json = JSON.stringify(privacyReportJson(result, LITERALS)); + for (const out of [report, json]) { + assert.ok(!out.includes(SECRET), "the report never carries a literal"); + assert.ok(!out.toLowerCase().includes("other-word")); + } + assert.match(report, /AUDIT FAILED: 6 hits/); + assert.match(report, /denylist line 2 \(len 10\): /); + assert.match(report, /denylist line 3 \(len 10, any case\): 1 in text/); + assert.match(report, /route fx \/sites\/\[site\]: 4 live, 2 ssr/); + assert.match(json, /\[REDACTED\]/, "a URL carrying the literal is masked"); + assert.match(report, /not reached .*\/docs\/\[\[\.\.\.slug\]\]/); +}); + +test("clean: one line of counts; the rule problems first", async () => { + const result = await runPrivacyAudit({ + targets: [{ app: "fx", baseUrl: "http://x.test", appDir: APP }], + literals: parseDenylist("nothing-here\n"), + browser: fakeBrowser(), + include: (_app, r) => r === "/sites/[site]" || r === "/", + ruleProblems: ["aliases line 2: does not compile (regex); it has no literal fragment to hide"], + }); + const lines = formatPrivacyReport(result, parseDenylist("nothing-here\n")); + assert.match(lines[0], /^\[privacy\] rule problem: aliases line 2/); + assert.match(lines[1], /^\[privacy\] audit clean: 3 pages \(2 routes\)/); +}); + +test("the CLI: usage errors exit 2 before any browser starts; --scrub adds literal left sides", async () => { + const said: string[] = []; + const log = (l: string) => said.push(l); + assert.equal(await cliMain({ log }), 2); + assert.equal(await cliMain({ editor: "http://127.0.0.1:9", log }), 2); + assert.equal(await cliMain({ editor: "http://127.0.0.1:9", denylist: path.join(DIR, "missing.txt"), log }), 2); + const scrub = path.join(DIR, "scrub.txt"); + writeFileSync(scrub, "alpha==>b\nregex:x+==>y\nliteral:gamma==>d\n"); + const deny = path.join(DIR, "deny.txt"); + writeFileSync(deny, "# none\n\n"); + assert.equal(await cliMain({ editor: "http://127.0.0.1:9", denylist: deny, log }), 2); + assert.deepEqual( + auditLiterals({ scrub }).map((l) => l.from), + ["scrub line 1 lhs", "scrub line 3 lhs"], + ); + assert.ok(!said.join("\n").includes("alpha")); +}); + +// A browser whose pages are given per URL path, per pass. +const scripted = (pages: Record<string, { status?: number; live?: Item[]; ssr?: Item[]; throws?: string }>): AuditBrowser => ({ + newContext: async (opts) => ({ + close: async () => {}, + newPage: async () => { + let at = ""; + return { + goto: async (url: string) => { + at = url; + const p = pages[new URL(url).pathname]; + if (p?.throws) throw new Error(p.throws); + return { status: () => p?.status ?? (p ? 200 : 404) }; + }, + url: () => at, + waitForTimeout: async () => {}, + close: async () => {}, + evaluate: async () => { + const p = pages[new URL(at).pathname]; + return (opts.javaScriptEnabled ? p?.live : p?.ssr) ?? []; + }, + }; + }, + }), +}); +const ONLY_ROOT_APP = path.join(DIR, "root-only"); +mkdirSync(ONLY_ROOT_APP, { recursive: true }); +writeFileSync(path.join(ONLY_ROOT_APP, "page.tsx"), ""); + +test("M4: never clean when it did not look — down, 500, unreached, no page; --allow-unreached excuses by name", async () => { + const down = await runPrivacyAudit({ + targets: [{ app: "fx", baseUrl: "http://x.test", appDir: APP }], + literals: LITERALS, + browser: scripted({ "/": { throws: "net::ERR_CONNECTION_REFUSED at http://x.test/" } }), + }); + assert.equal(failingHits(down).length, 0); + assert.equal(auditExitCode(down), 3); + assert.match(formatPrivacyReport(down, LITERALS)[0], /^\[privacy\] AUDIT INCOMPLETE \(.*did not load.*not reached/); + assert.equal(privacyReportJson(down, LITERALS).ok, false); + + const five = await runPrivacyAudit({ + targets: [{ app: "fx", baseUrl: "http://x.test", appDir: ONLY_ROOT_APP }], + literals: LITERALS, + browser: scripted({ "/": { status: 500 } }), + }); + assert.equal(auditExitCode(five), 3); + assert.deepEqual(incompleteReasons(five), ["1 page answered 400 or more"]); + + const none = await runPrivacyAudit({ targets: [{ app: "fx", baseUrl: "http://x.test", appDir: path.join(DIR, "no-such-app") }], literals: LITERALS, browser: scripted({}) }); + assert.deepEqual(incompleteReasons(none), ["no page was audited"]); + assert.equal(auditExitCode(none), 3); + + const ok = { "/": { live: [] }, "/grouped": { live: [] }, "/jobs": { live: [] } }; + const unreached = await runPrivacyAudit({ targets: [{ app: "fx", baseUrl: "http://x.test", appDir: APP }], literals: LITERALS, browser: scripted(ok) }); + assert.equal(auditExitCode(unreached), 3); + const excused = await runPrivacyAudit({ + targets: [{ app: "fx", baseUrl: "http://x.test", appDir: APP }], + literals: LITERALS, + browser: scripted(ok), + allowUnreached: ["/sites/[site]", "fx /sites/[site]/[...rest]", "/docs/[[...slug]]"], + }); + assert.equal(auditExitCode(excused), 0); + assert.match(formatPrivacyReport(excused, LITERALS).join("\n"), /audit clean: 3 pages.*\n.*not reached, excused: /); +}); + +test("a static route that 404s bare is visited through a link with its query, else its 404 stands", async () => { + const AT = path.join(DIR, "at-app"); + for (const d of ["", "at"]) { + mkdirSync(path.join(AT, d), { recursive: true }); + writeFileSync(path.join(AT, d, "page.tsx"), ""); + } + const pages = (linked: boolean): AuditBrowser => ({ + newContext: async () => ({ + close: async () => {}, + newPage: async () => { + let at = ""; + return { + goto: async (url: string) => { + at = url; + const u = new URL(url); + return { status: () => (u.pathname === "/at" && !u.search ? 404 : 200) }; + }, + url: () => at, + waitForTimeout: async () => {}, + close: async () => {}, + evaluate: async () => + new URL(at).pathname === "/" && linked ? [{ where: "href", selector: "a", text: "/at?path=x", href: "http://x.test/at?path=x" }] : [], + }; + }, + }), + }); + const viaLink = await runPrivacyAudit({ targets: [{ app: "fx", baseUrl: "http://x.test", appDir: AT }], literals: LITERALS, browser: pages(true) }); + assert.deepEqual(viaLink.pages.map((p) => [p.route, p.status]), [["/", 200], ["/at", 200]]); + assert.equal(auditExitCode(viaLink), 0); + const bare = await runPrivacyAudit({ targets: [{ app: "fx", baseUrl: "http://x.test", appDir: AT }], literals: LITERALS, browser: pages(false) }); + assert.deepEqual(bare.pages.map((p) => [p.route, p.status]), [["/", 200], ["/at", 404]]); + assert.deepEqual(incompleteReasons(bare), ["1 page answered 400 or more"]); + // A seeded path gives the route its query. + const seeded = await runPrivacyAudit({ targets: [{ app: "fx", baseUrl: "http://x.test", appDir: AT }], literals: LITERALS, browser: pages(false), seedPaths: ["fx /at?path=y"] }); + assert.deepEqual(seeded.pages.map((p) => [p.route, p.status]), [["/", 200], ["/at", 200]]); + assert.equal(auditExitCode(seeded), 0); + // --allow-unreached does not excuse a 404. + const named = await runPrivacyAudit({ targets: [{ app: "fx", baseUrl: "http://x.test", appDir: AT }], literals: LITERALS, browser: pages(false), allowUnreached: ["/at"] }); + assert.equal(auditExitCode(named), 3); +}); + +test("S4: encoded and JSON-escaped forms are hits and are masked everywhere; a joined text is one hit; a bad %-escape does not stop the crawl", async () => { + const pct = encodeURIComponent(`/a/${SECRET}`); + const json = JSON.stringify(`/a/${SECRET}`).slice(1, -1).replace(/\//g, "\\/"); + const r = await runPrivacyAudit({ + targets: [{ app: "fx", baseUrl: "http://x.test", appDir: ONLY_ROOT_APP }], + literals: parseDenylist("/a/SEKRITNAME\n"), + browser: scripted({ + "/": { + live: [ + { where: "href", selector: "a", text: "/%E0%A4%A", href: "http://x.test/%E0%A4%A" }, + { where: "text", selector: "p", text: `go ${pct.toLowerCase()}` }, + { where: "text", selector: "code", text: `{"p":"${json}"}` }, + { where: "text", selector: "b", text: "/a/SEKRIT" }, + { where: "text", selector: "i", text: "NAME" }, + { where: "text", selector: "p > span", text: "/a/SEKRITNAME", joined: true } as Item, + { where: "text", selector: "body", text: "… /a/SEKRITNAME …", joined: true } as Item, + ], + }, + }), + }); + const live = failingHits(r).filter((h) => h.pass === "live").map((h) => h.selector).sort(); + // The joined text adds nothing for a literal a single node already carried. + assert.deepEqual(live, ["code", "p"]); + // Split across nodes only: one hit, at the smallest joined element. + const split = await runPrivacyAudit({ + targets: [{ app: "fx", baseUrl: "http://x.test", appDir: ONLY_ROOT_APP }], + literals: parseDenylist("SEKRITNAME\n"), + browser: scripted({ + "/": { + live: [ + { where: "text", selector: "b", text: "SEKRIT" }, + { where: "text", selector: "i", text: "NAME" }, + { where: "text", selector: "p > span", text: "SEKRITNAME", joined: true } as Item, + { where: "text", selector: "body", text: "… SEKRITNAME …", joined: true } as Item, + ], + }, + }), + }); + assert.deepEqual(failingHits(split).map((h) => h.selector), ["p > span (joined)"]); + const out = JSON.stringify(privacyReportJson(r, parseDenylist("/a/SEKRITNAME\n"))) + formatPrivacyReport(r, parseDenylist("/a/SEKRITNAME\n")).join("\n"); + assert.ok(!out.includes("SEKRITNAME")); + assert.ok(!out.toLowerCase().includes(pct.toLowerCase())); + const { forms, orig } = literalForms(parseDenylist("/a/x y\n")); + // Plain, percent-encoded, `\/`-escaped (JSON.stringify changes nothing else here). + assert.equal(forms.length, 3); + assert.deepEqual(orig, [0, 0, 0]); +}); + +test.after(() => rmSync(DIR, { recursive: true, force: true })); diff --git a/common/publish/privacyAudit.ts b/common/publish/privacyAudit.ts @@ -0,0 +1,524 @@ +// THE PRIVACY AUDIT (demo epic D4): every page of the editor and umtool, as a +// browser draws it, searched for the denied literals — `archilyzer privacy +// audit` and the two apps' privacy-audit e2e specs. +// +// WHAT IS VISITED. Each app's routes come from its `app/` dir (routes.ts). The +// static ones are loaded first; a dynamic one gets its URLs from the links on +// the pages already visited (at most `maxPerRoute` each). A pattern no link +// reaches is reported as not reached, by its pattern. +// +// Every page is loaded in a fresh browser context, so no state a page leaves +// (a cookie) changes what the next one draws. +// +// WHAT IS SEARCHED, per page, twice — the server's first HTML with +// JavaScript off ("ssr") and the page after it has run ("live"): every text +// node, the title / aria-label / aria-description / alt / placeholder +// attributes, a field's value, an option's label, the document title and the +// page's URL; and, as a separate warn-only class (it fails only with +// `strict`), every link's href. The browser only COLLECTS: the search runs +// here, in this process, so the literals never reach a page. +// +// THE REPORT NEVER PRINTS A LITERAL (the source mirror's convention, +// sourceAudit.ts, beside it): a literal is named by where it was written +// (`denylist line 3 (len 5)`), a hit by its app, route, kind and a structural +// selector (tag names, data-attribute NAMES, nth-of-type — never a value), and +// every URL or selector it prints is masked. +// +// IT NEVER SAYS CLEAN WHEN IT DID NOT LOOK (review round 1, M4): a page that +// did not load or answered ≥ 400, a route pattern not reached (unless the +// caller excused it by name; a static route that answers 404 bare is visited +// through a link carrying its query, else its 404 stands and cannot be +// excused), or no page at all makes the report INCOMPLETE +// (auditExitCode 3; 1 is a hit). Each literal is searched, and every output +// masked, in its plain, percent-encoded and JSON-escaped forms. +// +// WHAT IS NOT READ: a canvas, CSS `content:`, text a page draws only on hover +// or in another tab or query state, a closed shadow root, a cross-origin +// frame, and the page's scripts — so a value the browser's privacy rules +// carry in the script payload (the home dir they hide, say) is not a hit. +// +// SERVER ONLY. It never decides which instance to run against: the caller +// names the base URLs. + +import { Buffer } from "node:buffer"; +import { foldAscii, literalLabel, maskLiterals, scanBuffer, type Literal } from "./sourceAudit"; +import { appRoutes, type AppRoute } from "../lib/privacy/routes"; + +export type HitWhere = + | "text" + | "title" + | "aria-label" + | "aria-description" + | "alt" + | "placeholder" + | "value" + | "option" + | "document.title" + | "url" + | "href"; + +export const HIT_WHERE_ORDER: readonly HitWhere[] = [ + "text", + "title", + "aria-label", + "aria-description", + "alt", + "placeholder", + "value", + "option", + "document.title", + "url", + "href", +]; + +export type Pass = "ssr" | "live"; + +export type PrivacyHit = { + app: string; + route: string; + // The page's URL, masked. + url: string; + pass: Pass; + where: HitWhere; + selector: string; + lit: number; +}; + +export type AuditPage = { app: string; route: string; url: string; status: number | null; error?: string }; + +export type PrivacyAuditResult = { + literals: number; + pages: AuditPage[]; + notReached: Array<{ app: string; route: string }>; + hits: PrivacyHit[]; + // Problems with the target's privacy rules (compile.ts problemLine). + ruleProblems: string[]; + // Route patterns the caller excused from "not reached" (allowUnreached). + allowUnreached: string[]; +}; + +// Structural slices of Playwright's API, so common needs no Playwright types. +export type AuditResponse = { status: () => number } | null; +export type AuditPageHandle = { + goto: (url: string, opts?: Record<string, unknown>) => Promise<AuditResponse>; + url: () => string; + evaluate: (expr: string) => Promise<unknown>; + waitForTimeout: (ms: number) => Promise<void>; + close: () => Promise<void>; +}; +export type AuditContext = { newPage: () => Promise<AuditPageHandle>; close: () => Promise<void> }; +export type AuditBrowser = { newContext: (opts: Record<string, unknown>) => Promise<AuditContext> }; + +export type AuditTarget = { app: string; baseUrl: string; appDir: string }; + +export type PrivacyAuditOptions = { + targets: readonly AuditTarget[]; + literals: readonly Literal[]; + browser: AuditBrowser; + maxPerRoute?: number; + settleMs?: number; + timeoutMs?: number; + // Only these routes (by pattern) — the specs' narrowing; default all. + include?: (app: string, route: string) => boolean; + ruleProblems?: string[]; + // Dynamic route patterns ("/x/[id]" or "app /x/[id]") the caller names as + // knowingly not reached: they no longer make the audit incomplete. + allowUnreached?: readonly string[]; + // Concrete paths to visit as well ("/projects/at?path=x"; "app /path" to + // name the app): a route that needs a query or an id no page links to. + seedPaths?: readonly string[]; + onPage?: (page: AuditPage) => void; +}; + +// THE COLLECTOR, run in the page. A string, not a function: a transpiler's +// helpers must not leak into the page's scope. It walks the document, every +// OPEN shadow root and every same-origin iframe; besides each text node it +// reads the JOINED text of each element with more than one child (a literal +// split across adjacent nodes — `zq<b>secret</b>`) and the body's innerText. +// Not read: a canvas, CSS `content:`, text only drawn on hover or in another +// tab/query state, a closed shadow root, a cross-origin frame, scripts. +const COLLECT = String.raw`(() => { + const out = []; + const sel = (el, prefix) => { + const parts = []; + let e = el; + for (let d = 0; e && e.nodeType === 1 && d < 6; d++) { + let p = e.tagName.toLowerCase(); + const data = [...e.attributes].map((a) => a.name).filter((n) => n.startsWith("data-")).slice(0, 2); + if (data.length) p += data.map((n) => "[" + n + "]").join(""); + const par = e.parentElement; + if (par) { + const same = [...par.children].filter((c) => c.tagName === e.tagName); + if (same.length > 1) p += ":nth-of-type(" + (same.indexOf(e) + 1) + ")"; + } + parts.unshift(p); + if (e.tagName === "BODY") break; + e = par; + } + return (prefix ? prefix + " >> " : "") + parts.join(" > "); + }; + const scopes = [{ root: document, prefix: "" }]; + for (let i = 0; i < scopes.length && i < 200; i++) { + const { root, prefix } = scopes[i]; + for (const el of root.querySelectorAll("*")) { + if (el.shadowRoot) scopes.push({ root: el.shadowRoot, prefix: sel(el, prefix) + " ::shadow" }); + if (el.tagName === "IFRAME") { + try { + const d = el.contentDocument; + if (d && d.documentElement) scopes.push({ root: d, prefix: sel(el, prefix) + " ::frame" }); + } catch (e) {} + } + } + } + const SKIP = "script,style,noscript,template,option"; + const ATTRS = ["title", "aria-label", "aria-description", "alt", "placeholder"]; + for (const { root, prefix } of scopes) { + const top = root.body || root.documentElement || root; + if (!top) continue; + const doc = root.nodeType === 9 ? root : root.ownerDocument; + const walker = doc.createTreeWalker(top, NodeFilter.SHOW_TEXT); + for (let n = walker.nextNode(); n; n = walker.nextNode()) { + const t = n.nodeValue; + if (!t || !t.trim()) continue; + const p = n.parentElement; + if (!p || p.closest(SKIP)) continue; + out.push({ where: "text", selector: sel(p, prefix), text: t }); + } + // An element's own drawn text: its text nodes, never a script's or a + // style's (textContent would read an inline <script>'s payload). + const drawn = (el) => { + if (!el.querySelector(SKIP)) return el.textContent || ""; + let t = ""; + const w = doc.createTreeWalker(el, NodeFilter.SHOW_TEXT); + for (let n = w.nextNode(); n; n = w.nextNode()) if (!(n.parentElement && n.parentElement.closest(SKIP))) t += n.nodeValue; + return t; + }; + for (const el of root.querySelectorAll("*")) { + if (el.childNodes.length < 2 || el.closest(SKIP) || el.closest("head") || el.tagName === "BODY" || el.tagName === "HTML") continue; + if ((el.textContent || "").length > 20000) continue; + const t = drawn(el); + if (t.trim()) out.push({ where: "text", joined: true, selector: sel(el, prefix), text: t }); + } + if (root.nodeType === 9 && root.body) out.push({ where: "text", joined: true, selector: sel(root.body, prefix), text: root.body.innerText || "" }); + for (const el of root.querySelectorAll("[title],[aria-label],[aria-description],[alt],[placeholder]")) { + if (el.closest("head")) continue; + for (const a of ATTRS) { + const v = el.getAttribute(a); + if (v) out.push({ where: a, selector: sel(el, prefix), text: v }); + } + } + for (const el of root.querySelectorAll("input,textarea")) { + if (el.type === "hidden" || el.type === "password") continue; + if (el.value) out.push({ where: "value", selector: sel(el, prefix), text: el.value }); + } + for (const el of root.querySelectorAll("option")) { + const t = el.label || el.textContent || ""; + if (t) out.push({ where: "option", selector: sel(el, prefix), text: t }); + } + for (const el of root.querySelectorAll("a[href]")) { + out.push({ where: "href", selector: sel(el, prefix), text: el.getAttribute("href") || "", href: el.href }); + } + } + out.push({ where: "document.title", selector: "title", text: document.title || "" }); + return out; +})()`; + +type Collected = { where: HitWhere; selector: string; text: string; href?: string; joined?: boolean }; + +/** + * Every literal and the forms a page may carry it in: percent-encoded (any + * hex case) and JSON-escaped (with and without `\/`). `orig[i]` is the + * literal a form stands for. The audit searches, and MASKS every output with, + * all of them. + */ +export function literalForms(literals: readonly Literal[]): { forms: Literal[]; orig: number[] } { + const forms: Literal[] = []; + const orig: number[] = []; + const seen = new Set<string>(); + const add = (bytes: Buffer, ci: boolean, from: string | undefined, i: number) => { + const key = `${ci ? "i" : "x"}:${bytes.toString("hex")}`; + if (!bytes.length || seen.has(key)) return; + seen.add(key); + forms.push({ bytes, ci, from }); + orig.push(i); + }; + literals.forEach((l, i) => { + add(l.bytes, l.ci, l.from, i); + const text = l.bytes.toString("utf8"); + let pct = text; + try { + pct = encodeURIComponent(text); + } catch { + /* a lone surrogate: no encoded form */ + } + if (pct !== text) add(foldAscii(Buffer.from(pct, "utf8")), true, l.from, i); + const json = JSON.stringify(text).slice(1, -1); + if (json !== text) add(Buffer.from(l.ci ? json.toLowerCase() : json, "utf8"), l.ci, l.from, i); + const slashed = json.replace(/\//g, "\\/"); + if (slashed !== json) add(Buffer.from(l.ci ? slashed.toLowerCase() : slashed, "utf8"), l.ci, l.from, i); + }); + return { forms, orig }; +} + +export async function runPrivacyAudit(opts: PrivacyAuditOptions): Promise<PrivacyAuditResult> { + const maxPerRoute = opts.maxPerRoute ?? 2; + const settleMs = opts.settleMs ?? 900; + const timeoutMs = opts.timeoutMs ?? 45_000; + const result: PrivacyAuditResult = { + literals: opts.literals.length, + pages: [], + notReached: [], + hits: [], + ruleProblems: opts.ruleProblems ?? [], + allowUnreached: [...(opts.allowUnreached ?? [])], + }; + const { forms, orig } = literalForms(opts.literals); + const mask = (s: string) => maskLiterals(s, forms); + const hitsIn = (text: string) => { + const lits = new Set<number>(); + for (const h of scanBuffer(Buffer.from(text, "utf8"), forms)) lits.add(orig[h.lit]); + return [...lits]; + }; + for (const target of opts.targets) { + const base = target.baseUrl.replace(/\/+$/, ""); + const origin = new URL(base).origin; + const routes = appRoutes(target.appDir).filter((r) => !opts.include || opts.include(target.app, r.pattern)); + const statics = routes.filter((r) => !r.dynamic); + const dynamics = routes.filter((r) => r.dynamic); + const instances = new Map<string, number>(); + const queue: Array<{ route: AppRoute; path: string; retry?: true }> = statics.map((r) => ({ route: r, path: r.pattern })); + const queued = new Set(queue.map((q) => q.path)); + // A STATIC route that answers 404 bare may want a query (umtool's + // /projects/at?path=…): a link the crawl finds to it with one is visited + // instead; with none, its 404 stands — "answered ≥ 400", which no + // --allow-unreached excuses. + const staticPaths = new Set(statics.map((r) => r.pattern)); + const withQuery = new Map<string, string>(); + const bare404 = new Map<string, { route: AppRoute; record: AuditPage }>(); + const retried = new Set<string>(); + const maybeRetry = (p: string) => { + const held = bare404.get(p); + const q = withQuery.get(p); + if (!held || !q || retried.has(p)) return; + retried.add(p); + queue.push({ route: held.route, path: q, retry: true }); + }; + const offer = (href: string, seeded = false) => { + let u: URL; + let p: string; + try { + u = new URL(href, base); + p = decodeURI(u.pathname); + } catch { + // A link that is not a URL, or a malformed %-escape: not followed. + return; + } + if (u.origin !== origin) return; + if (staticPaths.has(u.pathname) && u.search) { + if (!withQuery.has(u.pathname)) withQuery.set(u.pathname, u.pathname + u.search); + maybeRetry(u.pathname); + return; + } + if (queued.has(u.pathname)) return; + const r = dynamics.find((d) => d.match.test(p)); + if (!r) return; + const n = instances.get(r.pattern) ?? 0; + if (n >= maxPerRoute && !seeded) return; + instances.set(r.pattern, n + 1); + queued.add(u.pathname); + queue.push({ route: r, path: u.pathname + u.search }); + }; + for (const seed of opts.seedPaths ?? []) { + const sp = seed.indexOf(" "); + const [app, p] = sp > 0 && !seed.startsWith("/") ? [seed.slice(0, sp), seed.slice(sp + 1)] : [null, seed]; + if (app === null || app === target.app) offer(p, true); + } + while (queue.length) { + const { route, path, retry } = queue.shift()!; + const url = `${base}${path}`; + for (const pass of ["live", "ssr"] as const) { + // A FRESH CONTEXT PER PAGE: no cookie one page sets (the editor's + // site scope, written by visiting a site's page) colours the next. + const ctx = await opts.browser.newContext({ javaScriptEnabled: pass === "live" }); + const page = await ctx.newPage(); + const record: AuditPage = { app: target.app, route: route.pattern, url: mask(url), status: null }; + try { + const res = await page.goto(url, { waitUntil: "load", timeout: timeoutMs }); + record.status = res ? res.status() : null; + if (pass === "live") await page.waitForTimeout(settleMs); + const items = (await page.evaluate(COLLECT)) as Collected[]; + items.push({ where: "url", selector: "location", text: page.url() }); + // A JOINED text's hit counts only for a literal no single node on + // this page carried — reported once, at the smallest element. + const plain = new Set<number>(); + const joined = new Map<number, Collected>(); + for (const it of items) { + if (pass === "live" && it.where === "href") offer(it.href ?? it.text); + for (const lit of hitsIn(it.text)) { + if (it.joined) { + const prev = joined.get(lit); + if (!prev || it.text.length < prev.text.length) joined.set(lit, it); + continue; + } + if (it.where === "text") plain.add(lit); + result.hits.push({ app: target.app, route: route.pattern, url: mask(url), pass, where: it.where, selector: mask(it.selector), lit }); + } + } + for (const [lit, it] of joined) { + if (plain.has(lit)) continue; + result.hits.push({ app: target.app, route: route.pattern, url: mask(url), pass, where: "text", selector: `${mask(it.selector)} (joined)`, lit }); + } + } catch (err) { + record.error = mask(String((err as Error)?.message ?? err).split("\n")[0]); + } finally { + await page.close().catch(() => {}); + await ctx.close().catch(() => {}); + } + if (pass === "live") { + if (!retry && record.status === 404 && staticPaths.has(path)) { + bare404.set(path, { route, record }); + maybeRetry(path); + } else { + result.pages.push(record); + opts.onPage?.(record); + } + } + } + } + for (const d of dynamics) if (!instances.get(d.pattern)) result.notReached.push({ app: target.app, route: d.pattern }); + for (const [p, held] of bare404) { + if (retried.has(p)) continue; + result.pages.push(held.record); + opts.onPage?.(held.record); + } + } + return result; +} + +/** The hits that fail the audit: every kind but href, unless strict. */ +export function failingHits(result: PrivacyAuditResult, strict = false): PrivacyHit[] { + return result.hits.filter((h) => strict || h.where !== "href"); +} + +const excused = (result: PrivacyAuditResult, r: { app: string; route: string }) => + result.allowUnreached.some((a) => a === r.route || a === `${r.app} ${r.route}`); + +/** + * Why the audit did NOT look everywhere (review round 1, M4): a page that did + * not load or answered ≥ 400, a route pattern not reached (unless excused), + * no page at all. Empty = complete. A clean audit is only clean when complete. + */ +export function incompleteReasons(result: PrivacyAuditResult): string[] { + const out: string[] = []; + if (result.pages.length === 0) out.push("no page was audited"); + const failed = result.pages.filter((p) => p.error); + const bad = result.pages.filter((p) => !p.error && p.status !== null && p.status >= 400); + if (failed.length) out.push(`${plural(failed.length, "page")} did not load`); + if (bad.length) out.push(`${plural(bad.length, "page")} answered 400 or more`); + const unreached = result.notReached.filter((r) => !excused(result, r)); + if (unreached.length) out.push(`${plural(unreached.length, "route")} not reached (no link to a concrete URL; --allow-unreached excuses one by name)`); + return out; +} + +/** 0 complete and clean, 1 hits, 3 incomplete (2 is the CLI's usage). */ +export function auditExitCode(result: PrivacyAuditResult, strict = false): number { + if (failingHits(result, strict).length) return 1; + if (incompleteReasons(result).length) return 3; + return 0; +} + +const LISTED = 20; +const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? "" : "s"}`; + +/** + * The report, as lines. Clean and complete: one line of counts. Otherwise the + * headline says AUDIT FAILED and/or INCOMPLETE; then the counts per literal + * and kind, per route (ssr and live), the first hits — by app, route, pass, + * kind and selector, never by any text — the pages that did not load and the + * routes not reached. No line carries a literal, in any form. + */ +export function formatPrivacyReport( + result: PrivacyAuditResult, + literals: readonly Literal[], + opts: { strict?: boolean } = {}, +): string[] { + const { forms } = literalForms(literals); + const mask = (s: string) => maskLiterals(s, forms); + const failing = failingHits(result, opts.strict); + const warn = result.hits.length - failing.length; + const incomplete = incompleteReasons(result); + const read = + `${plural(result.pages.length, "page")} (${plural(new Set(result.pages.map((p) => `${p.app} ${p.route}`)).size, "route")}) ` + + `against ${plural(result.literals, "denied literal")}`; + const lines: string[] = []; + for (const p of result.ruleProblems) lines.push(`[privacy] rule problem: ${p}`); + const inc = incomplete.length ? `INCOMPLETE (${incomplete.join("; ")})` : ""; + if (failing.length === 0) { + lines.push( + inc + ? `[privacy] AUDIT ${inc}: no hit in ${read}${warn ? `; ${plural(warn, "href hit")} (warn only)` : ""}` + : `[privacy] audit clean: ${read}${warn ? `; ${plural(warn, "href hit")} (warn only)` : ""}`, + ); + } else { + lines.push(`[privacy] AUDIT FAILED: ${plural(failing.length, "hit")} in ${read}${inc ? `; ${inc}` : ""}`); + const byLit = new Map<number, Map<HitWhere, number>>(); + for (const h of failing) { + const m = byLit.get(h.lit) ?? new Map<HitWhere, number>(); + m.set(h.where, (m.get(h.where) ?? 0) + 1); + byLit.set(h.lit, m); + } + for (const [lit, kinds] of [...byLit].sort((a, b) => a[0] - b[0])) { + const parts = HIT_WHERE_ORDER.filter((k) => kinds.has(k)).map((k) => `${kinds.get(k)} in ${k}`); + lines.push(`[privacy] ${literalLabel(literals, lit)}: ${parts.join(", ")}`); + } + const byRoute = new Map<string, { ssr: number; live: number }>(); + for (const h of failing) { + const k = `${h.app} ${h.route}`; + const c = byRoute.get(k) ?? { ssr: 0, live: 0 }; + c[h.pass]++; + byRoute.set(k, c); + } + for (const [k, c] of [...byRoute].sort((a, b) => a[0].localeCompare(b[0]))) { + lines.push(`[privacy] route ${k}: ${c.live} live, ${c.ssr} ssr`); + } + for (const h of failing.filter((x) => x.pass === "live").slice(0, LISTED)) { + lines.push(`[privacy] ${h.app} ${h.route} ${h.where} at ${mask(h.selector)}: ${literalLabel(literals, h.lit)}`); + } + const liveN = failing.filter((x) => x.pass === "live").length; + if (liveN > LISTED) lines.push(`[privacy] … and ${liveN - LISTED} more live hits`); + } + for (const p of result.pages.filter((x) => x.error || (x.status !== null && x.status >= 400))) { + lines.push(`[privacy] page ${p.app} ${p.route} ${p.error ? `did not load (${mask(p.error)})` : `answered ${p.status}`}`); + } + const unreached = result.notReached.filter((r) => !excused(result, r)); + if (unreached.length) { + lines.push(`[privacy] not reached (no link to a concrete URL): ${unreached.map((r) => `${r.app} ${r.route}`).join(", ")}`); + } + const excusedList = result.notReached.filter((r) => excused(result, r)); + if (excusedList.length) lines.push(`[privacy] not reached, excused: ${excusedList.map((r) => `${r.app} ${r.route}`).join(", ")}`); + return lines; +} + +/** The same, as JSON: counts and positions, never text; every string masked. */ +export function privacyReportJson(result: PrivacyAuditResult, literals: readonly Literal[], opts: { strict?: boolean } = {}) { + const { forms } = literalForms(literals); + const mask = (s: string) => maskLiterals(s, forms); + const failing = failingHits(result, opts.strict); + const incomplete = incompleteReasons(result); + return { + ok: failing.length === 0 && incomplete.length === 0, + exitCode: auditExitCode(result, opts.strict), + incomplete, + literals: result.literals, + pages: result.pages.map((p) => ({ ...p, url: mask(p.url), ...(p.error ? { error: mask(p.error) } : {}) })), + notReached: result.notReached.map((r) => ({ ...r, excused: excused(result, r) })), + ruleProblems: result.ruleProblems, + hits: result.hits.map((h) => ({ + ...h, + url: mask(h.url), + selector: mask(h.selector), + literal: literalLabel(literals, h.lit), + failing: opts.strict || h.where !== "href", + })), + }; +} diff --git a/common/publish/scrubRuleLine.test.ts b/common/publish/scrubRuleLine.test.ts @@ -0,0 +1,126 @@ +// parseScrubRules' line split moved to lib/scrubRuleLine.ts (demo epic D4) as +// a PURE MOVE. This keeps the pre-move implementation, frozen, and asserts the +// new parseScrubRules answers exactly what it answered — the lines filter-repo +// reads, every denied literal and where it came from, and every refusal — over +// a rule file covering all four forms, comments, blanks, a BOM and CRLF. +// +// Run with: node_modules/.bin/tsx --test common/publish/scrubRuleLine.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { parseScrubRules, HOME_REPLACEMENT, BUILT_IN_HOME_RULE, SourceRefusal } from "./source"; +import { isScrubSkip, operatorLines, splitScrubLine, scrubLineDenied } from "../lib/scrubRuleLine"; +import { MASKED_HOME } from "../lib/privacy/compile"; + +// ── the implementation as it was before the move (06c95c3f), verbatim ──────── +function legacyOperatorLines(text: string): string[] { + return text.replace(/^\uFEFF/, "").split("\n").map((l) => l.replace(/\r$/, "")); +} +function legacyParseScrubRules(text: string, homeDir: string) { + const lines: string[] = []; + const denied: Array<{ text: string; from: string }> = []; + const home = homeDir.replace(/\/+$/, ""); + if (home.length > 1 && home !== HOME_REPLACEMENT) { + lines.push(`${home}==>${HOME_REPLACEMENT}`); + denied.push({ text: home, from: BUILT_IN_HOME_RULE }); + } + legacyOperatorLines(text).forEach((line, n) => { + const t = line.trim(); + if (t === "" || t.startsWith("#")) return; + const i = line.lastIndexOf("==>"); + let lhs = i === -1 ? line : line.slice(0, i); + const from = `scrub line ${n + 1} lhs`; + for (const prefix of ["regex:", "glob:", "literal:"]) { + if (lhs.startsWith(prefix)) { + if (lhs.length === prefix.length) { + throw new SourceRefusal(`scrub line ${n + 1} has an empty left side — it would match nothing and deny nothing`); + } + if (prefix === "literal:") lhs = lhs.slice(prefix.length); + else lhs = ""; + break; + } + } + if (i === 0) { + throw new SourceRefusal(`scrub line ${n + 1} has an empty left side — it would match nothing and deny nothing`); + } + lines.push(line); + if (lhs) denied.push({ text: lhs, from }); + }); + return { lines, denied }; +} + +const outcome = (f: () => unknown) => { + try { + return { ok: f() }; + } catch (err) { + return { err: `${(err as Error).name}: ${(err as Error).message}` }; + } +}; + +const DIR = mkdtempSync(path.join(tmpdir(), "scrub-line-")); +const FILE = path.join(DIR, "scrub.txt"); + +const RULE_FILE = + "\uFEFFalpha==>beta\r\n" + + "# a comment\r\n" + + "\r\n" + + " \r\n" + + " # an indented comment\n" + + "literal:gamma==>delta\n" + + "regex:ep+silon(\\d+)==>zeta\\1\n" + + "glob:eta*theta==>iota\n" + + "kappa with no arrow\n" + + "lambda==>mu==>nu\n" + + "literal:xi==>\n" + + "regex:omicron\n" + + " spaced ==> rhs \n" + + "trailing\r"; + +test("parseScrubRules answers exactly what it did before the move", () => { + writeFileSync(FILE, RULE_FILE); + const text = readFileSync(FILE, "utf8"); + for (const home of ["/home/someone", "/home/someone/", "/", HOME_REPLACEMENT, ""]) { + assert.deepEqual(outcome(() => parseScrubRules(text, home)), outcome(() => legacyParseScrubRules(text, home)), home); + } +}); + +test("the refusals are the same, at the same line", () => { + for (const bad of ["==>x\n", "a==>b\nregex:\n", "literal:==>x", "ok==>1\n\nglob:==>y\n", "\uFEFF==>z\r\n"]) { + writeFileSync(FILE, bad); + const text = readFileSync(FILE, "utf8"); + const got = outcome(() => parseScrubRules(text, "/home/someone")); + assert.deepEqual(got, outcome(() => legacyParseScrubRules(text, "/home/someone")), JSON.stringify(bad)); + assert.ok("err" in got, JSON.stringify(bad)); + } +}); + +test("the displayers' masked home dir is the mirror's HOME_REPLACEMENT", () => { + assert.equal(MASKED_HOME, HOME_REPLACEMENT); +}); + +test("operatorLines is the old one", () => { + for (const t of [RULE_FILE, "", "\uFEFF", "a\r\nb\r", "\r\n\r\n"]) assert.deepEqual(operatorLines(t), legacyOperatorLines(t)); +}); + +test("splitScrubLine: the four forms, the missing arrow, the last arrow", () => { + const split = (l: string) => { + const r = splitScrubLine(l, 1); + assert.ok(r.ok); + return r.line; + }; + assert.deepEqual(split("a==>b"), { kind: "plain", pattern: "a", replacement: "b" }); + assert.deepEqual(split("literal:a==>b"), { kind: "literal", pattern: "a", replacement: "b" }); + assert.deepEqual(split("regex:a+==>b"), { kind: "regex", pattern: "a+", replacement: "b" }); + assert.deepEqual(split("glob:a*==>b"), { kind: "glob", pattern: "a*", replacement: "b" }); + assert.deepEqual(split("a"), { kind: "plain", pattern: "a", replacement: null }); + assert.deepEqual(split("a==>b==>c"), { kind: "plain", pattern: "a==>b", replacement: "c" }); + assert.equal(scrubLineDenied(split("regex:a==>b")), ""); + assert.equal(scrubLineDenied(split("literal:a==>b")), "a"); + assert.equal(isScrubSkip(" # x"), true); + assert.equal(isScrubSkip(" x"), false); +}); + +test.after(() => rmSync(DIR, { recursive: true, force: true })); diff --git a/common/publish/source.ts b/common/publish/source.ts @@ -83,6 +83,7 @@ import { type Literal, } from "./sourceAudit"; import { writeTreeIndexes } from "./sourceTree"; +import { isScrubSkip, scrubLineDenied, splitScrubLine } from "../lib/scrubRuleLine"; // Type-only: build.ts imports THIS module lazily, and must not load it (or the // AWS SDK this would drag in) at import time. import type { PublishOpts } from "./build"; @@ -223,27 +224,15 @@ export function parseScrubRules(text: string, homeDir: string): ScrubRules { lines.push(`${home}==>${HOME_REPLACEMENT}`); denied.push({ text: home, from: BUILT_IN_HOME_RULE }); } + // The line split is lib/scrubRuleLine.ts (a pure move: the display rules, + // settings.privacy.aliases, read the same format with the same parser). operatorLines(text).forEach((line, n) => { - const t = line.trim(); - if (t === "" || t.startsWith("#")) return; - const i = line.lastIndexOf("==>"); - let lhs = i === -1 ? line : line.slice(0, i); - const from = `scrub line ${n + 1} lhs`; - for (const prefix of ["regex:", "glob:", "literal:"]) { - if (lhs.startsWith(prefix)) { - if (lhs.length === prefix.length) { - throw new SourceRefusal(`scrub line ${n + 1} has an empty left side — it would match nothing and deny nothing`); - } - if (prefix === "literal:") lhs = lhs.slice(prefix.length); - else lhs = ""; - break; - } - } - if (i === 0) { - throw new SourceRefusal(`scrub line ${n + 1} has an empty left side — it would match nothing and deny nothing`); - } + if (isScrubSkip(line)) return; + const split = splitScrubLine(line, n + 1); + if (!split.ok) throw new SourceRefusal(split.error); lines.push(line); - if (lhs) denied.push({ text: lhs, from }); + const lhs = scrubLineDenied(split.line); + if (lhs) denied.push({ text: lhs, from: `scrub line ${n + 1} lhs` }); }); return { lines, denied }; } diff --git a/common/publish/sourceAudit.ts b/common/publish/sourceAudit.ts @@ -32,6 +32,7 @@ import path from "node:path"; import { gunzipSync } from "node:zlib"; import { runChildIntoLog } from "../jobs/runChild"; import "../lib/childKillGuard"; +import { operatorLines } from "../lib/scrubRuleLine"; /** A refusal: the step stops, publishes nothing, and says why. */ export class SourceRefusal extends Error { @@ -65,14 +66,9 @@ export function foldAscii(buf: Uint8Array): Buffer { return out; } -/** - * An operator file's text as lines: a UTF-8 byte-order mark at the start is - * dropped and CRLF endings become LF. An editor that writes either must not - * turn the first rule (and the denial it implies) into one that never matches. - */ -export function operatorLines(text: string): string[] { - return text.replace(/^\uFEFF/, "").split("\n").map((l) => l.replace(/\r$/, "")); -} +// An operator file's text as lines (BOM dropped, CRLF → LF): moved unchanged +// to lib/scrubRuleLine.ts, re-exported here for its callers. +export { operatorLines }; /** * The denylist file: one literal per line. `i:` in front makes it ASCII diff --git a/common/views/channelRow.ts b/common/views/channelRow.ts @@ -154,6 +154,10 @@ export type ChannelRowInput = { // before locations existed). The dashboard names it from the media target, // as it always has, and passes that here. mediaLocationLabel?: string; + // The page's displayer for the media target and detail (settings.privacy, + // lib/privacy/privacy-server.ts displayPath): the row is drawn, never acted + // on, so the drawn path is the displayed one. Absent = as they are. + show?: (s: string) => string; }; // How old a channel's report is, in the three states /channels draws: @@ -227,8 +231,8 @@ export function buildChannelRowView(i: ChannelRowInput): ChannelRowView { i.media && i.media.status !== "in-place" ? { status: i.media.status, - target: i.media.target, - detail: i.media.detail, + target: i.show && i.media.target ? i.show(i.media.target) : i.media.target, + detail: i.show && i.media.detail ? i.show(i.media.detail) : i.media.detail, locationLabel: "mediaLocationLabel" in i ? i.mediaLocationLabel diff --git a/common/views/pipeline/stageStatus.ts b/common/views/pipeline/stageStatus.ts @@ -199,6 +199,10 @@ export type ComputeStageStatusesInput = { // null when it has none. Read only by the `mirror` stage, which the page // lists only for a channel with `mirror` in its config; omitted = no scan. mirrorScan?: { videos: number; onlyCopy: number; removedInWindow: number; held: number } | null; + // The page's displayer for the Storage stage's drawn path and detail + // (settings.privacy, lib/privacy/privacy-server.ts displayPath). Absent = as + // they are. + show?: (s: string) => string; }; export function computeStageStatuses( @@ -213,6 +217,7 @@ export function computeStageStatuses( backfillKindIds, media, mirrorScan, + show = (t: string) => t, } = input; const buckets = normalizeBuckets(snapshot.buckets); @@ -634,8 +639,10 @@ export function computeStageStatuses( mediaStatus === "in-place" ? "Media is in the channel directory." : mediaStatus === "ok" - ? `Media relocated to ${media?.target ?? "another drive"}.` - : (media?.detail ?? mediaStatus), + ? `Media relocated to ${media?.target != null ? show(media.target) : "another drive"}.` + : media?.detail != null + ? show(media.detail) + : mediaStatus, tone: mediaStatus === "in-transition" ? "running" diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -4,6 +4,18 @@ - **umtool: a picture-only post's read can become its screen, and a screen line can be read in your own voice.** `umtool posts screen <p> <item> add --from-read` (the post bench's "From its read") turns the script of a picture-only post into a screen: one line per line of the script, not checked, and with no speaker split out of a line. That screen *is* the post's read, so the thread read no longer reads the same words twice. `posts screen … record <id> <n> --recording <file>` (the bench's per-line Record / Stop / Keep) records one line as the read says it, with masked numbers and redacted words left out of what you read. It is kept as new takes: recorded, cleaned, and converted to the line's speaker's character's stock voice. None of them is picked. A line take is read only when you choose it, with the bench's per-line select or `set <id> take.<n>=<take>`. A choice follows its line when lines move, and is refused when the line's words or speaker changed. `--check-words` (CLI only) transcribes the recording first and refuses it if it says a number, a handle, an anonymous author's name or a redacted term. The lint flags every chosen take that was not heard this way. - **umtool: no preview plays a read the build refuses.** After a screen line is edited, removed, redacted or no longer read, the build refuses the old read. Play, Present (including the public payload), the card page and the post bench's player now refuse it too: they play the item silent and say why, until the read is made again. Present's public payload carries a post's screens the way the card draws them (masked, blurred speakers nameless), never the raw lines. - **umtool: no part of a read may say what the item's screens mask.** A build refuses a read in which any part says a number or e-mail one of the item's screens masks, or the words of a redacted line. That covers the post's own words, a context post and a screen line. Two recordings kept at the same moment never take the same file: a recorded take's name is now claimed with an exclusive create. +- **A `privacy` settings block: what the pages show of this machine, for a recorded demo; off by default.** Set it with `pnpm ops settings --json '{"patch":{"privacy":{…}}}'` (SETTINGS.md). With the block absent or at its defaults, every page renders as before. + - `displayPaths` `"home"` shows the home directory as `~`. `"masked"` shows it as `/home/user`, a storage location's root as `[<its label>]`, a removable-media mount as `/media/drive` and a volume's UUID as `[volume]`. + - `hideHost` shows the hostname as `host`, whole word only. `maskEmail` shows an e-mail address as `[email]`. + - `hidePrivateSites` leaves the sites marked private out of the site picker. Their pages still open by URL. + - `aliases` are your own display rules, in the source mirror's scrub format. + - `useSourceRules` also applies the source mirror's private rule files. Those rules apply only to text the server draws and are never sent to the browser. + - Covered so far: the "Media relocated to …" badge on the dashboard and /channels, a channel page's Storage summary, /storage's roots and volumes, the saved-video store's path, and /settings' System paths. Copy buttons and actions keep the real paths. + - `archilyzer privacy audit --denylist <file> --editor <url> --umtool <url>` loads every page of both apps in a browser and fails when a denied literal is drawn. It names a literal by its line number, never by its text. +- **umtool: the `privacy` settings block covers umtool's pages too.** + - Drawn through it: /jobs' render paths, errors and log tails; a queue step's label, command and error; /settings/system's roots, index and tool paths; a research case's local source folder. + - A copy button still copies the real text. The box it shows when the clipboard is refused shows the displayed text. + - `hidePrivateSites` leaves a private site's articles and their projects out of home, /projects and /work, and the site out of /research's source picker. - **A local-only Archilyzer in one command: `./docker/demo.sh up`.** On a machine with only docker (compose v2.24 or newer), it starts the editor, umtool and a local model server (ollama) in Docker, connects a published archive as a source (https://jeralyzer.pages.dev unless `--archive`), pulls the model (`--model`, default qwen2.5:7b) and routes every AI task to it. Every step is one printed line; `--dry-run` prints every command and changes nothing; a missing prerequisite (docker, compose, the daemon, 12 GB of RAM, 25 GB free, a port) is one sentence and exit 1. The GPU is found by itself (a render node: ollama on Vulkan; NVIDIA; else the CPU, said so), and ollama's own line about the device it uses is printed. A host ollama already holding a model on the GPU is warned about. The choices are kept in `.env.demo` (mode 600) and reused, so a second `up` changes nothing. A step that fails after the start (the start itself, the editor's first answer, the pull, the settings) ends with one sentence saying the demo is partly up and that `./docker/demo.sh down` stops it. `down` keeps the volumes unless `--volumes`, and stops the stack even when `.env.demo` is gone; `status` shows the stack; `voice` says what Orpheus needs. Nothing is opened off this machine: every value written to `.env.demo` is checked character by character (a newline cannot be smuggled in through `--archive`), a `.env.demo` line it did not write or a bind other than 127.0.0.1 (in the file or the shell) is refused, and the exposure guard is handed the binds compose really publishes on (docker-compose.yml, for every stack). RUNNING_IN_DOCKER.md, "A local-only demo". - **Local only: `ARCHILYZER_LOCAL_ONLY=1` (the demo sets it).** With ARCHILYZER_LOCAL_ONLY=1, this instance refuses — before any request is sent or any process started — every call to the Claude API, every Claude Code answer (a task routed to `code`, or `answers` posted by a session), the digest's `claude` CLI lane, and every call to an ollama model that is a cloud model (a `-cloud` tag, or one whose /api/show names a remote host) or that is served from anywhere but this machine (a loopback address) or a host named in ARCHILYZER_LOCAL_MODEL_HOSTS. It does not cover the web pages a local model may read (its web_search and fetch tools), the published site's in-browser Ask, or remote transcription workers, which are not language models. A settings change (on the ops route or the editor's own pages) that would route a task off the local model or name a model server elsewhere is refused, an LLM worker elsewhere is not saved and is skipped, and `reports import-sweep` and `import-local-runs` are refused. A refused job or write says so in one sentence; the digest's metered lane says "refused: local only", not "is the claude CLI installed". `archilyzer gen local-check` (and `./docker/demo.sh check`) checks it afterwards by counts and host names: the flag on, every route local, every model server a local route asks on this machine, no API key present, no call off the local route in the usage ledger or the per-call logs since a date, and no imported iteration; it exits 1 when any fails, says NOTHING TO PROVE YET (not PASS) while no call is recorded, and never prints a key or a home path. The editor's boot log says `models: LOCAL ONLY`, says as an ERROR when the flag holds a value it does not understand, and gives one line on whether ollama answers. umtool makes no model call itself. Unset, nothing changes. Needs a restart of the editor. - **`archilyzer gen model api|local|extractor <model>` sets the model a route runs** (settings.generation.models), from a terminal or a container; bare, it shows the three. diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx @@ -1,3 +1,5 @@ +import { displayPath, hidePrivateSites } from "yt-dlp-transcript-common/lib/privacy/privacy-server"; +import { isPrivateSite } from "yt-dlp-transcript-common/lib/siteSchema"; import path from "node:path"; import { Suspense, type ReactNode } from "react"; import type { Metadata } from "next"; @@ -464,6 +466,8 @@ export default async function ChannelDetailPage({ backfillEnabled: laneOperations.length > 0, backfillKindIds: laneOperations.map((k) => k.id), media, + // settings.privacy: the Storage summary's path as displayed. + show: displayPath, mirrorScan: mirrorScan ? { videos: mirrorScan.totals.videos, @@ -554,11 +558,15 @@ export default async function ChannelDetailPage({ // Sites membership section: every configured site plus this channel's // current membership (and group) on each. const allSites = listSites(paths); + // settings.privacy.hidePrivateSites: a private site is not drawn but + // stays in the list, so its membership survives a save. + const hidePrivate = hidePrivateSites(); const siteOptions: SiteMembershipOption[] = allSites.map((s) => ({ siteId: s.siteId, siteTitle: s.siteTitle, defaultGroupId: s.defaultGroupId, groups: sortGroups(s.groups).map((g) => ({ id: g.id, name: g.name })), + ...(hidePrivate && isPrivateSite(s) ? { hidden: true as const } : {}), })); const initialMemberships: InitialMembership[] = allSites.flatMap( (s) => { diff --git a/editor/app/channels/components/SiteMembershipsSection.test.ts b/editor/app/channels/components/SiteMembershipsSection.test.ts @@ -0,0 +1,29 @@ +// settings.privacy.hidePrivateSites on a channel's configure tab (review round +// 1, S1): a private site is not DRAWN, but its membership is submitted exactly +// as it was — a save must never drop a membership the operator cannot see. +// +// Run with: pnpm --filter editor test + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { membershipsJsonOf, type Row, type SiteMembershipOption } from "./SiteMembershipsSection"; + +const site = (siteId: string, hidden = false): SiteMembershipOption => ({ + siteId, + siteTitle: `T ${siteId}`, + defaultGroupId: "default", + groups: [{ id: "g1", name: "G1" }], + ...(hidden ? { hidden: true as const } : {}), +}); + +test("a hidden site's membership (and its group) is in what the form submits", () => { + const sites = [site("pub"), site("priv", true), site("other")]; + const selected = new Map<string, Row>([ + ["pub", { groupId: "", newGroupName: "" }], + ["priv", { groupId: "g1", newGroupName: "" }], + ]); + assert.deepEqual(JSON.parse(membershipsJsonOf(sites, selected)), [{ siteId: "pub" }, { siteId: "priv", groupId: "g1" }]); + // The same answer with nothing hidden: the flag changes what is drawn only. + const plain = [site("pub"), site("priv"), site("other")]; + assert.equal(membershipsJsonOf(plain, selected), membershipsJsonOf(sites, selected)); +}); diff --git a/editor/app/channels/components/SiteMembershipsSection.tsx b/editor/app/channels/components/SiteMembershipsSection.tsx @@ -20,6 +20,10 @@ export type SiteMembershipOption = { defaultGroupId: string; // Pre-sorted server-side via sortGroups. groups: { id: string; name: string }[]; + // settings.privacy.hidePrivateSites: a private site is NOT DRAWN, but it + // stays in the list so its membership is submitted as it was — a save never + // drops a membership the operator cannot see. Set only when true. + hidden?: true; }; export type InitialMembership = { siteId: string; groupId?: string }; @@ -28,7 +32,7 @@ export type InitialMembership = { siteId: string; groupId?: string }; // group id — underscores fail isValidGroupId (same trick as ALL_SITES). const NEW_GROUP = "__new__"; -type Row = { groupId: string; newGroupName: string }; +export type Row = { groupId: string; newGroupName: string }; type Props = { sites: SiteMembershipOption[]; @@ -40,6 +44,34 @@ type Props = { activeSiteId?: string | null; }; +// One entry per CHECKED site; an unchecked site is simply absent (= remove +// membership on edit). See MembershipRequest in lib/siteMemberships.ts. A +// HIDDEN site (hidePrivateSites) is in `sites` and so in here: its membership +// is kept exactly as it was. +export function membershipsJsonOf( + sites: ReadonlyArray<SiteMembershipOption>, + selected: ReadonlyMap<string, Row>, +): string { + return JSON.stringify( + sites + .filter((s) => selected.has(s.siteId)) + .map((s) => { + const row = selected.get(s.siteId)!; + if (row.groupId === NEW_GROUP) { + const name = row.newGroupName.trim(); + // The visible name input is `required`, so an empty name never + // submits; falling back to default is belt-and-braces only. + return name + ? { siteId: s.siteId, newGroupName: name } + : { siteId: s.siteId }; + } + return row.groupId + ? { siteId: s.siteId, groupId: row.groupId } + : { siteId: s.siteId }; + }), + ); +} + export function SiteMembershipsSection({ sites, initialMemberships, @@ -104,26 +136,7 @@ export function SiteMembershipsSection({ return next; }); - // One entry per CHECKED site; an unchecked site is simply absent (= remove - // membership on edit). See MembershipRequest in lib/siteMemberships.ts. - const membershipsJson = JSON.stringify( - sites - .filter((s) => selected.has(s.siteId)) - .map((s) => { - const row = selected.get(s.siteId)!; - if (row.groupId === NEW_GROUP) { - const name = row.newGroupName.trim(); - // The visible name input is `required`, so an empty name never - // submits; falling back to default is belt-and-braces only. - return name - ? { siteId: s.siteId, newGroupName: name } - : { siteId: s.siteId }; - } - return row.groupId - ? { siteId: s.siteId, groupId: row.groupId } - : { siteId: s.siteId }; - }), - ); + const membershipsJson = membershipsJsonOf(sites, selected); return ( <div className="flex flex-col gap-1"> @@ -132,7 +145,7 @@ export function SiteMembershipsSection({ Pick the sites this channel appears on, and the group it belongs to on each. </p> - {sites.map((s) => { + {sites.filter((s) => !s.hidden).map((s) => { const row = selected.get(s.siteId); const on = !!row; const label = s.siteTitle || s.siteId; diff --git a/editor/app/channels/page.tsx b/editor/app/channels/page.tsx @@ -1,3 +1,5 @@ +import { displayPath, hidePrivateSites } from "yt-dlp-transcript-common/lib/privacy/privacy-server"; +import { isPrivateSite } from "yt-dlp-transcript-common/lib/siteSchema"; import type { Metadata } from "next"; import Link from "next/link"; import { @@ -150,10 +152,13 @@ function focusLabelOf( focus: SiteSettings["channelPriority"]["focus"], focusSlugs: ReadonlyArray<string>, sites: ReadonlyArray<Site>, + hidden: (site: Site) => boolean = () => false, ): string | null { if (focusSlugs.length === 0) return null; if (focus.kind === "site") { const site = sites.find((s) => s.siteId === focus.siteId); + // settings.privacy.hidePrivateSites: a private focus is not named. + if (site && hidden(site)) return "a private site"; return `site ${site?.siteTitle ?? focus.siteId}`; } return focusSlugs.length === 1 @@ -201,7 +206,11 @@ export default async function ChannelsPage({ // returns [] for an unknown siteId deliberately, so a typo never holds the // corpus, and the bar must say "No focus" rather than name a site that is not // there. - const focusLabel = focusLabelOf(priority.focus, focusSlugs, sites); + // settings.privacy.hidePrivateSites: what the Focus bar DRAWS of a private + // site (the focus itself, and what a pick submits, are unchanged). + const hidePrivate = hidePrivateSites(); + const hiddenSite = (s: Site) => hidePrivate && isPrivateSite(s); + const focusLabel = focusLabelOf(priority.focus, focusSlugs, sites, hiddenSite); // Keyed by slug rather than by index: listChannelStatsFromSnapshots happens // to map the briefs in order today, and pairing a channel's counts with // another channel's bands is exactly the kind of silent wrongness this whole @@ -252,6 +261,8 @@ export default async function ChannelsPage({ // in-place one and names the location from the volume, which is the // same prefix match the Location column shows — one answer, not two. media: mediaBySlug.get(stat.slug) ?? null, + // settings.privacy: the badge's "relocated to <path>" as displayed. + show: displayPath, volume: channelVolumeOf(brief?.config, locations), priority: { tier: tierOf(priority, stat.slug), @@ -424,7 +435,11 @@ export default async function ChannelsPage({ {channels.length === 0 ? ( <p className="text-sm text-muted-foreground border border-dashed border-border rounded p-4"> {active.siteId && !active.isAll - ? `No channels assigned to ${active.siteId} yet — add some on the Sites page, or create a channel to add it here.` + ? `No channels assigned to ${ + // settings.privacy.hidePrivateSites: a private scope (a + // `?site=` link, or the stored choice) is not named. + activeSite && hiddenSite(activeSite) ? "this private site" : active.siteId + } yet — add some on the Sites page, or create a channel to add it here.` : "No channels yet."} </p> ) : ( @@ -450,10 +465,12 @@ export default async function ChannelsPage({ root: loc.root, }))} defaultLocationId={settings.storage.defaultLocationId} - sites={sites.map((s) => ({ - siteId: s.siteId, - title: s.siteTitle || s.siteId, - }))} + sites={sites + .filter((s) => !hiddenSite(s) || (priority.focus.kind === "site" && priority.focus.siteId === s.siteId)) + .map((s) => ({ + siteId: s.siteId, + title: hiddenSite(s) ? "A private site" : s.siteTitle || s.siteId, + }))} focusLabel={focusLabel} /> )} diff --git a/editor/app/components/SiteScopeSelect.tsx b/editor/app/components/SiteScopeSelect.tsx @@ -59,7 +59,9 @@ export function SiteScopeSelect({ sites }: { sites: SiteScopeOption[] }) { [held, onSite?.siteId, param, stored], siteIds, ); - const multi = sites.length > 1; + // Over EVERY site (siteIds), not the drawn list: hidePrivateSites leaves + // private ones out of `sites`, and "All sites" must stay offered. + const multi = siteIds.length > 1; async function onChange(value: string) { if (onSite) { @@ -97,7 +99,7 @@ export function SiteScopeSelect({ sites }: { sites: SiteScopeOption[] }) { router.replace(withoutSiteParam(pathname, search), { scroll: false }); } - if (sites.length === 0) { + if (siteIds.length === 0) { return ( <div className="px-4 py-2 text-xs text-muted-foreground"> No sites — create one under Sites. @@ -124,6 +126,15 @@ export function SiteScopeSelect({ sites }: { sites: SiteScopeOption[] }) { {s.siteTitle} ({s.siteId}) </option> ))} + {/* settings.privacy.hidePrivateSites: the layout leaves the private + sites out of `sites` (they stay valid scopes). One that is the + scope anyway — the stored choice, or the site this path names — + is shown without its name rather than as some other option. */} + {resolved.value !== ALL_SITES && !sites.some((s) => s.siteId === resolved.value) && ( + <option value={resolved.value} data-private-site=""> + A private site + </option> + )} </select> </label> ); diff --git a/editor/app/layout.tsx b/editor/app/layout.tsx @@ -7,6 +7,9 @@ import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { getSettings } from "yt-dlp-transcript-common/lib/settings"; import { getLatestChangelogDate } from "yt-dlp-transcript-common/lib/changelog"; import { listSites } from "yt-dlp-transcript-common/lib/site"; +import { isPrivateSite } from "yt-dlp-transcript-common/lib/siteSchema"; +import { clientPrivacyRules, hidePrivateSites } from "yt-dlp-transcript-common/lib/privacy/privacy-server"; +import { PrivacyProvider } from "yt-dlp-transcript-common/components/PrivacyProvider"; import { fontVars } from "yt-dlp-transcript-common/styles/fonts"; import { ThemeScript } from "yt-dlp-transcript-common/components/ThemeScript"; import { ThemeProvider } from "yt-dlp-transcript-common/components/ThemeProvider"; @@ -39,6 +42,13 @@ export async function generateMetadata(): Promise<Metadata> { // NAV_GROUPS now lives in ./lib/nav (shared with the command palette). +// The privacy provider around `children` while settings.privacy has browser +// rules; otherwise `children` itself. A plain call, not a component, so a page +// with the block absent has exactly the tree it had before. +function withPrivacy(rules: ReturnType<typeof clientPrivacyRules>, children: React.ReactElement) { + return rules ? <PrivacyProvider rules={rules}>{children}</PrivacyProvider> : children; +} + function readChangelogLatestDate(): string | null { try { const source = readFileSync(getPaths().editorChangelogFile, "utf8"); @@ -60,11 +70,20 @@ export default async function RootLayout({ (j) => j.status === "running" || j.status === "queued", ).length; const latestChangelogDate = readChangelogLatestDate(); - const sites = listSites().map((s) => ({ - siteId: s.siteId, - siteTitle: s.siteTitle, - })); - const siteIds = sites.map((s) => s.siteId); + const allSites = listSites(); + // Every site stays a valid scope (siteIds); settings.privacy.hidePrivateSites + // only leaves the private ones out of the picker's list. + const siteIds = allSites.map((s) => s.siteId); + const hidePrivate = hidePrivateSites(); + const sites = allSites + .filter((s) => !(hidePrivate && isPrivateSite(s))) + .map((s) => ({ + siteId: s.siteId, + siteTitle: s.siteTitle, + })); + // The browser's display rules (settings.privacy; never the private files'), + // and the provider ONLY while there are some: absent, the tree is unchanged. + const privacyRules = clientPrivacyRules(); // THE SITE SCOPE, read once per request from its cookie and supplied to the // picker (and anything else that asks) by SiteScopeProvider. A layout has no // searchParams, so a `?site=` link is applied by the picker from the URL and @@ -136,6 +155,7 @@ export default async function RootLayout({ <body className="min-h-full flex flex-col md:flex-row bg-background text-foreground"> <ThemeScript /> <ThemeProvider> + {withPrivacy(privacyRules, <SiteScopeProvider activeSite={scope.value} fromCookie={scope.stored !== null} @@ -214,7 +234,8 @@ export default async function RootLayout({ > {children} </AppFrame> - </SiteScopeProvider> + </SiteScopeProvider>, + )} </ThemeProvider> </body> </html> diff --git a/editor/app/page.tsx b/editor/app/page.tsx @@ -1,3 +1,4 @@ +import { displayPath } from "yt-dlp-transcript-common/lib/privacy/privacy-server"; import { existsSync, readFileSync } from "node:fs"; import type { Metadata } from "next"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; @@ -127,6 +128,8 @@ export default async function Dashboard({ mediaLocationLabel: media ? locationLabelOfDataDir(media.target, locations) : undefined, + // settings.privacy: the badge's "relocated to <path>" as displayed. + show: displayPath, }); }); diff --git a/editor/app/saved-videos/page.tsx b/editor/app/saved-videos/page.tsx @@ -1,6 +1,7 @@ import type { Metadata } from "next"; import Link from "next/link"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { displayPath } from "yt-dlp-transcript-common/lib/privacy/privacy-server"; import { getSettings } from "yt-dlp-transcript-common/lib/settings"; import { formatBytes } from "yt-dlp-transcript-common/lib/format"; import { listSavedVideos } from "yt-dlp-transcript-common/controller/savedVideoInventory"; @@ -85,7 +86,7 @@ export default async function SavedVideosPage() { <section aria-label="store location" className="flex flex-col gap-1 text-sm"> <div> <span className="text-muted-foreground">Default store dir: </span> - <span className="font-mono">{paths.savedVideosDir}</span> + <span className="font-mono">{displayPath(paths.savedVideosDir)}</span> </div> <div> <span className="text-muted-foreground">Last backup: </span> diff --git a/editor/app/settings/page.tsx b/editor/app/settings/page.tsx @@ -1,6 +1,7 @@ import type { Metadata } from "next"; import Link from "next/link"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { displayPath } from "yt-dlp-transcript-common/lib/privacy/privacy-server"; import { getSettings } from "yt-dlp-transcript-common/lib/settings"; import { readXSessionStatus } from "yt-dlp-transcript-common/social/xSessionBroker"; import { resolveXCookieSourceFor } from "yt-dlp-transcript-common/social/xBrowserLogin"; @@ -133,7 +134,7 @@ export default async function SettingsPage() { <th className="text-left font-medium py-2 pr-4 align-top whitespace-nowrap"> {key} </th> - <td className="py-2 font-mono text-xs break-all">{value}</td> + <td className="py-2 font-mono text-xs break-all">{displayPath(value)}</td> </tr> ))} </tbody> diff --git a/editor/app/storage/components/SavedVideosStoreCard.tsx b/editor/app/storage/components/SavedVideosStoreCard.tsx @@ -1,5 +1,6 @@ "use client"; +import { useDisplay } from "yt-dlp-transcript-common/components/PrivacyProvider"; import Link from "next/link"; import { useState } from "react"; import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; @@ -31,6 +32,9 @@ import { // `disabled` rather than becoming a second Run button. export function SavedVideosStoreCard({ store }: { store: SavedVideosView }) { + // settings.privacy: the store's path and detail as displayed (client-side: + // never the private files' rules). + const { displayPath, displayText } = useDisplay(); const [destId, setDestId] = useState(() => store.destinations[0]?.id ?? ""); const [ranResumeHere, setRanResumeHere] = useState(false); const [note, setNote] = useState<string | null>(null); @@ -82,8 +86,8 @@ export function SavedVideosStoreCard({ store }: { store: SavedVideosView }) { <dd aria-label="saved videos location">{store.locationLabel}</dd> <dt className="text-muted-foreground">Path</dt> <dd className="font-mono text-xs break-all" aria-label="saved videos path"> - {store.at} - {store.at !== store.dir ? ` (read as ${store.dir})` : ""} + {displayPath(store.at)} + {store.at !== store.dir ? ` (read as ${displayPath(store.dir)})` : ""} </dd> <dt className="text-muted-foreground">Size</dt> <dd aria-label="saved videos bytes"> @@ -99,7 +103,7 @@ export function SavedVideosStoreCard({ store }: { store: SavedVideosView }) { aria-label="saved videos detail" className="text-sm rounded border border-border bg-muted px-3 py-2" > - {store.detail} + {displayText(store.detail)} </p> )} {store.busy && ( diff --git a/editor/app/storage/components/StorageLocationsTable.tsx b/editor/app/storage/components/StorageLocationsTable.tsx @@ -1,5 +1,6 @@ "use client"; +import { useDisplay } from "yt-dlp-transcript-common/components/PrivacyProvider"; import Link from "next/link"; import { useState } from "react"; import { useRouter } from "next/navigation"; @@ -130,6 +131,9 @@ function LocationCard({ row: StorageRow; onChanged: () => void; }) { + // settings.privacy: the root and the volume as displayed (client-side: + // never the private files' rules). Actions keep the real root. + const { displayPath, displayText } = useDisplay(); const [editing, setEditing] = useState(false); const [note, setNote] = useState<string | null>(null); const [error, setError] = useState<string | null>(null); @@ -208,14 +212,15 @@ function LocationCard({ a trap for a screen reader user for the same reason. */} <dt className="text-muted-foreground">Root</dt> <dd className="font-mono text-xs break-all" aria-label="location path"> - {row.root} + {displayPath(row.root)} </dd> <dt className="text-muted-foreground">Volume</dt> <dd className="text-xs" aria-label="volume identity"> {row.kind === "internal" ? "the corpus volume" - : (row.identity ?? - "unknown — nothing here can ask (no findmnt, or a container)")} + : row.identity != null + ? displayText(row.identity) + : "unknown — nothing here can ask (no findmnt, or a container)"} </dd> <dt className="text-muted-foreground">Channels</dt> {/* THE COUNT AND THE LINK ARE TWO ELEMENTS, not one. `location channels` diff --git a/editor/e2e/privacy-audit.spec.ts b/editor/e2e/privacy-audit.spec.ts @@ -0,0 +1,327 @@ +import { test, expect, type Browser } from "@playwright/test"; +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import { join } from "node:path"; +import { foldAscii, maskLiterals, type Literal } from "yt-dlp-transcript-common/publish/sourceAudit"; +import { + failingHits, + formatPrivacyReport, + incompleteReasons, + runPrivacyAudit, + type AuditBrowser, + type PrivacyAuditResult, +} from "yt-dlp-transcript-common/publish/privacyAudit"; +import { appRoutes } from "yt-dlp-transcript-common/lib/privacy/routes"; +import { DEFAULT_PRIVACY_SETTINGS } from "yt-dlp-transcript-common/lib/privacySettings"; +import { baseUrl } from "./baseUrl"; +import { resetData, testPaths } from "./helpers"; +import { EDITOR_ROOT } from "./testPaths"; + +// --------------------------------------------------------------------------- +// THE PRIVACY AUDIT OVER THE EDITOR (demo epic D4, slice 1). +// +// Every page route of editor/app (lib/privacy/routes.ts — derived, not typed), +// drawn by a browser with JavaScript off and on, searched for a denylist the +// spec writes at run time from FIXTURE values: this machine's home dir and +// hostname, a storage location's root and a private site's id and title (both +// planted). The literals are never printed: the report names them by line. +// +// 1. byte identity: with settings.privacy absent and at its defaults, every +// route's server HTML is byte-identical (routes whose HTML moves between +// two absent reads are skipped and counted), and so is a client-rendered +// seam's drawn text (/storage); +// 2. positive control, privacy OFF: the scanner finds the literals in text +// nodes, in an attribute (the private site's id in /sites' aria-label) +// and in an option label (the private site in the scope picker); +// 3. masked, privacy ON: no hit on any route but the slice-2 ones listed +// below (their per-route live/ssr counts go in the test's annotations); +// 4. the private files' rules (useSourceRules) are SERVER-SIDE ONLY: with +// the home dir only in the (fixture) source denylist, the server-rendered +// /settings System paths lose their hits and the client-rendered /storage +// root keeps its own. +// +// WRITES the slot's test-settings.json, a site and the source rule files under +// test-transcripts (servers.ts points SOURCE_SCRUB_FILE / SOURCE_DENYLIST_FILE +// there); resetData() restores the fixture after. +// --------------------------------------------------------------------------- + +test.describe.configure({ mode: "serial" }); +test.setTimeout(600_000); + +const paths = testPaths(); +const APP_DIR = join(EDITOR_ROOT, "app"); +const SITES = join(paths.transcriptsDir, "sites"); +const PRIVATE_ID = "zq-private-fixture"; +const PRIVATE_TITLE = "Zq Private Title"; +// A second, PUBLIC site (review round 1, S1): with it the /channels rack and +// its Focus bar render, so the masked run looks at them, not at an empty state. +const PUBLIC_ID = "zq-public-fixture"; +const CHANNEL = "test-youtube"; +const DRIVE_ROOT = join(paths.root, "test-transcripts", ".privacy-drive"); +const RULES_DIR = join(paths.transcriptsDir, ".privacy"); + +// Routes whose leaks are slice 2: the masked test reports their counts and +// does not fail on them. Measured on the first masked run (12 Nov): the +// private site's OWN pages, which hidePrivateSites leaves reachable by design +// and the /sites index (slice 2) still links to — its id and title in the +// text, title and URL; and /channels/new's site memberships (its title in an +// aria-label), a FORM whose hiding needs care on the edit page so a save never +// drops a hidden membership; and /operations/publish's lane list (the private +// site's id in a <code>). Job logs and /workers are slice 2 too (no fixture +// leak there today). +// Dynamic routes no fixture page links to (the audit reports them; the masked +// test names them, so a NEW unreached route fails it). +const UNREACHABLE = ["/channels/[slug]/captures", "/channels/[slug]/local-media", "/channels/[slug]/videos/[id]", "/jobs/[id]"]; + +const SLICE_2 = new Set<string>([ + "/sites", + "/sites/[siteId]", + "/sites/[siteId]/aliases", + "/sites/[siteId]/charts", + "/sites/[siteId]/publish", + "/sites/[siteId]/reports", + "/sites/[siteId]/tags", + "/channels/new", + "/operations/publish", + "/jobs/[id]", + "/workers", +]); + +const lit = (text: string, from: string, ci = false): Literal => ({ + bytes: ci ? foldAscii(Buffer.from(text, "utf8")) : Buffer.from(text, "utf8"), + ci, + from, +}); +const HOME = os.homedir(); +const literals = (): Literal[] => [ + lit(HOME, "fixture literal 1 (home dir)"), + lit(os.hostname(), "fixture literal 2 (hostname)"), + lit(DRIVE_ROOT, "fixture literal 3 (location root)"), + lit(PRIVATE_TITLE, "fixture literal 4 (private site title)"), + lit(PRIVATE_ID, "fixture literal 5 (private site id)"), +]; + +function settings(privacy: Record<string, unknown> | null) { + const s = JSON.parse(readFileSync(paths.settingsFile, "utf8")) as Record<string, unknown>; + delete s.privacy; + if (privacy) s.privacy = privacy; + s.storage = { + locations: [{ id: "zq-drive", label: "Zq Drive", root: DRIVE_ROOT, autoRepoint: false }], + defaultLocationId: "", + }; + // The focus on the PRIVATE site: /channels' Focus bar names it unless hidden. + const cp = (s.channelPriority ?? {}) as Record<string, unknown>; + s.channelPriority = { ...cp, focus: { kind: "site", siteId: PRIVATE_ID } }; + writeFileSync(paths.settingsFile, `${JSON.stringify(s, null, 2)}\n`); +} +// Where two renders first differ, the window around it masked (never a literal). +const firstDiff = (x: string, y: string) => { + let i = 0; + while (i < x.length && x[i] === y[i]) i++; + if (i === x.length && i === y.length) return ""; + const at = (s: string) => JSON.stringify(maskLiterals(s.slice(Math.max(0, i - 80), i + 80), literals())); + return ` — first differs at ${i}: ${at(x)} vs ${at(y)}`; +}; +// The server's privacy memo re-checks the file at most once a second. +const settle = () => new Promise((r) => setTimeout(r, 1300)); + +async function audit(browser: Browser, include?: (route: string) => boolean): Promise<PrivacyAuditResult> { + return runPrivacyAudit({ + targets: [{ app: "editor", baseUrl, appDir: APP_DIR }], + literals: literals(), + browser: browser as unknown as AuditBrowser, + maxPerRoute: 1, + include: include ? (_app, r) => include(r) : undefined, + }); +} + +let madeChangelog = false; + +test.beforeAll(async () => { + await resetData("one-youtube-channel-with-data"); + const siteJson = (siteId: string, siteTitle: string, extra: Record<string, unknown>) => ({ + siteId, + siteTitle, + groups: [{ id: "default", name: "All channels", selectedByDefault: true }], + defaultGroupId: "default", + channels: [{ slug: CHANNEL, groupId: "default" }], + ...extra, + }); + for (const [id, title, extra] of [ + [PRIVATE_ID, PRIVATE_TITLE, { audience: "private" }], + [PUBLIC_ID, "Zq Public Title", {}], + ] as const) { + mkdirSync(join(SITES, id), { recursive: true }); + writeFileSync(join(SITES, id, "site.json"), JSON.stringify(siteJson(id, title, extra), null, 2)); + } + mkdirSync(DRIVE_ROOT, { recursive: true }); + mkdirSync(RULES_DIR, { recursive: true }); + // /changelog reads the slot's disposable EDITOR_CHANGELOG_FILE, which only + // the changelog specs write: without one the page answers 500 and the audit + // is (rightly) incomplete. A one-line file, removed after if made here. + if (!existsSync(paths.editorChangelog)) { + writeFileSync(paths.editorChangelog, "# Changelog\n\n## [Unreleased]\n- A fixture line.\n"); + madeChangelog = true; + } +}); + +test.afterAll(async () => { + rmSync(RULES_DIR, { recursive: true, force: true }); + if (madeChangelog) rmSync(paths.editorChangelog, { force: true }); + await resetData(); +}); + +test("byte identity: absent and explicit defaults render the same HTML, and the same /storage text", async ({ browser }) => { + const statics = appRoutes(APP_DIR).filter((r) => !r.dynamic).map((r) => r.pattern); + const fetchHtml = async (r: string) => { + const res = await fetch(`${baseUrl}${r}`, { redirect: "manual" }); + return `${res.status}\n${await res.text()}`; + }; + const storageText = async () => { + const ctx = await browser.newContext(); + const page = await ctx.newPage(); + await page.goto(`${baseUrl}/storage`); + await expect(page.getByLabel("location path").first()).toBeVisible(); + // The client-rendered seams themselves (useDisplay): a location's root and + // the saved-video store's path — not the page, whose probe ages tick. + const text = (await page.locator('[aria-label="location path"], [aria-label="saved videos path"]').allInnerTexts()).join("\n"); + await ctx.close(); + return text; + }; + // Per route, absent and explicit defaults read in turn, each a moment after + // its switch. The server streams its Suspense boundaries in whatever order + // they finish, so one read is one of a few byte strings: a route passes when + // a defaults read is byte-identical to an absent read (up to four rounds). + // One whose absent reads never repeat and never meet is volatile, skipped + // and counted; a STABLE absent read that no defaults read matches fails. + let compared = 0; + const volatile: string[] = []; + for (const r of statics) { + const absent = new Set<string>(); + const given = new Set<string>(); + let same = false; + for (let round = 0; round < 4 && !same; round++) { + settings(null); + await settle(); + absent.add(await fetchHtml(r)); + settings({ ...DEFAULT_PRIVACY_SETTINGS }); + await settle(); + given.add(await fetchHtml(r)); + same = [...given].some((g) => absent.has(g)); + } + if (same) { + compared++; + continue; + } + if (absent.size > 1) { + volatile.push(r); + continue; + } + const [a] = absent; + const [b] = given; + expect(same, `${r}: explicit defaults render the HTML the absent block does${firstDiff(a, b)}`).toBe(true); + } + // A client-rendered seam's drawn text (no clock in it): absent vs defaults. + settings(null); + await settle(); + const aText = await storageText(); + settings({ ...DEFAULT_PRIVACY_SETTINGS }); + await settle(); + const bText = await storageText(); + settings(null); + await settle(); + test.info().annotations.push({ type: "byte-identity", description: `${compared} of ${statics.length} static routes compared; volatile, skipped: ${volatile.join(" ") || "none"}` }); + expect(compared).toBeGreaterThan(statics.length / 2); + expect(bText).toBe(aText); +}); + +test("positive control, privacy off: text, an attribute and an option label are all seen", async ({ browser }) => { + settings(null); + await settle(); + const result = await audit(browser); + const hits = failingHits(result); + const report = formatPrivacyReport(result, literals()).join("\n"); + for (const l of literals()) expect(report.includes(l.bytes.toString("utf8")), "the report never carries a literal").toBe(false); + test.info().annotations.push({ type: "positive", description: report.split("\n").slice(0, 12).join(" | ") }); + const kinds = new Set(hits.map((h) => h.where)); + expect(kinds.has("text")).toBe(true); + expect(kinds.has("option"), "the scope picker's private site").toBe(true); + expect(["title", "aria-label", "alt", "placeholder", "aria-description"].some((k) => kinds.has(k as never)), "an attribute").toBe(true); + expect(hits.some((h) => h.route === "/settings" && h.lit === 0), "the System paths name the home dir").toBe(true); + expect(hits.some((h) => h.route === "/storage" && h.lit === 2), "the location root").toBe(true); +}); + +test("masked, privacy on: no hit outside the slice-2 routes", async ({ browser }) => { + settings({ displayPaths: "masked", hideHost: true, hidePrivateSites: true, maskEmail: true, aliases: [], useSourceRules: false }); + await settle(); + const result = await audit(browser); + const hits = failingHits(result); + const outside = hits.filter((h) => !SLICE_2.has(h.route)); + const byRoute = new Map<string, { live: number; ssr: number }>(); + for (const h of hits) { + const c = byRoute.get(h.route) ?? { live: 0, ssr: 0 }; + c[h.pass]++; + byRoute.set(h.route, c); + } + test.info().annotations.push({ + type: "masked per route (live/ssr)", + description: [...byRoute].map(([r, c]) => `${r} ${c.live}/${c.ssr}`).join("; ") || "none", + }); + test.info().annotations.push({ + type: "masked coverage", + description: `${result.pages.length} pages; not reached: ${result.notReached.map((r) => r.route).join(" ") || "none"}`, + }); + expect(outside.map((h) => `${h.route} ${h.pass} ${h.where} ${h.selector} lit${h.lit + 1}`)).toEqual([]); + // Complete (review round 1, M4): every page loaded, every route reached but + // the ones named here, which no fixture page links to. + const bad = result.pages.filter((p) => p.error || (p.status !== null && p.status >= 400)).map((p) => `${p.route} ${p.status ?? p.error}`); + expect(incompleteReasons({ ...result, allowUnreached: UNREACHABLE }), `pages: ${bad.join("; ")}`).toEqual([]); + // The rack rendered (S1): the masked run looked at the Focus bar, not an empty state. + expect(result.pages.some((p) => p.route === "/channels" && p.status === 200)).toBe(true); + // The private site is out of the picker; the page still opens by URL. + const ctx = await browser.newContext(); + const page = await ctx.newPage(); + await page.goto(`${baseUrl}/`); + await expect(page.getByLabel("Active site").locator("option")).not.toHaveText([PRIVATE_TITLE]); + await expect(page.getByLabel("Active site").locator(`option[value="${PRIVATE_ID}"]`)).toHaveCount(0); + await ctx.close(); +}); + +test("a hidden membership survives a save of the channel's configure tab", async ({ page }) => { + settings({ ...DEFAULT_PRIVACY_SETTINGS, hidePrivateSites: true }); + await settle(); + await page.goto(`/channels/${CHANNEL}?stage=configure`); + await expect(page.getByLabel("Include on Zq Public Title")).toBeChecked(); + await expect(page.getByLabel(`Include on ${PRIVATE_TITLE}`)).toHaveCount(0); + await expect(page.getByText(PRIVATE_ID)).toHaveCount(0); + // The save visibly does something (the public membership goes), so the + // poll below waits for the save itself, then checks the hidden one stayed. + const box = page.getByLabel("Include on Zq Public Title"); + await expect(async () => { + await box.uncheck(); + await expect(box).not.toBeChecked(); + }).toPass(); + await page.getByRole("button", { name: /save changes/i }).click(); + const read = (id: string) => JSON.parse(readFileSync(join(SITES, id, "site.json"), "utf8")) as { channels: Array<{ slug: string }> }; + await expect.poll(() => read(PUBLIC_ID).channels.map((c) => c.slug)).toEqual([]); + expect(read(PRIVATE_ID).channels.map((c) => c.slug)).toEqual([CHANNEL]); +}); + +test("the private files' rules are server-side only: /settings loses its hits, /storage keeps its own", async ({ browser }) => { + writeFileSync(join(RULES_DIR, "source-scrub.txt"), "# none\n"); + writeFileSync(join(RULES_DIR, "source-denylist.txt"), `${HOME}\n`); + settings(null); + await settle(); + const off = failingHits(await audit(browser, (r) => r === "/settings" || r === "/storage")); + settings({ ...DEFAULT_PRIVACY_SETTINGS, useSourceRules: true }); + await settle(); + const on = failingHits(await audit(browser, (r) => r === "/settings" || r === "/storage")); + const n = (hs: typeof on, route: string, l: number) => hs.filter((h) => h.route === route && h.lit === l && h.pass === "live").length; + test.info().annotations.push({ + type: "server vs client (home-dir hits, live)", + description: `/settings ${n(off, "/settings", 0)} → ${n(on, "/settings", 0)}; /storage ${n(off, "/storage", 0)} → ${n(on, "/storage", 0)}`, + }); + expect(n(on, "/settings", 0)).toBeLessThan(n(off, "/settings", 0)); + // The client-rendered location root does not get the files' rules. + expect(n(on, "/storage", 2)).toBeGreaterThan(0); +}); diff --git a/editor/e2e/servers.ts b/editor/e2e/servers.ts @@ -247,6 +247,11 @@ export function slotServers(slot: number, mode: E2EMode, env: Env = process.env) editorEnv.E2E_FORUM_FIXTURE_DIR = forumFixtureDir(paths.transcriptsDir); // The same for the stub umtool find-clips.spec starts (lib/umtoolUrl.ts). editorEnv.E2E_UMTOOL_ORIGIN_FILE = umtoolOriginFile(paths.transcriptsDir); + // settings.privacy's opt-in rule files (demo epic D4, useSourceRules): the + // slot's own, which privacy-audit.spec writes. Their default is the + // operator's ~/.config/archilyzer, which a suite must never read. + editorEnv.SOURCE_SCRUB_FILE = join(paths.transcriptsDir, ".privacy", "source-scrub.txt"); + editorEnv.SOURCE_DENYLIST_FILE = join(paths.transcriptsDir, ".privacy", "source-denylist.txt"); // The browser lookup's recorded page reads (browser-lookup.spec): set on // every slot, so the e2e server never opens a headless browser on the // network — the player-page opener refuses under it too. diff --git a/settings.json.example b/settings.json.example @@ -385,5 +385,14 @@ "enabled": false, "afterSync": false, "items": [] + }, + "privacy": { + "displayPaths": "full", + "hideHost": false, + "hideUser": false, + "hidePrivateSites": false, + "aliases": [], + "maskEmail": false, + "useSourceRules": false } } diff --git a/umtool/app/create/page.tsx b/umtool/app/create/page.tsx @@ -4,6 +4,7 @@ import AppShell from "@/components/shell/AppShell"; import { readCreate } from "@/lib/create"; import { policyChip } from "@/lib/create/policy.mjs"; import { generationPolicyHref, isMake, type Make } from "@/lib/hrefs"; +import { shownSources } from "@/lib/research/sources"; export const dynamic = "force-dynamic"; @@ -30,6 +31,10 @@ export default async function CreatePage({ const from = typeof sp.from === "string" && sp.from.trim() ? sp.from.trim() : null; const initial: Make | null = from ? "video-recording" : isMake(sp.make) ? sp.make : null; const data = await readCreate(); + // settings.privacy.hidePrivateSites: the research form's source picker + // DRAWS no private site (the data itself stays whole). + const sources = await shownSources(data.sources); + const shown = sources === data.sources ? data : { ...data, sources }; const chip = policyChip(data.policy?.generation ?? null, data.policy?.tasks); return ( @@ -51,7 +56,7 @@ export default async function CreatePage({ } /> <main className="deck-main flex-1 px-4 pb-6 pt-4"> - <CreateView data={data} initial={initial} from={from} initialCase={sp.case ?? null} initialArticle={sp.article ?? null} /> + <CreateView data={shown} initial={initial} from={from} initialCase={sp.case ?? null} initialArticle={sp.article ?? null} /> </main> </div> ); diff --git a/umtool/app/jobs/page.tsx b/umtool/app/jobs/page.tsx @@ -7,6 +7,7 @@ import { ActivityPanel } from "@/components/system/Status"; import { Panel } from "@/components/ui/panel"; import { listActivity, runningActivity } from "@/lib/activity"; import { queueView, rendersView } from "@/lib/queue/view"; +import { displayText } from "yt-dlp-transcript-common/lib/privacy/privacy-server"; export const dynamic = "force-dynamic"; export const metadata: Metadata = { title: "Jobs · umtool" }; @@ -39,7 +40,7 @@ export default async function JobsPage() { ) : ( <div className="space-y-1.5"> {renders.map((r) => ( - <RenderRecord key={`${r.project}:${r.take}`} project={r.project ?? ""} rec={r} showProject compact={r.state === "done"} /> + <RenderRecord key={`${r.project}:${r.take}`} project={r.project ?? ""} rec={r} showProject compact={r.state === "done"} show={displayText} /> ))} </div> )} diff --git a/umtool/app/layout.tsx b/umtool/app/layout.tsx @@ -5,6 +5,8 @@ import { fontVariables } from "./fonts"; import { LastPageRecorder } from "@/components/LastPage"; import JumpPalette from "@/components/shell/JumpPalette"; import { THEME_COOKIE, parseTheme, themeAttr } from "@/lib/theme"; +import { PrivacyProvider } from "yt-dlp-transcript-common/components/PrivacyProvider"; +import { clientPrivacyRules } from "yt-dlp-transcript-common/lib/privacy/privacy-server"; export const metadata: Metadata = { title: "umtool", @@ -31,13 +33,16 @@ export const viewport: Viewport = { // route dynamic; every page here reads the disk per request anyway. export default async function RootLayout({ children }: { children: React.ReactNode }) { const theme = parseTheme((await cookies()).get(THEME_COOKIE)?.value); + // The browser's display rules (settings.privacy; never the private files'), + // and the provider only while there are some: absent, the tree is unchanged. + const privacy = clientPrivacyRules(); return ( <html lang="en" data-theme={themeAttr(theme)} className={fontVariables}> <body className="h-full"> {/* Writes down where you are, so / can bring you back. Renders nothing, and needs no Suspense boundary -- see components/LastPage.tsx. */} <LastPageRecorder /> - {children} + {privacy ? <PrivacyProvider rules={privacy}>{children}</PrivacyProvider> : children} {/* ⌘K, on every page -- a bench with no rail included. */} <JumpPalette /> </body> diff --git a/umtool/app/page.tsx b/umtool/app/page.tsx @@ -7,6 +7,7 @@ import { buttonVariants } from "@/components/ui/button"; import { machineCalls } from "@/lib/machine"; import { homeHref, systemHref } from "@/lib/hrefs"; import { readInbox, type GroupCard, type GroupSummary } from "@/lib/inbox"; +import { privateFilter } from "@/lib/privacy"; import { summarizeGroups } from "@/lib/inbox/groups.mjs"; import { headlineNote, inboxHeadline } from "@/lib/inbox/headline.mjs"; import { whatOf } from "@/lib/inbox/what.mjs"; @@ -100,7 +101,8 @@ export default async function Inbox({ searchParams: Promise<{ hidden?: string; muted?: string }>; }) { const { hidden: showHidden, muted: showMuted } = await searchParams; - const inbox = await readInbox(); + // settings.privacy.hidePrivateSites: the private sites' cards are left out. + const inbox = await readInbox({ hide: await privateFilter() }); const lifeOf = new Map<string, LifecycleState>(); for (const d of inbox.items) if (d.piece && d.lifecycle) lifeOf.set(d.piece, d.lifecycle as LifecycleState); diff --git a/umtool/app/projects/page.tsx b/umtool/app/projects/page.tsx @@ -12,6 +12,7 @@ import ProjectGrid from "@/components/projects/ProjectGrid"; import { KINDS, decisionCounts, indexHealth, listFolders, listProjects } from "@/lib/projects"; import { PROJECT_STATES } from "@/lib/project-types"; import { projectsNote } from "@/lib/system/status"; +import { privateFilter } from "@/lib/privacy"; export const dynamic = "force-dynamic"; @@ -50,7 +51,10 @@ export default async function BrowsePage({ const sp = await searchParams; const { kind, template, state, open, q, sort } = sp; - const all = await listProjects(); + // settings.privacy.hidePrivateSites: a private site's projects are left out. + const hide = await privateFilter(); + const listed = await listProjects(); + const all = hide ? listed.filter((p) => !hide.projects.has(p.id)) : listed; const counts = await decisionCounts(); const folders = await listFolders(); diff --git a/umtool/app/research/archive/page.tsx b/umtool/app/research/archive/page.tsx @@ -5,7 +5,7 @@ import { badgeVariants } from "@/components/ui/badge"; import { scopeFrom } from "@/lib/research/corpus"; import { coverageOf } from "@/lib/research/coverage"; import { researchArchiveHref, researchHref } from "@/lib/research/hrefs"; -import { listSources } from "@/lib/research/sources"; +import { listSources, shownSources } from "@/lib/research/sources"; import type { CoverageResponse } from "@/lib/research/types"; export const dynamic = "force-dynamic"; @@ -30,6 +30,9 @@ export default async function ArchivePage({ searchParams }: { searchParams: Prom error = (e as Error).message; } const at = (handle: string) => (handle === sources[0].handle ? undefined : handle); + // settings.privacy.hidePrivateSites: what the source links DRAW (the full + // list above stays the allow-list and the default). + const shown = await shownSources(sources, scope.source); return ( <div className="flex h-full flex-col"> <AppShell @@ -39,7 +42,7 @@ export default async function ArchivePage({ searchParams }: { searchParams: Prom note={data ? `${data.rows.length} channels · ${data.years.length ? `${data.years[0]}–${data.years[data.years.length - 1]}` : "no dates"}` : undefined} /> <nav aria-label="Source" className="flex flex-wrap items-center gap-1.5 border-b border-seam px-7 py-2.5"> - {sources.map((s) => ( + {shown.map((s) => ( <Link key={s.handle} href={researchArchiveHref({ source: at(s.handle) })} diff --git a/umtool/app/research/page.tsx b/umtool/app/research/page.tsx @@ -6,7 +6,7 @@ import { listCases } from "@/lib/research/boards"; import { scopeFrom, scopeOf } from "@/lib/research/corpus"; import { researchArchiveHref } from "@/lib/research/hrefs"; import { runsHref } from "@/lib/research/runs-hrefs"; -import { listSources } from "@/lib/research/sources"; +import { listSources, shownSources } from "@/lib/research/sources"; import type { ScopeSummary } from "@/lib/research/types"; export const dynamic = "force-dynamic"; @@ -52,7 +52,7 @@ export default async function ResearchPage({ searchParams }: { searchParams: Pro } /> <ResearchView - sources={sources} + sources={await shownSources(sources, scope.source)} initialQuery={q} initialScope={scope} initialSummary={summary} diff --git a/umtool/app/work/page.tsx b/umtool/app/work/page.tsx @@ -15,6 +15,7 @@ import { createHref, siteHref, workHref, type WorkQuery } from "@/lib/hrefs"; import { ARTICLES_KEY } from "@/lib/articles/key.mjs"; import { KINDS } from "@/lib/projects"; import { readWork, type WorkRow } from "@/lib/work"; +import { privateFilter } from "@/lib/privacy"; import { LIFECYCLES, STAGES, keepRow, lifeFilter, sortRows } from "@/lib/work/facets.mjs"; import { cn } from "@/lib/utils"; @@ -62,7 +63,11 @@ const EXTRA: { key: keyof Search; label: string }[] = [ export default async function WorkPage({ searchParams }: { searchParams: Promise<Search> }) { const sp = await searchParams; - const { rows: all, lifecycleError } = await readWork(); + const { rows: read, lifecycleError } = await readWork(); + // settings.privacy.hidePrivateSites: the rows DRAWN leave out a private + // site's pieces and the projects they own (readWork itself stays whole). + const hide = await privateFilter(); + const all = hide ? read.filter((r) => !hide.pieces.has(r.id) && !(r.project && hide.projects.has(r.project))) : read; const q = sp as Record<string, string | undefined>; const shown = sortRows( all.filter((r) => keepRow(r, q)), diff --git a/umtool/components/CopyButton.tsx b/umtool/components/CopyButton.tsx @@ -1,6 +1,7 @@ "use client"; import { useState } from "react"; +import { useDisplay } from "yt-dlp-transcript-common/components/PrivacyProvider"; // Put something on the clipboard, and fall back visibly when that is not // allowed. @@ -21,6 +22,9 @@ type Props = { }; export default function CopyButton({ text, url, label = "copy", title, className }: Props) { + // settings.privacy: the clipboard always gets the REAL text; only the + // on-screen fallback box below is drawn through the displayer. + const { displayText } = useDisplay(); const [state, setState] = useState<"idle" | "busy" | "done" | "failed">("idle"); const [fallback, setFallback] = useState<string | null>(null); @@ -55,7 +59,7 @@ export default function CopyButton({ text, url, label = "copy", title, className <button type="button" onClick={run} - title={title} + title={title === undefined ? undefined : displayText(title)} data-copy data-state={state} className={ @@ -68,13 +72,15 @@ export default function CopyButton({ text, url, label = "copy", title, className {fallback !== null && ( <div className="mt-1 w-full"> <p className="text-[10px] text-[var(--color-dim)]"> - the clipboard was refused — select and copy: + {displayText(fallback) === fallback + ? "the clipboard was refused — select and copy:" + : "the clipboard was refused — privacy is on, so this is the text as shown, not the real one:"} </p> <textarea readOnly autoFocus onFocus={(e) => e.currentTarget.select()} - value={fallback} + value={displayText(fallback)} rows={8} className="w-full rounded border border-[var(--color-line)] bg-[var(--color-ink)] p-2 font-mono text-[11px] text-[var(--color-text)]" /> diff --git a/umtool/components/projects/TakeVariants.tsx b/umtool/components/projects/TakeVariants.tsx @@ -5,6 +5,7 @@ import { useRouter } from "next/navigation"; import { useState } from "react"; import DeletePlan from "@/components/DeletePlan"; import RenderRecord from "@/components/queue/RenderRecord"; +import { useDisplay } from "yt-dlp-transcript-common/components/PrivacyProvider"; import type { RenderView } from "@/lib/queue/view"; import { buttonVariants } from "@/components/ui/button"; import { takesCompareHref, takesHref } from "@/lib/hrefs"; @@ -186,6 +187,7 @@ export function CompareWith({ project, take, options }: { project: string; take: */ export function TakeWorkDirs({ project, dirs, ready }: { project: string; dirs: WorkDirs; ready: boolean }) { const router = useRouter(); + const { displayText } = useDisplay(); const [show, setShow] = useState(false); const [said, setSaid] = useState<CancelSaid | null>(null); const failed = dirs.failed ?? []; @@ -222,7 +224,7 @@ export function TakeWorkDirs({ project, dirs, ready }: { project: string; dirs: <DeletePlan label={`Delete take ${f.id}`} subject={`the failed take ${f.id}`} endpoint="/api/report/takes/delete" body={{ project, take: f.id }} onDone={() => router.refresh()} /> </span> </div> - <RenderRecord project={project} rec={f.record} /> + <RenderRecord project={project} rec={f.record} show={displayText} /> </div> ))} {dirs.cancelled.length > 0 && ( diff --git a/umtool/components/projects/TakesBench.tsx b/umtool/components/projects/TakesBench.tsx @@ -13,6 +13,7 @@ import { fmtAgo, fmtBytes } from "@/lib/format"; import { cn } from "@/lib/utils"; import { openInDraftHref, playHref, presentHref } from "@/lib/hrefs"; import RenderRecord from "@/components/queue/RenderRecord"; +import { useDisplay } from "yt-dlp-transcript-common/components/PrivacyProvider"; import type { RenderView } from "@/lib/queue/view"; import { BenchBody, VerdictBar } from "./bench/BenchShell"; import { startTakeJob } from "./NewTakePanel"; @@ -552,6 +553,7 @@ function TakeCard({ onFreed: () => void; }) { const notes = useSharedNotes({ project }); + const { displayText } = useDisplay(); const router = useRouter(); // The element, for the timed notes; the parent's callback (audio routing) // still gets it. Stable, so it runs once per mount, not once per render. @@ -790,7 +792,7 @@ function TakeCard({ </button> </div> {t.summary && <p className="text-[12px] text-[var(--color-text)]">{t.summary}</p>} - {t.render && <RenderRecord project={project} rec={t.render} compact />} + {t.render && <RenderRecord project={project} rec={t.render} compact show={displayText} />} {t.changes.length > 0 && ( <ul className="list-disc pl-4 text-[11px] text-[var(--color-dim)]"> {t.changes.map((c, i) => ( diff --git a/umtool/components/projects/inspector/ProvenanceInspector.tsx b/umtool/components/projects/inspector/ProvenanceInspector.tsx @@ -2,6 +2,7 @@ import { useCallback, useEffect, useState } from "react"; import { useRouter } from "next/navigation"; +import { useDisplay } from "yt-dlp-transcript-common/components/PrivacyProvider"; import { Button } from "@/components/ui/button"; import { Field, Input } from "@/components/ui/field"; import LinkPolicyPanel from "../report/LinkPolicyPanel"; @@ -24,6 +25,8 @@ const KEYS = ["siteOrigin", "channelSlug", "channel"] as const; export default function ProvenanceInspector({ project }: InspectorProps) { const router = useRouter(); + // settings.privacy: a site's title as the suggestion DRAWS it (client-side). + const { displayText } = useDisplay(); const [view, setView] = useState<View | null>(null); const [draft, setDraft] = useState<Record<(typeof KEYS)[number], string>>({ siteOrigin: "", channelSlug: "", channel: "" }); const [busy, setBusy] = useState(false); @@ -83,7 +86,7 @@ export default function ProvenanceInspector({ project }: InspectorProps) { <datalist id={`prov-sites-${project}`}> {view.sites.map((s) => ( <option key={s.origin} value={s.origin}> - {s.title ?? s.siteId} + {displayText(s.title ?? s.siteId)} </option> ))} </datalist> diff --git a/umtool/components/queue/QueuePanel.tsx b/umtool/components/queue/QueuePanel.tsx @@ -6,6 +6,7 @@ import { badgeVariants, type BadgeVariants } from "@/components/ui/badge"; import { buttonVariants } from "@/components/ui/button"; import { queueLogHref } from "@/lib/hrefs"; import type { RunnerView, StepView } from "@/lib/queue/view"; +import { useDisplay } from "yt-dlp-transcript-common/components/PrivacyProvider"; // THE DURABLE QUEUE (lib/queue/store.mjs), as a list: the runner (is the umtool // app running it), then each step -- its qid, state, label, what it waits on, @@ -33,6 +34,9 @@ const clock = (iso: string | null) => (iso ? iso.slice(11, 16) : ""); export default function QueuePanel({ initial, project = null, emptyText = "Nothing queued." }: { initial: View; project?: string | null; emptyText?: string }) { const router = useRouter(); + // settings.privacy: what a step's label, command and error DRAW (client-side, + // so never the private files' rules); the identity when it is off. + const { displayText } = useDisplay(); const [view, setView] = useState<View>(initial); const [said, setSaid] = useState<{ text: string; ok: boolean } | null>(null); const [ready, setReady] = useState(false); @@ -80,7 +84,7 @@ export default function QueuePanel({ initial, project = null, emptyText = "Nothi {runner.live ? ( <> Run by the umtool app (pid {runner.pid}) one step at a time. - {runner.waiting ? <span className="text-[var(--color-dim)]"> {runner.waiting}.</span> : null} + {runner.waiting ? <span className="text-[var(--color-dim)]"> {displayText(runner.waiting)}.</span> : null} </> ) : ( <span className="text-reject-text">No runner: nothing in the queue runs until the umtool app is up (archilyzer-umtool.service).</span> @@ -91,7 +95,7 @@ export default function QueuePanel({ initial, project = null, emptyText = "Nothi </p> {said && ( <p className={`m-0 text-[11.5px] ${said.ok ? "text-text-2" : "text-reject-text"}`} data-queue-said=""> - {said.text} + {displayText(said.text)} </p> )} {view.steps.length === 0 ? ( @@ -110,8 +114,8 @@ export default function QueuePanel({ initial, project = null, emptyText = "Nothi <div className="flex flex-wrap items-baseline gap-2"> <span className="font-mono text-text">{s.qid}</span> <span className={badgeVariants({ variant: TONE[s.state], size: "sm" })}>{s.state}</span> - <span className="min-w-0 truncate" title={`umtool ${s.argv.join(" ")}`} data-queue-label=""> - {s.label} + <span className="min-w-0 truncate" title={displayText(`umtool ${s.argv.join(" ")}`)} data-queue-label=""> + {displayText(s.label)} </span> {s.after && <span className="text-[11px] text-[var(--color-dim)]">after {s.after}</span>} <span className="num text-[11px] text-[var(--color-dim)]" suppressHydrationWarning> @@ -139,7 +143,7 @@ export default function QueuePanel({ initial, project = null, emptyText = "Nothi </div> {s.error && ( <p className="m-0 font-mono text-[11px] text-reject-text" data-queue-error=""> - {s.error} + {displayText(s.error)} </p> )} </li> diff --git a/umtool/components/queue/RenderRecord.tsx b/umtool/components/queue/RenderRecord.tsx @@ -10,6 +10,11 @@ import type { RenderView } from "@/lib/queue/view"; // stage and percent while it runs, and when it failed the error, the log's // last lines (folded) and the full log. Server-safe: no hooks. Used by the // Takes panel (a take's card, a first render that failed) and /jobs. +// +// `show` is the page's displayer (settings.privacy, demo epic D4): the +// server's displayText on /jobs, useDisplay()'s in a client panel; the +// identity when absent. It changes what is DRAWN — the path, the error, the +// tail — never the copied path or a data-* attribute. const TONE: Record<RenderView["state"], BadgeVariants["variant"]> = { queued: "info", @@ -20,6 +25,8 @@ const TONE: Record<RenderView["state"], BadgeVariants["variant"]> = { cancelled: "state", }; +const same = (s: string) => s; + const clock = (iso: string | null) => (iso ? iso.slice(0, 16).replace("T", " ") : ""); export default function RenderRecord({ @@ -27,6 +34,7 @@ export default function RenderRecord({ rec, showProject = false, compact = false, + show = same, }: { project: string; rec: RenderView; @@ -34,6 +42,8 @@ export default function RenderRecord({ showProject?: boolean; /** A take's card: one line, the tail folded. */ compact?: boolean; + /** The displayer for drawn text (settings.privacy); identity by default. */ + show?: (s: string) => string; }) { const live = rec.state === "running" || rec.state === "waiting"; // The output file as a local path (never an /api/ URL shown as where a file is). @@ -77,19 +87,19 @@ export default function RenderRecord({ </div> {rec.state === "done" && mp4Path && ( <p className="m-0 flex flex-wrap items-center gap-1.5 font-mono text-[11px] text-text-2" data-render-mp4={mp4Path}> - {mp4Path} + {show(mp4Path)} <CopyButton text={mp4Path} label="copy path" /> </p> )} {rec.error && ( <p className="m-0 font-mono text-[11px] text-reject-text" data-render-error=""> - {rec.error} + {show(rec.error)} </p> )} {bad && rec.tail?.length > 0 && ( <details data-render-tail="" open={!compact}> <summary className="cursor-pointer text-[11px] text-[var(--color-dim)]">the log&rsquo;s last {Math.min(rec.tail.length, 40)} lines</summary> - <pre className="m-0 mt-1 max-h-56 overflow-auto whitespace-pre-wrap break-all rounded bg-panel-2 p-1.5 text-[10.5px] leading-snug">{rec.tail.slice(-40).join("\n")}</pre> + <pre className="m-0 mt-1 max-h-56 overflow-auto whitespace-pre-wrap break-all rounded bg-panel-2 p-1.5 text-[10.5px] leading-snug">{show(rec.tail.slice(-40).join("\n"))}</pre> </details> )} </div> diff --git a/umtool/components/research/BoardView.tsx b/umtool/components/research/BoardView.tsx @@ -3,6 +3,7 @@ import Link from "next/link"; import { useRouter } from "next/navigation"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { useDisplay } from "yt-dlp-transcript-common/components/PrivacyProvider"; import AppHeader from "@/components/shell/AppHeader"; import { buttonVariants } from "@/components/ui/button"; import { Dialog } from "@/components/ui/dialog"; @@ -122,6 +123,8 @@ type Ask = | { kind: "remove-quote"; q: Quote }; export default function BoardView({ initial }: { initial: CaseView }) { + // settings.privacy: a `local:` source's directory as displayed (client-side). + const { displayPath } = useDisplay(); const router = useRouter(); const hydrated = useHydrated(); // WHAT IS DRAWN, as ONE state: the case's view, the light, the list's key @@ -502,7 +505,7 @@ export default function BoardView({ initial }: { initial: CaseView }) { }, []); const s = doc.scope; - const where = view.sourceLabel ?? (s.source ? s.source.replace(/^(local|remote|hub):/, "") : "no source yet"); + const where = view.sourceLabel ?? (s.source ? displayPath(s.source.replace(/^(local|remote|hub):/, "")) : "no source yet"); const scopeLine = [where, s.channels?.length ? `${s.channels.length} ${s.channels.length === 1 ? "channel" : "channels"}` : "all channels", s.dateFrom || s.dateTo ? `${s.dateFrom ?? "…"} – ${s.dateTo ?? "…"}` : ""].filter(Boolean).join(" · "); const se = doc.search; const meta = [ diff --git a/umtool/components/system/Maintenance.tsx b/umtool/components/system/Maintenance.tsx @@ -1,3 +1,4 @@ +import { displayPath, displayText } from "yt-dlp-transcript-common/lib/privacy/privacy-server"; import ActionPlan from "@/components/system/ActionPlan"; import { Panel } from "@/components/ui/panel"; import { fmtAgo } from "@/lib/format"; @@ -32,18 +33,18 @@ export function RootsPanel({ roots }: { roots: Roots }) { <Panel title="Roots" aside={<span className="text-muted-2">umtool doctor</span>} data-panel="roots" data-roots-ok={roots.ok ? "yes" : "no"}> <dl className="m-0 grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 text-[12px]"> <Row k="reports" bad={!roots.reports.present}> - {roots.reports.path} + {displayPath(roots.reports.path)} {roots.reports.present ? "" : " — not there"} </Row> <Row k="media" bad={!!roots.media.problem}> - {roots.media.tiered ? roots.media.path : "= reports · UMTOOL_MEDIA_DIR unset"} - {roots.media.problem ? ` — ${roots.media.problem}` : ""} + {roots.media.tiered ? displayPath(roots.media.path) : "= reports · UMTOOL_MEDIA_DIR unset"} + {roots.media.problem ? ` — ${displayText(roots.media.problem)}` : ""} </Row> <Row k="cache"> - {roots.cache.path} + {displayPath(roots.cache.path)} {roots.cache.index ? "" : " — no index yet"} </Row> - {roots.oldCache.present && <Row k="old cache">{roots.oldCache.path} — not read; safe to delete</Row>} + {roots.oldCache.present && <Row k="old cache">{displayPath(roots.oldCache.path)} — not read; safe to delete</Row>} </dl> </Panel> ); @@ -65,7 +66,7 @@ export function IndexPanel({ index }: { index: { ok: boolean; records: number; p ) : ( <p className="m-0 text-[12.5px] text-text-2">No index — every read walks the disk.</p> )} - {index.path && <p className="m-0 mt-1 truncate font-mono text-[11px] text-muted-2">{index.path}</p>} + {index.path && <p className="m-0 mt-1 truncate font-mono text-[11px] text-muted-2">{displayPath(index.path)}</p>} <div className="mt-2.5 flex flex-wrap items-start gap-2"> <ActionPlan label="Rebuild…" subject="index rebuild" endpoint="/api/system/index" body={{ action: "rebuild" }} /> <ActionPlan label="Prune…" subject="index prune" endpoint="/api/system/index" body={{ action: "prune" }} /> @@ -81,7 +82,7 @@ export function StoragePanel({ rows, tiered, mediaRoot }: { rows: StorageRow[]; return ( <Panel title="Storage" - aside={<span className="text-muted-2">umtool storage · {tiered ? `media root ${mediaRoot}` : "no media root (UMTOOL_MEDIA_DIR unset)"}</span>} + aside={<span className="text-muted-2">umtool storage · {tiered ? `media root ${displayPath(mediaRoot)}` : "no media root (UMTOOL_MEDIA_DIR unset)"}</span>} data-panel="storage" className="lg:col-span-2 2xl:col-span-3" > diff --git a/umtool/components/system/ToolsPanel.tsx b/umtool/components/system/ToolsPanel.tsx @@ -1,6 +1,7 @@ "use client"; import { useState } from "react"; +import { useDisplay } from "yt-dlp-transcript-common/components/PrivacyProvider"; import { buttonVariants } from "@/components/ui/button"; import { Panel } from "@/components/ui/panel"; import type { DoctorReport } from "@/lib/tool-types"; @@ -14,6 +15,8 @@ import { fmtAgo } from "@/lib/format"; // Red ONLY when the report pipeline needs a tool and it is absent. A missing // python on a machine that never cuts a face is a fact, not a fault. export default function ToolsPanel({ initial, freeBytes }: { initial: DoctorReport | null; freeBytes: number | null }) { + // settings.privacy: a tool's path (its title) as displayed, client-side. + const { displayText } = useDisplay(); const [report, setReport] = useState<DoctorReport | null>(initial); const [busy, setBusy] = useState(false); @@ -59,11 +62,11 @@ export default function ToolsPanel({ initial, freeBytes }: { initial: DoctorRepo data-tool={t.id} data-present={t.present ? "1" : "0"} data-required={t.required ? "1" : "0"} - title={t.error ?? t.bin} + title={displayText(t.error ?? t.bin)} className={`flex gap-1.5 ${bad ? "text-reject-text" : t.present ? "text-muted" : "text-muted opacity-70"}`} > <span className="font-mono text-text">{t.id}</span> - <span className="num truncate">{t.present ? (t.version ?? "present") : "absent"}</span> + <span className="num truncate">{t.present ? (t.version != null ? displayText(t.version) : "present") : "absent"}</span> </li> ); })} diff --git a/umtool/e2e/privacy-audit.spec.ts b/umtool/e2e/privacy-audit.spec.ts @@ -0,0 +1,253 @@ +import { test, expect, type Browser } from "@playwright/test"; +import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; +import { maskLiterals, type Literal } from "yt-dlp-transcript-common/publish/sourceAudit"; +import { + failingHits, + formatPrivacyReport, + incompleteReasons, + runPrivacyAudit, + type AuditBrowser, + type PrivacyAuditResult, +} from "yt-dlp-transcript-common/publish/privacyAudit"; +import { appRoutes } from "yt-dlp-transcript-common/lib/privacy/routes"; +import { DEFAULT_PRIVACY_SETTINGS } from "yt-dlp-transcript-common/lib/privacySettings"; + +// --------------------------------------------------------------------------- +// THE PRIVACY AUDIT OVER UMTOOL (demo epic D4, slice 1). +// +// Every page route of umtool/app (lib/privacy/routes.ts — derived, not typed), +// drawn with JavaScript off and on, searched for a denylist written at run +// time from FIXTURE values: this machine's home dir (every fixture path holds +// it) and hostname, and the fixture's private site's title. Never printed: the +// report names a literal by its line. +// +// 1. byte identity: settings.privacy absent vs at its defaults — every static +// route's server HTML (volatile ones skipped and counted) and a +// client-rendered seam's drawn text (/jobs' queue panel); +// 2. positive control, privacy OFF: text nodes and an option label (the +// private site in /research's source picker, planted siteUrl). The +// scanner's attribute read is the editor spec's control (a site id in +// /sites' aria-label): no umtool fixture page draws a fixture literal in +// an attribute; +// 3. masked, privacy ON: no hit outside the slice-2 routes listed below; +// 4. the private files' rules reach the server-rendered seams: with the home +// dir only in the fixture source denylist, /settings/system's roots and +// index (server components) lose every hit. That a client-rendered seam +// does NOT get them is the editor spec's test 4 (no umtool fixture page +// draws the home dir from a client component). +// +// WRITES the fixture's settings.json privacy key, the private site's siteUrl +// and the fixture's source rule files (playwright.config.ts points +// SOURCE_SCRUB_FILE / SOURCE_DENYLIST_FILE there); all restored after. +// --------------------------------------------------------------------------- + +test.describe.configure({ mode: "serial" }); +test.setTimeout(900_000); + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const SETTINGS = path.join(FIXTURE, "settings.json"); +const PRIV_SITE = path.join(FIXTURE, "sites", "priv", "site.json"); +const RULES_DIR = path.join(FIXTURE, "privacy"); +const APP_DIR = path.join(HERE, "..", "app"); +const BASE = `http://localhost:${portFor("UMTOOL_E2E_PORT")}`; +const PRIVATE_TITLE = "Private Fixture"; + +// Routes whose leaks are slice 2: the masked test reports their counts and +// does not fail on them. +const SLICE_2 = new Set<string>([]); + +// Dynamic routes no fixture page links to (the audit reports them; the masked +// test names them, so a NEW unreached route fails it). +const UNREACHABLE = [ + "/articles/[report]/compare", + "/articles/[report]/evidence", + "/series/[id]", + "/series/[id]/triage/[k]", + "/sites/[site]/[report]/evidence", +]; +// /projects/at is a static escape hatch that 404s without `?path=` (a project +// whose name has no URL of its own); no fixture project needs it, so no page +// links to it — the audit is GIVEN one (a 404 can never be excused). +const SEEDS = ["/projects/at?path=reports/phone-walk-fixture"]; + +const lit = (text: string, from: string): Literal => ({ bytes: Buffer.from(text, "utf8"), ci: false, from }); +const HOME = os.homedir(); +const literals = (): Literal[] => [ + lit(HOME, "fixture literal 1 (home dir)"), + lit(os.hostname(), "fixture literal 2 (hostname)"), + lit(PRIVATE_TITLE, "fixture literal 3 (private site title)"), +]; + +let settingsBefore = ""; +let privBefore = ""; + +function settings(privacy: Record<string, unknown> | null) { + const s = JSON.parse(settingsBefore) as Record<string, unknown>; + delete s.privacy; + if (privacy) s.privacy = privacy; + writeFileSync(SETTINGS, `${JSON.stringify(s, null, 2)}\n`); +} +// Where two renders first differ, the window around it masked (never a literal). +const firstDiff = (x: string, y: string) => { + let i = 0; + while (i < x.length && x[i] === y[i]) i++; + if (i === x.length && i === y.length) return ""; + const at = (s: string) => JSON.stringify(maskLiterals(s.slice(Math.max(0, i - 80), i + 80), literals())); + return ` — first differs at ${i}: ${at(x)} vs ${at(y)}`; +}; +// The server's privacy memo re-checks the file at most once a second. +const settle = () => new Promise((r) => setTimeout(r, 1300)); + +async function audit(browser: Browser, include?: (route: string) => boolean): Promise<PrivacyAuditResult> { + return runPrivacyAudit({ + targets: [{ app: "umtool", baseUrl: BASE, appDir: APP_DIR }], + literals: literals(), + browser: browser as unknown as AuditBrowser, + maxPerRoute: 1, + seedPaths: SEEDS, + include: include ? (_app, r) => include(r) : undefined, + }); +} + +test.beforeAll(async () => { + settingsBefore = readFileSync(SETTINGS, "utf8"); + privBefore = readFileSync(PRIV_SITE, "utf8"); + // The private site gets a public URL, so /research offers it as a source: + // its title is then an OPTION label (the positive control's option). + writeFileSync(PRIV_SITE, JSON.stringify({ ...JSON.parse(privBefore), siteUrl: "https://zq-private-fixture.example" }, null, 2)); + mkdirSync(RULES_DIR, { recursive: true }); +}); + +test.afterAll(() => { + writeFileSync(SETTINGS, settingsBefore); + writeFileSync(PRIV_SITE, privBefore); + rmSync(RULES_DIR, { recursive: true, force: true }); +}); + +test("byte identity: absent and explicit defaults render the same HTML, and the same /jobs text", async ({ browser }) => { + const statics = appRoutes(APP_DIR).filter((r) => !r.dynamic).map((r) => r.pattern); + const fetchHtml = async (r: string) => { + const res = await fetch(`${BASE}${r}`, { redirect: "manual" }); + return `${res.status}\n${await res.text()}`; + }; + const jobsText = async () => { + const ctx = await browser.newContext(); + const page = await ctx.newPage(); + await page.goto(`${BASE}/jobs`); + await expect(page.locator("[data-queue]")).toBeVisible(); + const text = await page.locator("[data-queue]").innerText(); + await ctx.close(); + return text; + }; + // Per route, absent and explicit defaults read in turn, each a moment after + // its switch. The server streams its Suspense boundaries in whatever order + // they finish, so one read is one of a few byte strings: a route passes when + // a defaults read is byte-identical to an absent read (up to four rounds). + // One whose absent reads never repeat and never meet is volatile, skipped + // and counted; a STABLE absent read that no defaults read matches fails. + let compared = 0; + const volatile: string[] = []; + for (const r of statics) { + const absent = new Set<string>(); + const given = new Set<string>(); + let same = false; + for (let round = 0; round < 4 && !same; round++) { + settings(null); + await settle(); + absent.add(await fetchHtml(r)); + settings({ ...DEFAULT_PRIVACY_SETTINGS }); + await settle(); + given.add(await fetchHtml(r)); + same = [...given].some((g) => absent.has(g)); + } + if (same) { + compared++; + continue; + } + if (absent.size > 1) { + volatile.push(r); + continue; + } + const [a] = absent; + const [b] = given; + expect(same, `${r}: explicit defaults render the HTML the absent block does${firstDiff(a, b)}`).toBe(true); + } + // A client-rendered seam's drawn text (no clock in it): absent vs defaults. + settings(null); + await settle(); + const aText = await jobsText(); + settings({ ...DEFAULT_PRIVACY_SETTINGS }); + await settle(); + const bText = await jobsText(); + settings(null); + await settle(); + test.info().annotations.push({ type: "byte-identity", description: `${compared} of ${statics.length} static routes compared; volatile, skipped: ${volatile.join(" ") || "none"}` }); + expect(compared).toBeGreaterThan(statics.length / 2); + expect(bText).toBe(aText); +}); + +test("positive control, privacy off: text and an option label are seen", async ({ browser }) => { + settings(null); + await settle(); + const result = await audit(browser); + const hits = failingHits(result); + const report = formatPrivacyReport(result, literals()).join("\n"); + for (const l of literals()) expect(report.includes(l.bytes.toString("utf8")), "the report never carries a literal").toBe(false); + test.info().annotations.push({ type: "positive", description: report.split("\n").slice(0, 12).join(" | ") }); + const kinds = new Set(hits.map((h) => h.where)); + expect(kinds.has("text")).toBe(true); + expect(kinds.has("option"), "the private site in /research's source picker").toBe(true); + expect(hits.some((h) => h.route === "/settings/system" && h.lit === 0 && h.where === "text"), "the roots name the home dir").toBe(true); + expect(hits.some((h) => h.pass === "ssr"), "the JavaScript-off pass reads the server's HTML").toBe(true); +}); + +test("masked, privacy on: no hit outside the slice-2 routes", async ({ browser }) => { + settings({ displayPaths: "masked", hideHost: true, hidePrivateSites: true, maskEmail: true, aliases: [`${PRIVATE_TITLE}==>A private site`], useSourceRules: false }); + await settle(); + const result = await audit(browser); + const hits = failingHits(result); + const byRoute = new Map<string, { live: number; ssr: number }>(); + for (const h of hits) { + const c = byRoute.get(h.route) ?? { live: 0, ssr: 0 }; + c[h.pass]++; + byRoute.set(h.route, c); + } + test.info().annotations.push({ + type: "masked per route (live/ssr)", + description: [...byRoute].map(([r, c]) => `${r} ${c.live}/${c.ssr}`).join("; ") || "none", + }); + test.info().annotations.push({ + type: "masked coverage", + description: `${result.pages.length} pages; not reached: ${result.notReached.map((r) => r.route).join(" ") || "none"}`, + }); + expect(hits.filter((h) => !SLICE_2.has(h.route)).map((h) => `${h.route} ${h.pass} ${h.where} ${h.selector} lit${h.lit + 1}`)).toEqual([]); + // Complete (review round 1, M4): every page loaded, every route reached but + // the ones named here, which no fixture page links to. + const bad = result.pages.filter((p) => p.error || (p.status !== null && p.status >= 400)).map((p) => `${p.route} ${p.status ?? p.error}`); + expect(incompleteReasons({ ...result, allowUnreached: UNREACHABLE }), `pages: ${bad.join("; ")}`).toEqual([]); +}); + +test("the private files' rules reach the server-rendered seams: /settings/system's roots lose every hit", async ({ browser }) => { + writeFileSync(path.join(RULES_DIR, "source-scrub.txt"), "# none\n"); + writeFileSync(path.join(RULES_DIR, "source-denylist.txt"), `${HOME}\n`); + const only = (r: string) => r === "/settings/system"; + settings(null); + await settle(); + const off = failingHits(await audit(browser, only)); + settings({ ...DEFAULT_PRIVACY_SETTINGS, useSourceRules: true }); + await settle(); + const on = failingHits(await audit(browser, only)); + const n = (hs: typeof on, pass: string) => hs.filter((h) => h.lit === 0 && h.pass === pass).length; + test.info().annotations.push({ + type: "server seams (home-dir hits on /settings/system)", + description: `live ${n(off, "live")} → ${n(on, "live")}; ssr ${n(off, "ssr")} → ${n(on, "ssr")}`, + }); + expect(n(off, "live")).toBeGreaterThan(0); + expect(n(on, "live")).toBe(0); + expect(n(on, "ssr")).toBe(0); +}); diff --git a/umtool/lib/inbox.ts b/umtool/lib/inbox.ts @@ -29,6 +29,7 @@ import { refreshDecisions } from "./inbox/refresh"; import { sourceWatchDecisions } from "./inbox/sourceWatch"; import { projectCallsAll } from "./inbox/projectCalls"; import { caseCuesDecisions } from "./inbox/caseCues"; +import { decisionIsPrivate, type PrivateFilter } from "./privacy"; // --------------------------------------------------------------------------- // THE INBOX, AS DATA: every open decision (lib/projects.ts openDecisions: the @@ -417,7 +418,7 @@ export async function diskDecisions(graph: PieceGraph, life: LifecycleRead): Pro * The inbox. `project` narrows to one song's reducer (the decisions route's * `?project=`), annotated the same way, with no disk sources added. */ -export async function readInbox({ project }: { project?: string | null } = {}): Promise<Inbox> { +export async function readInbox({ project, hide = null }: { project?: string | null; hide?: PrivateFilter | null } = {}): Promise<Inbox> { const [base, graph, life, mutes] = await Promise.all([ project ? decisionsForSong(project) : openDecisions(), readPieceGraph(), @@ -426,8 +427,12 @@ export async function readInbox({ project }: { project?: string | null } = {}): ]); // A disk source that cannot be read adds nothing; it never hides the rest. const extra = project ? [] : await diskDecisions(graph, life).catch(() => [] as Decision[]); + // settings.privacy.hidePrivateSites (lib/privacy.ts): a page that passes the + // filter leaves the private sites' decisions out; null leaves every one in. + const all = [...base, ...extra]; + const kept = hide ? all.filter((d) => !decisionIsPrivate(d, graph, hide)) : all; const items = rankDecisions( - annotate([...base, ...extra], { + annotate(kept, { pieceOf: (d: Decision) => pieceOfDecision(d, graph), lifecycleOf: (id: string) => lifecycleOf(life, id), isMuted: (piece: string, kind: string) => isMuted(mutes, piece, kind), diff --git a/umtool/lib/privacy.test.ts b/umtool/lib/privacy.test.ts @@ -0,0 +1,71 @@ +// settings.privacy.hidePrivateSites in umtool (lib/privacy.ts): which pieces, +// projects and decisions home, /projects and /work leave out — over a temp +// sites dir and a temp settings file, never the real ones. +// +// Run with: pnpm --filter umtool test (or ../node_modules/.bin/tsx --test lib/privacy.test.ts) + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +const DIR = mkdtempSync(path.join(tmpdir(), "umtool-privacy-")); +const SITES = path.join(DIR, "sites"); +const SETTINGS = path.join(DIR, "settings.json"); +for (const [id, extra] of [ + ["pub", {}], + ["sec", { audience: "private" }], +] as const) { + mkdirSync(path.join(SITES, id), { recursive: true }); + writeFileSync(path.join(SITES, id, "site.json"), JSON.stringify({ siteId: id, siteTitle: id, ...extra })); +} +Object.assign(process.env, { SITES_DIR: SITES, SETTINGS_FILE: SETTINGS }); + +const { privateFilter, decisionIsPrivate } = await import("./privacy"); +const { resetPrivacyMemo } = await import("yt-dlp-transcript-common/lib/privacy/privacy-server"); +type Graph = NonNullable<Parameters<typeof privateFilter>[0]>; + +const piece = (id: string, site: string | null) => ({ id, site }) as unknown as Graph["pieces"][number]; +const GRAPH = { + pieces: [piece("a:pub/one", "pub"), piece("a:sec/two", "sec"), piece("p:loose", null)], + byId: new Map(), + pieceOfProject: new Map([ + ["videos/for-pub", "a:pub/one"], + ["videos/for-sec", "a:sec/two"], + ["loose", "p:loose"], + ]), + projectByName: new Map(), +} as unknown as Graph; + +const settings = (privacy: unknown) => { + writeFileSync(SETTINGS, JSON.stringify({ privacy })); + resetPrivacyMemo(); +}; + +test("off: null, so every list is as it was", async () => { + settings({ hidePrivateSites: false, displayPaths: "home" }); + assert.equal(await privateFilter(GRAPH), null); +}); + +test("on: a private site's articles and the projects they own; a decision about either", async () => { + settings({ hidePrivateSites: true }); + const hide = await privateFilter(GRAPH); + assert.ok(hide); + assert.deepEqual([...hide.sites], ["sec"]); + assert.deepEqual([...hide.pieces], ["a:sec/two"]); + assert.deepEqual([...hide.projects], ["videos/for-sec"]); + const d = (x: object) => ({ kind: "k", project: "", ...x }) as unknown as Parameters<typeof decisionIsPrivate>[0]; + assert.equal(decisionIsPrivate(d({ piece: "a:sec/two" }), GRAPH, hide), true); + assert.equal(decisionIsPrivate(d({ project: "videos/for-sec" }), GRAPH, hide), true); + assert.equal(decisionIsPrivate(d({ piece: "a:pub/one" }), GRAPH, hide), false); + assert.equal(decisionIsPrivate(d({ project: "loose" }), GRAPH, hide), false); +}); + +test("on, with no private site: null", async () => { + rmSync(path.join(SITES, "sec"), { recursive: true, force: true }); + settings({ hidePrivateSites: true }); + assert.equal(await privateFilter(GRAPH), null); +}); + +test.after(() => rmSync(DIR, { recursive: true, force: true })); diff --git a/umtool/lib/privacy.ts b/umtool/lib/privacy.ts @@ -0,0 +1,53 @@ +// settings.privacy.hidePrivateSites in umtool (demo epic D4): which pieces and +// projects home, /projects and /work leave out. The one notion of "private" +// is a site's own (site.json `audience: "private"`, isPrivateSite); a piece is +// private when it is an article of a private site, and a project when the +// piece it belongs to (the piece graph's pieceOfProject) is. An article's own +// `audience` is a different thing and hides nothing. +// +// A LIST FILTER, not access control: a private site's pages still open by URL. +// Null while the setting is off or no site is private — every caller then +// does exactly what it did before. +// +// SERVER ONLY. + +import { hidePrivateSites } from "yt-dlp-transcript-common/lib/privacy/privacy-server"; +import { isPrivateSite, listSites } from "yt-dlp-transcript-common/lib/site"; +import { sitesPaths } from "./articles/sites"; +import { ARTICLES_KEY } from "./articles/key.mjs"; +import { pieceOfDecision, readPieceGraph, type PieceGraph } from "./pieces"; +import type { Decision } from "./decisions"; + +export type PrivateFilter = { + sites: Set<string>; + pieces: Set<string>; + projects: Set<string>; +}; + +/** The private sites' pieces and projects, or null when nothing is hidden. */ +export async function privateFilter(graph?: PieceGraph): Promise<PrivateFilter | null> { + if (!hidePrivateSites()) return null; + let sites: Set<string> | null; + try { + sites = new Set(listSites(sitesPaths()).filter(isPrivateSite).map((s) => s.siteId)); + } catch { + // FAIL CLOSED (review round 1, S3): the sites cannot be read, so which + // are private is unknown — every site's pieces are hidden. Home, /projects + // and /work then show the article store's pieces and the projects no site + // article claims. + sites = null; + } + if (sites && !sites.size) return null; + const g = graph ?? (await readPieceGraph()); + if (!sites) sites = new Set(g.pieces.flatMap((p) => (p.site !== null && p.site !== ARTICLES_KEY ? [p.site] : []))); + const pieces = new Set(g.pieces.filter((p) => p.site !== null && sites.has(p.site)).map((p) => p.id)); + const projects = new Set([...g.pieceOfProject].filter(([, piece]) => pieces.has(piece)).map(([project]) => project)); + return { sites, pieces, projects }; +} + +/** Is this decision about a hidden piece or project? */ +export function decisionIsPrivate(d: Decision, graph: PieceGraph, hide: PrivateFilter): boolean { + if (hide.projects.has(d.project)) return true; + const piece = pieceOfDecision(d, graph); + return piece !== null && hide.pieces.has(piece); +} diff --git a/umtool/lib/research/privacySources.test.ts b/umtool/lib/research/privacySources.test.ts @@ -0,0 +1,58 @@ +// settings.privacy.hidePrivateSites and the research sources (review round 1, +// M2): the flag filters what a PICKER draws (shownSources) and nothing else. +// listSources() is also openSource's allow-list and every reader's default +// (corpus, boards, case-verify, coverage, fetch, runs-board, triage), so with +// the flag ON it must still name a private site's archive — a case on that +// source keeps reading it. Temp dirs only; nothing is fetched. +// +// Run with: pnpm --filter umtool test + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +const D = mkdtempSync(path.join(tmpdir(), "umtool-privacy-sources-")); +const SITES = path.join(D, "sites"); +const SETTINGS = path.join(D, "settings.json"); +for (const [id, extra] of [ + ["priv", { audience: "private", siteUrl: "https://priv.invalid" }], + ["pub", { siteUrl: "https://pub.invalid" }], +] as const) { + mkdirSync(path.join(SITES, id), { recursive: true }); + writeFileSync(path.join(SITES, id, "site.json"), JSON.stringify({ siteId: id, siteTitle: `T-${id}`, ...extra })); +} +mkdirSync(path.join(D, "export"), { recursive: true }); +Object.assign(process.env, { SITES_DIR: SITES, SETTINGS_FILE: SETTINGS, TRANSCRIPT_LOCAL_DIR: path.join(D, "export"), TRANSCRIPT_HUB_URL: "" }); + +const srv = await import("yt-dlp-transcript-common/lib/privacy/privacy-server"); +const { listSources, shownSources } = await import("./sources"); + +let t = 0; +const set = (privacy: unknown) => { + writeFileSync(SETTINGS, JSON.stringify({ privacy })); + t += 10; + const d = new Date(Date.UTC(2026, 0, 1) + t * 1000); + utimesSync(SETTINGS, d, d); + srv.resetPrivacyMemo(); +}; +const handles = (l: { handle: string }[]) => l.map((s) => s.handle).filter((h) => h.startsWith("remote:")).sort(); + +test("flag ON: listSources (the allow-list, the default) still has the private site; only the picker's list drops it", async () => { + set({ hidePrivateSites: false }); + const off = await listSources(); + assert.deepEqual(handles(off), ["remote:https://priv.invalid", "remote:https://pub.invalid"]); + assert.equal(await shownSources(off), off, "off: the very same list"); + + set({ hidePrivateSites: true }); + const on = await listSources(); + assert.deepEqual(handles(on), handles(off), "every non-UI caller sees the full list"); + assert.deepEqual(handles(await shownSources(on)), ["remote:https://pub.invalid"]); + // The chosen source stays drawn, without its name. + const kept = (await shownSources(on, "remote:https://priv.invalid")).find((s) => s.handle === "remote:https://priv.invalid"); + assert.equal(kept?.label, "A private site"); + assert.equal(kept?.detail, ""); +}); + +test.after(() => rmSync(D, { recursive: true, force: true })); diff --git a/umtool/lib/research/sources.ts b/umtool/lib/research/sources.ts @@ -6,6 +6,7 @@ import { fetchOnOrigin, readBounded, type FetchLike } from "yt-dlp-transcript-co import { REPO_ROOT, REPORTS_ROOT, SITES_DIR } from "../paths.mjs"; import { readCensus } from "./census.mjs"; import type { SourceOption } from "./types"; +import { hidePrivateSites } from "yt-dlp-transcript-common/lib/privacy/privacy-server"; // --------------------------------------------------------------------------- // THE SOURCE PICKER (plans/umtool-redesign.md, "Research, first-class" 1): @@ -56,6 +57,32 @@ async function readJson<T>(file: string): Promise<T | null> { } /** Every corpus the ask bar may read, the default first: the local one, unless it has no build and an archive is offered. */ +/** + * The sources a PICKER draws (settings.privacy.hidePrivateSites): `list` + * without a private site's published archive (isPrivateSite's rule, + * `audience: "private"`). The one the page has chosen (`keep`) stays, as + * "A private site", so the picker shows what is in use. Only a page that DRAWS + * the list calls this — listSources() itself stays the full list, because it + * is also openSource's allow-list and every reader's default: a case on a + * private site's source must keep reading that source. + */ +export async function shownSources(list: SourceOption[], keep?: string | null): Promise<SourceOption[]> { + if (!hidePrivateSites()) return list; + const ids = await readdir(/* turbopackIgnore: true */ SITES_DIR).catch(() => [] as string[]); + const hidden = new Set<string>(); + for (const id of ids) { + if (id.startsWith("_") || id.startsWith(".")) continue; + const site = await readJson<{ siteUrl?: unknown; audience?: unknown }>(path.join(/* turbopackIgnore: true */ SITES_DIR, id, "site.json")); + if (site?.audience !== "private") continue; + const url = typeof site.siteUrl === "string" ? site.siteUrl.trim().replace(/\/+$/, "") : ""; + if (url) hidden.add(`remote:${url}`); + } + if (!hidden.size) return list; + return list.flatMap((s) => + !hidden.has(s.handle) ? [s] : s.handle === keep ? [{ ...s, label: "A private site", detail: "" }] : [], + ); +} + export async function listSources(): Promise<SourceOption[]> { const dir = localDir(); const corpus = await readJson<{ site?: { title?: string } }>(path.join(/* turbopackIgnore: true */ dir, "corpus.json")); diff --git a/umtool/package.json b/umtool/package.json @@ -8,7 +8,7 @@ "build": "next build", "start": "next start --port ${UMTOOL_PORT:-3050}", "typecheck": "tsc --noEmit", - "test": "tsx --test lib/brandIcon.test.ts lib/articles/*.test.ts lib/research/*.test.ts lib/inbox/*.test.ts lib/clips/*.test.ts components/projects/bench/*.test.ts", + "test": "tsx --test lib/brandIcon.test.ts lib/privacy.test.ts lib/articles/*.test.ts lib/research/*.test.ts lib/inbox/*.test.ts lib/clips/*.test.ts components/projects/bench/*.test.ts", "e2e": "node ../scripts/worktree.mjs run -- node ../scripts/queue-lock.mjs --name e2e-umtool --estimate 1500 --prebuild umtool --ports UMTOOL_E2E_PORT:3051,EDITOR_STUB_PORT:3052 -- playwright test" }, "dependencies": { diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts @@ -208,6 +208,10 @@ export default defineConfig({ // archive from the shell's TRANSCRIPT_SITE_URL; the archive cache the // fixture's own (common/lib/archiveCache-server.ts). `SETTINGS_FILE=${FIXTURE}/settings.json TRANSCRIPT_SITE_URL= ARCHIVE_CACHE_DIR=${FIXTURE}/archive-cache ` + + // settings.privacy's opt-in rule files (demo epic D4, useSourceRules): + // the fixture's own, which privacy-audit.spec writes. Their default is + // the operator's ~/.config/archilyzer, which a suite must never read. + `SOURCE_SCRUB_FILE=${FIXTURE}/privacy/source-scrub.txt SOURCE_DENYLIST_FILE=${FIXTURE}/privacy/source-denylist.txt ` + // The generation usage ledger (release 27): the fixture's, never the // checkout's .generation/usage.jsonl. `GENERATION_USAGE_FILE=${FIXTURE}/generation-usage.jsonl ` +