Archilyzer · Source

archilyzer

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

commit b5be847c7caaaa4c858ab4848245cbcb6da6d830
parent 5ef7c7b8abf24ab00390d26be2dabdbde99a307e
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 13 Nov 2026 02:21:57 -0500

privacy D4: the privacy-audit e2e specs, and the CHANGELOG

editor/e2e/privacy-audit.spec.ts and umtool/e2e/privacy-audit.spec.ts run the
audit over each app's fixture with a denylist written at run time from
fixture values (the home dir, the hostname, a location root, a private site's
id and title), never printed: byte identity of absent vs explicit-default
privacy (server HTML per static route, and a client seam's drawn text); a
positive control (text, an attribute, an option label, both passes); the
masked run, which must also be COMPLETE (named unreached routes; umtool seeds
/projects/at); the private files' rules reaching server-rendered seams only;
and (editor) a hidden membership surviving a save. Both suites' servers point
SOURCE_SCRUB_FILE / SOURCE_DENYLIST_FILE at fixture files, never the
operator's.

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

Diffstat:
Meditor/CHANGELOG.md | 12++++++++++++
Aeditor/e2e/privacy-audit.spec.ts | 327+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/e2e/servers.ts | 5+++++
Aumtool/e2e/privacy-audit.spec.ts | 253+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/playwright.config.ts | 4++++
5 files changed, 601 insertions(+), 0 deletions(-)

diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,18 @@ # Changelog ## [Unreleased] +- **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/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/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/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 ` +