// 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/ 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 = { "/": { 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): 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 }));