Archilyzer · Source

archilyzer

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

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

privacy D4: the privacy audit and `archilyzer privacy audit`

lib/privacy/routes.ts reads every page route off an app/ dir.
publish/privacyAudit.ts loads each in a fresh browser context twice
(JavaScript off and on), following links to give dynamic routes concrete URLs
and --url seeds for a route no page links to; it searches text nodes, each
element's drawn joined text, innerText, open shadow roots, same-origin
frames, title / aria-label / aria-description / alt / placeholder, field
values, option labels, the title and the URL, for every denied literal in its
plain, percent-encoded and JSON-escaped forms (hrefs warn only). The browser
only collects; the search runs in node. The report names a literal by line
and length and a hit by app, route, pass, kind and a structural selector,
every output masked. It is INCOMPLETE (exit 3) when a page did not load or
answered >= 400 (a static route that 404s without its query included,
whatever --allow-unreached says), a route was not reached and not excused, or
no page was audited; exit 1 on a hit, 2 on usage. COMMANDS.md regenerated.

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

Diffstat:
MCOMMANDS.md | 1+
Mcommon/bin/archilyzer.ts | 33+++++++++++++++++++++++++++++++++
Acommon/bin/privacy-audit.ts | 129+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/privacy/routes.ts | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/publish/privacyAudit.test.ts | 319+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/publish/privacyAudit.ts | 524+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6 files changed, 1077 insertions(+), 0 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/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/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/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", + })), + }; +}