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 ). 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([ "/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", ]); // Routes whose cookiesFromBrowser INPUT draws the saved spec as typed. const VALUE_ROUTES = new Set(["/settings", "/cookies"]); 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 | null) { const s = JSON.parse(readFileSync(paths.settingsFile, "utf8")) as Record; delete s.privacy; if (privacy) s.privacy = privacy; // A browser spec that names a profile PATH under the home dir (the path does // not exist: nothing reads a browser store). X's login source draws it on // /settings and /cookies — through the privacy rules, never raw — while the // yt-dlp field that edits it shows the saved value as it is (VALUE_ROUTES). s.cookiesFromBrowser = `firefox:${join(HOME, ".zq-audit-firefox", "zq.default")}`; 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; 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 { 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) => ({ 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); // An ISO timestamp is the clock, not the privacy setting: a page that says // when it read (/cookies' readAt) is compared with its times blanked. const ISO = /\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?Z/g; const fetchHtml = async (r: string) => { const res = await fetch(`${baseUrl}${r}`, { redirect: "manual" }); return `${res.status}\n${(await res.text()).replace(ISO, "