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([]); // 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 | null) { const s = JSON.parse(settingsBefore) as Record; 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 { 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(); const given = new Set(); 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(); 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); });