commit 0b83181af876e10669d1244bb13d31c6ec1e2bc3 parent 1e00b6b1fb219c484078199326cf8818101e8262 Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Sat, 14 Nov 2026 10:01:00 -0500 Merge lane/flaky-tests (no network): a test run reaches this machine and nothing else -- ARCHILYZER_NO_NETWORK=1, set by every test command, refuses every connection that is not loopback, every download tool given a URL and every browser sent to another host, in the process, its children and its workers, and says so loudly if it is ever set outside a test; a render reaches nothing either: the HyperFrames renderer runs with outward connections refused and its telemetry off, the package from the local cache, a first download the one logged exception; Next's telemetry is off wherever a build or a dev server starts, and the browsers umtool starts keep quiet; a second signal no longer cuts a hold's release short, a queue step whose end cannot be written ends failed, and a path with brackets no longer runs no tests and passes Co-Authored-By: Claude <noreply@anthropic.com> Diffstat:
61 files changed, 1820 insertions(+), 141 deletions(-)
diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -189,6 +189,10 @@ The publish pipeline sets these for a process it spawns. Listed so a reader know | `GGML_BACKEND_PATH` | settings.tts.orpheus.ggmlBackendPath | The ggml backend llama-server loads (Vulkan by default), set for the Orpheus server the editor starts — from `settings.tts.orpheus.ggmlBackendPath`, never the environment. | common/lib/ttsApps.ts | | `HOMEPAGE_DIST_DIR` | unset (`homepage/out`) | Where the homepage's `next build` writes its export; `archilyzer build homepage --private` sets it to `out-private`, so the private build never replaces the deployable `homepage/out`. | homepage/next.config.ts, common/publish/build.ts | | `HOMEPAGE_PUBLIC_DIR` | `<repo>/homepage/public` | Where `compose homepage` and `source publish` write. | common/bin/compose-homepage.ts, common/publish/source.ts | +| `ARCHILYZER_NO_NETWORK` | unset (no effect) | `1`: nothing in the process reaches a host that is not loopback. A connection (every fetch, http(s) request, WebSocket and UDP datagram) to another host fails with an `ENONETWORK` error naming the door. Spawning yt-dlp, gallery-dl, ffmpeg, curl or wget with such a URL is refused. A browser gets a proxy that does not answer, and Firefox is refused. The Odysee player-page opener refuses by name. Every test script sets it (each package's `test`, `pnpm test:scripts`, `pnpm test:files`) and preloads the guard into every node process the run starts, through `NODE_OPTIONS=--import=…/common/lib/noNetwork.mjs`. A test file run by hand must do the same. | common/lib/noNetwork.mjs (installed by the test harness's `--import`, and by lib/paths.ts, ytdlp/runYtdlp.ts, social/playwrightRuntime.ts on import), common/ytdlp/storedUrlPageOpen.ts, common/controller/seeder.ts, scripts/test-files.mjs | +| `ARCHILYZER_NO_NETWORK_LOG` | unset (no log) | A file. Under `ARCHILYZER_NO_NETWORK`, each refused door adds one JSON line to it: the door, the target and the process's argv. It finds the tests that reach for the network even when their code swallows the failure. | common/lib/noNetwork.mjs | +| `DO_NOT_TRACK` | unset | The common opt-out of CLI telemetry. Set to `1` for the run's children when `ARCHILYZER_NO_NETWORK` is on, unless already set. | common/lib/noNetwork.mjs | +| `HYPERFRAMES_NO_TELEMETRY` | unset (HyperFrames sends usage telemetry) | `1`: the HyperFrames CLI sends no telemetry. Set to `1` for the run's children when `ARCHILYZER_NO_NETWORK` is on, unless already set. Outside test runs, nothing sets it. | common/lib/noNetwork.mjs (for the HyperFrames CLI umtool renders through) | ## Docker diff --git a/OPERATING.md b/OPERATING.md @@ -1262,6 +1262,37 @@ pnpm ops compaction-markers --json '{"clear":{"slug":"example","id":"<videoId>"} pointer before it removes the file; an interrupted one is listed (`leftover`) and finished by asking again. - **Not automatic.** There is no lane: compaction runs only when it is asked. +## What renders and builds send out: nothing + +Nothing about the operator's work goes to an outside service from a render or a build: + +- **HyperFrames** (every deck, intro and chrome render) **runs with outward connections refused**. Its process, + npx and everything they start have `common/lib/noNetwork.mjs` preloaded (`ARCHILYZER_NO_NETWORK=1`), so they + reach loopback only. + - **What gets blocked:** at start the CLI checks the npm registry for a newer version and + raw.githubusercontent.com for its skills. Unguarded, that is once a day, fire-and-forget. Those requests are refused, and the + render goes on. + - **Browser:** it gets a proxy that does not answer, so local pages still load. + - **Evidence:** refused requests are listed in `<project>/.renderer-refused.jsonl`, and the build's log says + `note — N outward requests from the renderer refused: <hosts>`. + - **Opt-outs, set as well:** `DO_NOT_TRACK`, `HYPERFRAMES_NO_TELEMETRY`, `HYPERFRAMES_NO_UPDATE_CHECK` (which + only silences the notice) and `HYPERFRAMES_NO_AUTO_INSTALL`. +- **First-run downloads are the one logged exception.** The pinned package runs from the npm cache + (`npx --offline`). When it is not there yet, or HyperFrames' browser has not been downloaded, that one step + runs with connections allowed. A line first names what is fetched and from where: the npm registry, or Chrome + for Testing on storage.googleapis.com. Then the render runs guarded again. +- **Chromium**: the review still and the analysis page's measure start their own headless Chromium. They run with + no background networking, component updates, pings, metrics upload, sync or crash reports. Playwright's + launches already set these. +- **Next.js telemetry** is off (`NEXT_TELEMETRY_DISABLED=1`) for every app's `dev`, `build` and `start` script, + the publish stages' builds, the e2e builds and the service units. + +**HyperFrames run by hand on the host is not guarded.** There, `hyperframes telemetry disable` turns off its +TELEMETRY only: a by-hand run still makes the daily update and skills checks. The CLI keeps its settings in +`~/.hyperframes/config.json` (found through `$HOME`; it has no variable of its own for that directory). A product +render reads it, and does not write it for its checks: the CLI records a check's time only after a check that +answered, so under the guard the check is tried, and refused, on every render. Hence the note each time. + ## Publish ```sh diff --git a/common/controller/mirrorScan.test.ts b/common/controller/mirrorScan.test.ts @@ -32,7 +32,14 @@ const PINNED: Record<string, string> = { }; Object.assign(process.env, PINNED); delete process.env.ARCHILYZER_INDEX_ALLOW_HELD; -after(() => rmSync(ROOT, { recursive: true, force: true })); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs } = await import("../testing/jobs/quiesce"); +after(async () => { + await quiesceJobs(); + rmSync(ROOT, { recursive: true, force: true }); +}); const { getPaths } = await import("../lib/paths"); const { buildIndex } = await import("./buildIndex"); diff --git a/common/controller/seeder.test.ts b/common/controller/seeder.test.ts @@ -9,7 +9,7 @@ import WebTorrent from "webtorrent"; import type { Paths } from "../lib/paths"; import { DEFAULT_SEEDER_SETTINGS } from "../lib/seederSettings"; import { interfacePresent, mergeScrapes, runSeeder, scrapeTracker, startTracker } from "./seeder"; -import { destroyClient as destroy, newClient, SEED_ID as ID, seederFixture as fixture, seederSettings as settings, until } from "../testing/seeder/fixture"; +import { childExecArgv, destroyClient as destroy, newClient, SEED_ID as ID, seederFixture as fixture, seederSettings as settings, until } from "../testing/seeder/fixture"; // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/seeder.test.ts // @@ -39,6 +39,14 @@ test("unit: scrape answers merge by max, and an absent interface is absent", () assert.equal(interfacePresent("wg0", { wg0: [{ address: "10.2.0.2", internal: false } as never] }), true); }); +test("unit: a child is started without the test runner's flags, values written with a space included", () => { + const loader = ["--require", "/x/preflight.cjs", "--import", "file:///x/loader.mjs"]; + assert.deepEqual(childExecArgv([...loader, "--test-name-pattern=WebRTC"]), loader); + assert.deepEqual(childExecArgv([...loader, "--test-name-pattern", "WebRTC", "--test-reporter", "tap"]), loader); + assert.deepEqual(childExecArgv(["--test", ...loader, "--test-only", "--experimental-test-coverage"]), loader); + assert.deepEqual(childExecArgv([...loader, "--test-timeout", "5000", "--max-old-space-size=3072"]), [...loader, "--max-old-space-size=3072"]); +}); + test("unconfigured, it refuses to start", async () => { await assert.rejects( runSeeder({ paths: {} as Paths, settings: DEFAULT_SEEDER_SETTINGS, onLog: () => {} }), @@ -173,7 +181,7 @@ test("WebRTC: a peer reaching it through the WebSocket tracker completes (node-d return; } // The same loader this file runs under (tsx), without the test runner's flags. - const execArgv = process.execArgv.filter((a) => !a.startsWith("--test")); + const execArgv = childExecArgv(); const child = spawn(process.execPath, [...execArgv, SCENARIO], { stdio: ["ignore", "pipe", "pipe"] }); const lines: string[] = []; let buf = ""; diff --git a/common/controller/seeder.ts b/common/controller/seeder.ts @@ -34,6 +34,7 @@ import WebTorrent, { type Torrent } from "webtorrent"; import { Client as TrackerClient, Server as TrackerServer, type ScrapeData } from "bittorrent-tracker"; import parseTorrent from "parse-torrent"; import type { Paths } from "../lib/paths"; +import { noNetwork } from "../lib/noNetwork.mjs"; import { getSite, siteChannelSlugs } from "../lib/site"; import { readChannelConfig } from "./channels"; import { defaultPlayableRoot, loadPlayableManifest } from "./preparePlayable"; @@ -239,6 +240,9 @@ export async function runSeeder(opts: RunSeederOptions): Promise<void> { natPmp: false, utp: false, webSeeds: false, + // The STUN servers WebRTC would ask are native code's sockets, past the + // process guard: under ARCHILYZER_NO_NETWORK none are named. + ...(noNetwork() ? { tracker: { rtcConfig: { iceServers: [] } } } : {}), }); onLog(`seeder: WebRTC ${WebTorrent.WEBRTC_SUPPORT ? "available" : "NOT available (TCP peers only)"}; sites ${settings.sites.join(", ")}`); diff --git a/common/controller/waybackScan.test.ts b/common/controller/waybackScan.test.ts @@ -25,7 +25,12 @@ const { isNewRow } = await import("../lib/waybackPages/scanFile"); const { getRegistry } = await import("../jobs/registry"); const wb = await startFakeWayback({ captures: SCAN_CAPTURES }); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs } = await import("../testing/jobs/quiesce"); after(async () => { + await quiesceJobs(); await wb.close(); await rm(ROOT, { recursive: true, force: true }); }); diff --git a/common/jobs/resumeInterrupted.test.ts b/common/jobs/resumeInterrupted.test.ts @@ -9,6 +9,7 @@ import type { JobSpec } from "./jobSpec"; import { INTERRUPTED_REASON, settleRunningJobMetas, type RequeueFn } from "./bootQueuedJobs"; import { getRegistry } from "./registry"; import { runManagedFunction } from "./streamCommand"; +import { settleJob } from "../testing/jobs/quiesce"; import { MAX_RESUMES_IN_A_ROW, RESUME_WINDOW_MS, @@ -108,17 +109,13 @@ test("the resumed job carries the chain, and its log opens with what it resumes" assert.equal(record?.resumeCount, 1); const log = await fx.log(newId); assert.match(log.split("\n")[0], /^\[resume\] Resumes refresh-report job R1 on h3, interrupted when the process running it stopped: the channel's report is regenerated\.$/); - // On disk too, for the next boot. - for (let i = 0; i < 50; i++) { - const m = await fx.read(newId).catch(() => null); - if (m?.status === "done") { - assert.equal(m.resumedFrom, "R1"); - assert.equal(m.resumeCount, 1); - return; - } - await new Promise((r) => setTimeout(r, 20)); - } - assert.fail("the resumed job's meta never reached done"); + // On disk too, for the next boot. (`done` settles before the last sidecar + // write lands: waited for by the sidecar, not by 50 polls of 20 ms.) + await settleJob(newId, { paths: fx.paths }); + const m = await fx.read(newId); + assert.equal(m?.status, "done"); + assert.equal(m?.resumedFrom, "R1"); + assert.equal(m?.resumeCount, 1); } finally { await rm(fx.root, { recursive: true, force: true }); } diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -221,6 +221,10 @@ const DECLARED: EnvVarDecl[] = [ { name: "ARCHILYZER_OLLAMA_TAG", audience: "docker", default: "`0.40.5`", readBy: "docker-compose.yml", doc: "The `ollama/ollama` image tag the `ollama` profile runs." }, // ── test: harnesses, fakes and test-mode branches ────────────────────── + { name: "ARCHILYZER_NO_NETWORK", audience: "internal", default: "unset (no effect)", readBy: "common/lib/noNetwork.mjs (installed by the test harness's `--import`, and by lib/paths.ts, ytdlp/runYtdlp.ts, social/playwrightRuntime.ts on import), common/ytdlp/storedUrlPageOpen.ts, common/controller/seeder.ts, scripts/test-files.mjs", doc: "`1`: nothing in the process reaches a host that is not loopback. A connection (every fetch, http(s) request, WebSocket and UDP datagram) to another host fails with an `ENONETWORK` error naming the door. Spawning yt-dlp, gallery-dl, ffmpeg, curl or wget with such a URL is refused. A browser gets a proxy that does not answer, and Firefox is refused. The Odysee player-page opener refuses by name. Every test script sets it (each package's `test`, `pnpm test:scripts`, `pnpm test:files`) and preloads the guard into every node process the run starts, through `NODE_OPTIONS=--import=…/common/lib/noNetwork.mjs`. A test file run by hand must do the same." }, + { name: "ARCHILYZER_NO_NETWORK_LOG", audience: "internal", default: "unset (no log)", readBy: "common/lib/noNetwork.mjs", doc: "A file. Under `ARCHILYZER_NO_NETWORK`, each refused door adds one JSON line to it: the door, the target and the process's argv. It finds the tests that reach for the network even when their code swallows the failure." }, + { name: "DO_NOT_TRACK", audience: "internal", default: "unset", readBy: "common/lib/noNetwork.mjs", doc: "The common opt-out of CLI telemetry. Set to `1` for the run's children when `ARCHILYZER_NO_NETWORK` is on, unless already set." }, + { name: "HYPERFRAMES_NO_TELEMETRY", audience: "internal", default: "unset (HyperFrames sends usage telemetry)", readBy: "common/lib/noNetwork.mjs (for the HyperFrames CLI umtool renders through)", doc: "`1`: the HyperFrames CLI sends no telemetry. Set to `1` for the run's children when `ARCHILYZER_NO_NETWORK` is on, unless already set. Outside test runs, nothing sets it." }, { name: "E2E_TEST_ROUTES", audience: "test", default: "off", readBy: "editor/app/api/test/_guard.ts, editor/instrumentation.ts", doc: "`1` opens the editor's `/api/test/*` routes and marks a test server at boot. Set by `editor/playwright.config.ts` on its test server, and by nothing else." }, { name: "E2E_MODE", audience: "test", default: "`start`", readBy: "editor/playwright.config.ts, umtool/playwright.config.ts, scripts/e2e-stamp.mjs", doc: "`start`: the editor and umtool suites run against `next start` from a build `scripts/e2e-stamp.mjs` vouches for, rebuilt through the heavy slot when the tree moved. `dev`: against `next dev`, for iterating on one spec. The export and homepage suites always run `next dev` (static exports) and say so when asked for `start`." }, { name: "E2E_NEXT_DIST_DIR", audience: "test", default: "`.next`", readBy: "editor/next.config.ts, export/next.config.ts", doc: "The editor's build directory for the e2e suite's start mode (`.next/e2e`), so a test build never replaces the `.next` a running editor serves from. Set by `scripts/e2e-stamp.mjs` for its build and by `editor/playwright.config.ts` for its test server — and for the editor suite's export dev server (`.next/e2e-editor`), which then runs beside the export suite's own (Next allows one `next dev` per dist dir)." }, diff --git a/common/lib/noNetwork.d.mts b/common/lib/noNetwork.d.mts @@ -0,0 +1,17 @@ +// Types for ./noNetwork.mjs: the ARCHILYZER_NO_NETWORK switch. +export const NO_NETWORK_ENV: "ARCHILYZER_NO_NETWORK"; +export function noNetwork(env?: Record<string, string | undefined>): boolean; +export function isLoopbackHost(host: string | null | undefined): boolean; +export class NoNetworkError extends Error { + constructor(door: string, target: string); + code: "ENONETWORK"; + door: string; + target: string; +} +export function assertNetworkAllowed(door: string, url: string | URL, env?: Record<string, string | undefined>): void; +export function guardSpawn(file: string, args: readonly string[]): { refuse: string } | { args: string[] }; +export function installNoNetworkGuard(): void; +export function guardShell(command: string): { refuse: string } | { args: string[] }; +export function withPreload(nodeOptions: string | undefined): string; +export function guardedChildEnv(env: Record<string, string | undefined>): Record<string, string | undefined>; +export function announceNoNetwork(line: string): boolean; diff --git a/common/lib/noNetwork.mjs b/common/lib/noNetwork.mjs @@ -0,0 +1,590 @@ +// ARCHILYZER_NO_NETWORK=1: NOTHING IN THIS PROCESS REACHES ANOTHER HOST. +// +// The operator's rule is that nothing fetches outside the editor's paced +// paths, and a burst of requests from a test run is exactly what makes a site +// challenge him. Every test harness sets this switch (every package's test +// script, `pnpm test:scripts`, `pnpm test:files`). With it set, the process's +// outward doors refuse before any request is made, and the error names the +// door. The default (unset) changes nothing. +// +// A door is one of: +// - a connection: net.Socket#connect, which every fetch, http(s) request, +// WebSocket and tracker announce in this process goes through, and dgram, +// for UDP trackers. A connection to a host that is not loopback fails with +// the socket's usual `error` event, so a caller handles it like any other +// failed connection. +// - a child process: a networking tool spawned for another host is refused +// (the spawn throws). The tools are yt-dlp, gallery-dl, curl, wget, +// streamlink and git when a URL or `host:path` names one; ffmpeg and +// ffprobe by their inputs and output only; ssh, scp and rsync by their +// destination; gh always; pip, uv and kin when they install. A tool counts +// only where it is the COMMAND (the executable, what a wrapper or a shell +// string runs, `shell: true` included), so `--cookies-from-browser firefox` +// and a test's `fake-ytdlp.mjs` pass. A browser is given a proxy that does +// not answer, so loopback and file:// pages still load; Playwright reaches +// its browser this way too. Firefox is refused. A child given an +// environment of its own gets the switch and this module's preload put +// back in. npm, pnpm and npx run with `npm_config_offline=true`; telemetry +// is opted out (DO_NOT_TRACK, HYPERFRAMES_NO_TELEMETRY). +// - a worker thread: each one runs this module first. +// - a named door that refuses by itself, earlier and by name: the Odysee +// player-page opener, for example (`assertNetworkAllowed`). +// Loopback (localhost, 127.0.0.0/8, ::1) is never refused, so a test's fake +// server keeps working. A loopback NAME's lookup is checked as well: a custom +// `lookup` or a hosts file cannot map it elsewhere. +// +// It installs itself when this module is imported with the switch set. The +// harness preloads it (`NODE_OPTIONS=--import=…`), and the door modules +// import it too, so a test run is covered however it is started. Outside a +// test run (no NODE_TEST_CONTEXT, no preload), installing says so on stderr, +// and the editor's and umtool's boot say it again. +// +// KNOWN LIMITS — what a JS guard cannot see: +// - a unix socket (or a named pipe) is never refused. A local proxy listening +// on one could carry a request out. +// - native code's own sockets: node-datachannel's WebRTC (STUN/ICE, peer +// traffic), and any addon. The seeder names no STUN servers under the +// switch, which is the one such path the repo has. +// - `dns.resolve*` queries (a lookup before a REFUSED connection never happens). +// - a process this one did not start, and what a non-node child starts. +// +// Plain ESM: umtool and the scripts run it under bare node. +import childProcess from "node:child_process"; +import { appendFileSync } from "node:fs"; +import dgram from "node:dgram"; +import dns from "node:dns"; +import { syncBuiltinESMExports } from "node:module"; +import net from "node:net"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { promisify } from "node:util"; +import workerThreads from "node:worker_threads"; + +export const NO_NETWORK_ENV = "ARCHILYZER_NO_NETWORK"; + +/** @param {Record<string, string | undefined>} [env] */ +export function noNetwork(env = process.env) { + const v = env[NO_NETWORK_ENV]; + return v !== undefined && v !== "" && v !== "0"; +} + +/** @param {string | null | undefined} host */ +export function isLoopbackHost(host) { + if (host === undefined || host === null || host === "") return true; // node's default host: localhost + const h = String(host).replace(/^\[|\]$/g, "").toLowerCase(); + if (h === "localhost" || h.endsWith(".localhost")) return true; + if (/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h)) return true; + if (h === "::1" || h === "0:0:0:0:0:0:0:1") return true; + if (/^::ffff:127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h)) return true; + return false; +} + +export class NoNetworkError extends Error { + /** @param {string} door @param {string} target */ + constructor(door, target) { + super(`${NO_NETWORK_ENV}=1: ${door} refused (${target}) — nothing in this process may reach another host`); + this.name = "NoNetworkError"; + this.code = "ENONETWORK"; + this.door = door; + this.target = target; + // ARCHILYZER_NO_NETWORK_LOG: every refusal, one JSON line, for a run that + // wants to know which tests reach for the network — including those whose + // code swallows the failure and passes anyway. + const log = process.env.ARCHILYZER_NO_NETWORK_LOG; + if (log) { + try { + appendFileSync(/* turbopackIgnore: true */ log, `${JSON.stringify({ door, target, argv: process.argv.slice(1, 4), cwd: process.cwd() })}\n`); + } catch { + /* the log is a convenience */ + } + } + } +} + +/** The first frame outside this module and node's internals: where a door was asked from. */ +function caller() { + const lines = (new Error().stack ?? "").split("\n").slice(1); + for (const l of lines) { + if (l.includes("noNetwork.mjs") || l.includes("node:") || l.includes("(native)")) continue; + const m = /\(?((?:file:\/\/)?\/[^():]+):(\d+):\d+\)?\s*$/.exec(l); + if (m) return `${path.relative(/* turbopackIgnore: true */ process.cwd(), m[1].replace(/^file:\/\//, ""))}:${m[2]}`; + } + return "unknown caller"; +} + +/** + * A named door's check, before it makes a request: refuses (throws a + * NoNetworkError) when the switch is set and `url`'s host is not loopback. + * @param {string} door what is asking, e.g. "the Odysee player-page opener" + * @param {string | URL} url + * @param {Record<string, string | undefined>} [env] + */ +export function assertNetworkAllowed(door, url, env = process.env) { + if (!noNetwork(env)) return; + let host = ""; + try { + host = new URL(String(url)).hostname; + } catch { + host = String(url); + } + if (!isLoopbackHost(host)) throw new NoNetworkError(door, String(url)); +} + +// --- child processes ---------------------------------------------------------- + +// A networking tool, by its basename (an extension and a version suffix are allowed). +const NETWORK_TOOLS = /^(yt-dlp(_linux|_macos)?|youtube-dl|gallery-dl|curl|wget|streamlink|aria2c|rclone|wrangler|nitter|twitch-dl|git)(\.(exe|py|sh))?$/; +// ffmpeg and its kin: only an INPUT (`-i`) or the output names a host; a URL in +// a -metadata comment, a drawtext or -headers for a local input asks nothing. +const FFMPEG_KIN = /^(ffmpeg|ffprobe|ffplay)$/; +// Always another host unless what they are pointed at is loopback. +const REMOTE_SHELLS = /^(ssh|scp|sftp|rsync|mosh)$/; +// Network by nature, whatever the arguments (but `--version`/`--help`). +const ALWAYS_NETWORK = /^(gh|hub|glab)$/; +// Installers: refused when the subcommand fetches. +// (npm, pnpm, yarn and npx are given npm_config_offline=true instead: they read their cache.) +const INSTALLERS = /^(pip|pip3|uv|pipx|bun|cargo|go)$/; +const INSTALL_VERBS = new Set(["install", "i", "add", "download", "sync", "lock", "update", "upgrade", "up", "dlx", "exec", "x", "create", "init", "get", "fetch", "publish", "login"]); +const PYTHON = /^python(\d(\.\d+)?)?$/; +const BROWSERS = /^(chrome|chromium|chromium-browser|google-chrome(-stable)?|chrome-headless-shell|headless_shell|msedge|brave(-browser)?)$/; +const FIREFOX = /^(firefox(-esr)?|librewolf)$/; +const URL_IN = /\b(?:https?|wss?|rtmps?|rtsp|ftp):\/\/[^\s"'<>]+/gi; +// A proxy nobody listens on: a browser asking another host gets a refused +// connection, and the implicit bypass keeps loopback direct. +const DEAD_PROXY = "--proxy-server=http://127.0.0.1:9"; + +/** @param {string} w */ +const base = (w) => path.basename(String(w)).replace(/\.(cmd|exe)$/i, ""); + +/** The non-loopback URLs a command line names. @param {readonly string[]} words */ +function outwardUrls(words) { + const out = []; + for (const w of words) { + for (const m of String(w).matchAll(URL_IN)) { + try { + if (!isLoopbackHost(new URL(m[0]).hostname)) out.push(m[0]); + } catch { + /* not a URL after all */ + } + } + } + return out; +} + +// Words that run the next word as a command (`xvfb-run chrome …`, `timeout 30 yt-dlp …`). +const WRAPPERS = /^(xvfb-run|env|nice|ionice|timeout|setsid|stdbuf|nohup|systemd-run|sudo|exec|time|chrt|taskset)$/; +const SHELLS = /^(sh|bash|dash|zsh|ash|ksh)$/; + +/** + * The COMMANDS of a command line — the executable, what a wrapper runs, the + * first word of a shell string and of each of its pipeline stages — each with + * the words that follow it, and its index in `words` (-1 inside a shell + * string). An argument VALUE is not a command: `--cookies-from-browser firefox` + * starts no Firefox, `--ffmpeg-location ffmpeg` runs no ffmpeg. + * @param {readonly string[]} words + * @returns {Array<{ word: string, at: number, args: string[] }>} + */ +function commandWords(words) { + const out = []; + const skippable = (t) => /^\w+=/.test(t) || /^-/.test(t) || /^\d+[smhd]?$/.test(t); + const shellString = (str) => { + for (const stage of String(str).split(/\|\||&&|[|;&\n]/)) { + const toks = stage.trim().split(/\s+/).filter(Boolean).map((t) => t.replace(/^["']|["']$/g, "")); + let i = 0; + while (i < toks.length && (WRAPPERS.test(base(toks[i])) || skippable(toks[i]))) i += 1; + if (!toks[i]) continue; + if (SHELLS.test(base(toks[i])) && toks[i + 1] === "-c") { + shellString(toks.slice(i + 2).join(" ")); + continue; + } + out.push({ word: toks[i], at: -1, args: toks.slice(i + 1) }); + } + }; + let i = 0; + while (i < words.length) { + const w = words[i]; + const b = base(w); + if (SHELLS.test(b)) { + out.push({ word: w, at: i, args: words.slice(i + 1) }); + const c = words.indexOf("-c", i + 1); + if (c > 0 && words[c + 1] !== undefined) shellString(words[c + 1]); + break; + } + out.push({ word: w, at: i, args: words.slice(i + 1) }); + if (!WRAPPERS.test(b)) break; + // The wrapped command: the next word that is not a flag, an assignment or a duration. + i += 1; + while (i < words.length && skippable(words[i])) i += 1; + } + return out; +} + +const GIT_NETWORK = new Set(["clone", "fetch", "pull", "push", "ls-remote", "remote", "submodule", "archive"]); + +/** `user@host:path` / `host:path` (scp, rsync, git): the host, or null. */ +function scpHost(w) { + if (/^[a-z][\w+.-]*:\/\//i.test(w) || w.startsWith("/") || w.startsWith(".")) return null; + const m = /^([^@\s/]+@)?(\[[^\]]+\]|[^:\s/@]+):/.exec(w); + if (!m) return null; + return m[1] && !/[.@]/.test(m[2]) ? `${m[1]}${m[2]}` : m[2]; +} + +// ssh's options that take a value (so the destination is found past them). +const SSH_VALUE_OPTS = new Set(["-b", "-c", "-D", "-E", "-e", "-F", "-I", "-i", "-J", "-L", "-l", "-m", "-O", "-o", "-p", "-Q", "-R", "-S", "-W", "-w", "-P"]); + +/** Why one command reaches another host, or null. @param {{ word: string, args: string[] }} c */ +function outwardReason(c) { + const b = base(c.word); + const urls = outwardUrls(c.args); + if (NETWORK_TOOLS.test(b)) { + if (b === "git") { + // Only git's network commands, by a URL or `user@host:path` among their + // arguments: `git show <sha>:<path>` and `HEAD:file` are revisions, and a + // URL in a commit message asks nothing. (A named remote — `git fetch + // origin` — cannot be judged from the command line.) + const sub = c.args.find((w) => !w.startsWith("-")); + if (!GIT_NETWORK.has(sub ?? "")) return null; + if (urls.length) return `spawning git ${sub} for ${urls[0]}`; + const remote = c.args.map(scpHost).find((h) => h && !isLoopbackHost(h.replace(/^[^@]*@/, "")) && /[.@]|^\[/.test(h)); + return remote ? `spawning git ${sub} for ${remote}` : null; + } + if (urls.length) return `spawning ${b} for ${urls[0]}`; + return null; + } + if (FFMPEG_KIN.test(b)) { + // The inputs (`-i` values, concat:/protocol inputs included) and the last word (the output, or ffprobe's input). + const judged = c.args.filter((w, i) => c.args[i - 1] === "-i"); + if (c.args.length) judged.push(c.args[c.args.length - 1]); + const u = outwardUrls(judged); + return u.length ? `spawning ${b} for ${u[0]}` : null; + } + if (REMOTE_SHELLS.test(b)) { + if (b === "ssh" || b === "mosh" || b === "sftp") { + let dest = null; + for (let i = 0; i < c.args.length; i += 1) { + const w = c.args[i]; + if (SSH_VALUE_OPTS.has(w)) i += 1; + else if (!w.startsWith("-")) { + dest = w; + break; + } + } + if (dest === null) return null; + const host = dest.replace(/^ssh:\/\//, "").replace(/^[^@]*@/, "").replace(/:\d+$/, ""); + return isLoopbackHost(host) ? null : `spawning ${b} to ${host}`; + } + const remote = c.args.map(scpHost).find((h) => h && !isLoopbackHost(h.replace(/^[^@]*@/, ""))); + if (remote) return `spawning ${b} to ${remote}`; + return urls.length ? `spawning ${b} for ${urls[0]}` : null; + } + if (ALWAYS_NETWORK.test(b)) { + return c.args.every((w) => /^(--version|-v|--help|-h|help|version)$/.test(w)) ? null : `spawning ${b} (it always asks its service)`; + } + if (INSTALLERS.test(b) || (PYTHON.test(b) && c.args[0] === "-m" && /^(pip|pip3|uv)$/.test(c.args[1] ?? ""))) { + const sub = (PYTHON.test(b) ? c.args.slice(2) : c.args).find((w) => !w.startsWith("-")); + if (sub && INSTALL_VERBS.has(sub)) return `spawning ${PYTHON.test(b) ? `${b} -m ${c.args[1]}` : b} ${sub} (it fetches packages)`; + return urls.length ? `spawning ${b} for ${urls[0]}` : null; + } + if (PYTHON.test(b) && urls.length) return `spawning ${b} for ${urls[0]}`; + return null; +} + +/** + * What the switch does to one spawn: `{refuse}` with the door, or the argv to + * run (a browser's with the dead proxy added). Pure; exported for its test. + * @param {string} file @param {readonly string[]} args + * @returns {{ refuse: string } | { args: string[] }} + */ +export function guardSpawn(file, args) { + const words = [String(file), ...args.map(String)]; + const commands = commandWords(words); + for (const c of commands) { + const why = outwardReason(c); + if (why) return { refuse: why }; + } + const fox = commands.find((c) => FIREFOX.test(base(c.word))); + if (fox) return { refuse: `starting ${base(fox.word)} (no proxy switch it obeys)` }; + const browser = commands.find((c) => BROWSERS.test(base(c.word))); + if (browser) { + const urls = outwardUrls(browser.args); + if (urls.length) return { refuse: `starting ${base(browser.word)} on ${urls[0]}` }; + const all = [...words]; + // In a shell string the flag cannot be placed; a browser there with no URL asks nothing yet. + if (browser.at >= 0 && !all.some((w) => w.startsWith("--proxy-server="))) all.splice(browser.at + 1, 0, DEAD_PROXY); + return { args: all.slice(1) }; + } + return { args: [...args] }; +} + +/** A shell command line (exec, or spawn with `shell: true`): what /bin/sh would run. */ +export function guardShell(command) { + const g = guardSpawn("sh", ["-c", String(command)]); + return "refuse" in g ? g : { args: [] }; +} + +/** spawn/execFile-style (file, args?, options?, cb?) → [file, args, rest]. */ +function splitArgs(argList) { + const [file, maybeArgs, ...rest] = argList; + if (Array.isArray(maybeArgs)) return [file, maybeArgs, rest]; + return [file, [], maybeArgs === undefined ? rest : [maybeArgs, ...rest]]; +} + +/** This module, as NODE_OPTIONS can name it whatever the path holds (a file URL: no spaces to quote). */ +// (Never thrown at import: a bundler may hand this module an import.meta.url that is not a file URL.) +const SELF_PATH = (() => { + try { + return fileURLToPath(import.meta.url); + } catch { + return null; + } +})(); +const SELF_URL = SELF_PATH ? pathToFileURL(SELF_PATH).href : String(import.meta.url); +const PRELOAD = `--import=${SELF_URL}`; + +/** NODE_OPTIONS with this module's preload in it (once). */ +export function withPreload(nodeOptions) { + const cur = nodeOptions ?? ""; + return /noNetwork\.mjs/.test(cur) ? cur : `${PRELOAD} ${cur}`.trim(); +} + +/** + * The environment a child runs with when its caller gave it one of its own + * (`env: {}`): the switch, the preload and the offline/opt-out settings put + * back, so a child cannot step outside the guard by being given less. + * @param {Record<string, string | undefined>} env + */ +export function guardedChildEnv(env) { + return { + ...env, + [NO_NETWORK_ENV]: process.env[NO_NETWORK_ENV] || "1", + NODE_OPTIONS: withPreload(env.NODE_OPTIONS), + npm_config_offline: env.npm_config_offline ?? "true", + DO_NOT_TRACK: env.DO_NOT_TRACK ?? "1", + HYPERFRAMES_NO_TELEMETRY: env.HYPERFRAMES_NO_TELEMETRY ?? "1", + }; +} + +/** The options object among `rest` (the first plain object), and its index. */ +function optionsIn(rest) { + const at = rest.findIndex((x) => x !== null && typeof x === "object" && !Array.isArray(x)); + return at >= 0 ? { at, opts: rest[at] } : { at: -1, opts: null }; +} + +/** `rest` with options.env (when the caller gave one) carrying the guard. */ +function guardOptions(rest) { + const { at, opts } = optionsIn(rest); + if (!opts || !opts.env || typeof opts.env !== "object") return rest; + const next = [...rest]; + next[at] = { ...opts, env: guardedChildEnv(opts.env) }; + return next; +} + +// exec/execFile carry a custom promisified form (resolving {stdout, stderr}); +// a wrapper keeps it, guarded the same way, or `promisify(execFile)` would +// resolve to stdout alone. +function keepCustomPromisify(guarded, orig, check) { + const custom = orig[promisify.custom]; + if (typeof custom === "function") { + guarded[promisify.custom] = function guardedPromisified(...argList) { + let next; + try { + next = check(argList); + } catch (e) { + return Promise.reject(e); // a promise-returning door refuses as a rejection + } + return custom.apply(this, next); + }; + } + return guarded; +} + +function wrapFileStyle(orig, name) { + const check = (argList) => { + const [file, args, rest] = splitArgs(argList); + const { opts } = optionsIn(rest); + // `shell: true`: the file and its arguments are one command line for /bin/sh. + const g = opts?.shell ? guardShell([file, ...args].join(" ")) : guardSpawn(String(file), args); + if ("refuse" in g) throw new NoNetworkError(`child_process.${name} (${caller()})`, g.refuse); + return [file, opts?.shell ? args : g.args, ...guardOptions(rest)]; + }; + const guarded = function guarded(...argList) { + return orig.apply(this, check(argList)); + }; + return keepCustomPromisify(guarded, orig, check); +} + +function wrapShellStyle(orig, name) { + const check = (argList) => { + // exec runs its command line in /bin/sh: read as the shell would. + const g = guardShell(argList[0]); + if ("refuse" in g) throw new NoNetworkError(`child_process.${name} (${caller()})`, g.refuse); + return [argList[0], ...guardOptions(argList.slice(1))]; + }; + const guarded = function guarded(...argList) { + return orig.apply(this, check(argList)); + }; + return keepCustomPromisify(guarded, orig, check); +} + +// --- worker threads --------------------------------------------------------------- + +// A worker is a fresh module graph: neither the preload nor this process's +// patches reach it. Each one runs this module first (it installs itself, the +// worker seeing the switch), then its own code. +function guardWorkers() { + const Orig = workerThreads.Worker; + class GuardedWorker extends Orig { + constructor(filename, options = {}) { + const opts = { ...options }; + if (opts.env && typeof opts.env === "object") opts.env = guardedChildEnv(opts.env); + const guard = SELF_PATH ? `require(${JSON.stringify(SELF_PATH)});\n` : ""; + let code; + if (opts.eval) { + code = guard + String(filename); + } else { + const href = filename instanceof URL ? filename.href : /^(file|data):/.test(String(filename)) ? String(filename) : pathToFileURL(path.resolve(String(filename))).href; + code = `${guard}import(${JSON.stringify(href)}).catch((e) => { setImmediate(() => { throw e; }); });\n`; + } + super(code, { ...opts, eval: true }); + } + } + workerThreads.Worker = GuardedWorker; +} + +// --- connections --------------------------------------------------------------- + +/** The host a Socket#connect call names, or null for a unix socket / pipe. */ +function connectHost(args) { + let a = args; + if (Array.isArray(a[0])) a = a[0]; // net's own normalized [options, cb] + const first = a[0]; + if (first && typeof first === "object") { + if (first.path) return null; + return first.host ?? first.hostname ?? "localhost"; + } + if (typeof first === "string" && !/^\d+$/.test(first)) return null; // a path + return typeof a[1] === "string" ? a[1] : "localhost"; +} + +/** The address a dgram send names, by argument position — or null (a connected socket's send). */ +function sendAddress(args) { + const [, a1, a2, a3, a4] = args; + // send(msg, offset, length, port, address?, cb?) + if (typeof a1 === "number" && typeof a2 === "number" && a3 !== undefined && typeof a3 !== "function") { + return typeof a4 === "string" ? a4 : null; + } + // send(msg, port, address?, cb?) + if (typeof a1 === "number" || (typeof a1 === "string" && /^\d+$/.test(a1))) return typeof a2 === "string" ? a2 : null; + return null; // send(msg[, offset, length], cb?): the socket's connected peer (its connect was guarded) +} + +/** A lookup whose answers are checked: a name may not resolve to another host. */ +function checkedLookup(lookup, host) { + return function guardedLookup(name, options, cb) { + const done = typeof options === "function" ? options : cb; + const opts = typeof options === "function" ? {} : options; + return lookup(name, opts, (err, address, family) => { + if (err) return done(err); + const all = Array.isArray(address) ? address.map((a) => a.address) : [address]; + const away = all.find((a) => !isLoopbackHost(a)); + if (away) return done(new NoNetworkError(`a connection's lookup (${host})`, `${name} → ${away}`)); + return done(null, address, family); + }); + }; +} + +let installed = false; +let announced = false; + +/** + * Say, once per process, that the switch is on (the guard's own line, or a + * boot's — the editor's and umtool's instrumentation — whichever comes first). + * @param {string} line + * @returns {boolean} whether this call printed it + */ +export function announceNoNetwork(line) { + if (announced || !workerThreads.isMainThread) return false; + announced = true; + process.stderr.write(`${line}\n`); + return true; +} + +/** Install the process-wide guard (idempotent). Called on import when the switch is set. */ +export function installNoNetworkGuard() { + if (installed) return; + installed = true; + // Said out loud when nothing says it is a test run: the switch in a service + // unit must not look like a normal boot. + const harness = !!process.env.NODE_TEST_CONTEXT || /noNetwork\.mjs/.test(process.env.NODE_OPTIONS ?? ""); + if (!harness) announceNoNetwork(`${NO_NETWORK_ENV}=1: this process refuses every non-loopback connection`); + // What children would ask by themselves, said off before they start: npm/npx + // read only their cache (a render's `npx --yes hyperframes@…` asked the npm + // registry every run), and HyperFrames and other CLIs send no telemetry + // (PostHog, on every render). And every node child preloads this module. + // Children inherit this environment. + process.env.npm_config_offline ??= "true"; + process.env.DO_NOT_TRACK ??= "1"; + process.env.HYPERFRAMES_NO_TELEMETRY ??= "1"; + process.env.NODE_OPTIONS = withPreload(process.env.NODE_OPTIONS); + const origConnect = net.Socket.prototype.connect; + net.Socket.prototype.connect = function guardedConnect(...args) { + const host = connectHost(args); + if (host !== null && !isLoopbackHost(host)) { + const port = Array.isArray(args[0]) ? args[0][0]?.port : typeof args[0] === "object" ? args[0]?.port : args[0]; + const err = new NoNetworkError(`a connection (${caller()})`, `${host}:${port ?? "?"}`); + process.nextTick(() => this.destroy(err)); + return this; + } + // A loopback NAME is looked up: its answers are checked too (a custom + // `lookup`, or a hosts file, mapping it elsewhere). + if (host !== null && net.isIP(String(host).replace(/^\[|\]$/g, "")) === 0) { + const normalized = Array.isArray(args[0]); + const o = normalized ? args[0][0] : args[0]; + if (o && typeof o === "object") { + const next = { ...o, lookup: checkedLookup(o.lookup ?? dns.lookup, String(host)) }; + if (normalized) { + const arr = [next, ...args[0].slice(1)]; + for (const k of Object.getOwnPropertySymbols(args[0])) arr[k] = args[0][k]; + return origConnect.apply(this, [arr, ...args.slice(1)]); + } + return origConnect.apply(this, [next, ...args.slice(1)]); + } + } + return origConnect.apply(this, args); + }; + const origSend = dgram.Socket.prototype.send; + dgram.Socket.prototype.send = function guardedSend(...args) { + const cb = typeof args.at(-1) === "function" ? args.at(-1) : null; + const address = sendAddress(args); + if (address !== null && !isLoopbackHost(address)) { + const err = new NoNetworkError(`a UDP datagram (${caller()})`, address); + if (cb) process.nextTick(() => cb(err)); + else process.nextTick(() => this.emit("error", err)); + return; + } + return origSend.apply(this, args); + }; + const origUdpConnect = dgram.Socket.prototype.connect; + dgram.Socket.prototype.connect = function guardedUdpConnect(port, address, ...rest) { + if (typeof address === "string" && !isLoopbackHost(address)) { + const err = new NoNetworkError(`a UDP connect (${caller()})`, `${address}:${port}`); + process.nextTick(() => this.emit("error", err)); + return; + } + return origUdpConnect.call(this, port, address, ...rest); + }; + for (const name of ["spawn", "spawnSync", "execFile", "execFileSync", "fork"]) { + childProcess[name] = wrapFileStyle(childProcess[name], name); + } + for (const name of ["exec", "execSync"]) { + childProcess[name] = wrapShellStyle(childProcess[name], name); + } + guardWorkers(); + // ESM named imports of node builtins are live bindings of their CJS + // exports: this makes `import { spawn } from "node:child_process"` and + // `import { Worker } from "node:worker_threads"`, done anywhere, before or + // after, see the guarded ones. + syncBuiltinESMExports(); +} + +if (noNetwork()) installNoNetworkGuard(); diff --git a/common/lib/noNetwork.test.ts b/common/lib/noNetwork.test.ts @@ -0,0 +1,295 @@ +// ARCHILYZER_NO_NETWORK (lib/noNetwork.mjs): every door refuses a host that is +// not loopback, loopback still works, and with the switch unset nothing changes. +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/noNetwork.test.ts +// +// The "outward" address is 192.0.2.1 (TEST-NET-1, documentation only: nothing +// answers there), so even a broken guard would reach no real site. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { execFileSync, exec, spawn, spawnSync } from "node:child_process"; +import dgram from "node:dgram"; +import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import http from "node:http"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +// This file holds the switch itself, however it is run. +process.env.ARCHILYZER_NO_NETWORK = "1"; +const nn = await import("./noNetwork.mjs"); +nn.installNoNetworkGuard(); + +const OUT = "192.0.2.1"; +const MODULE = fileURLToPath(new URL("./noNetwork.mjs", import.meta.url)); + +const refusedBy = (e: unknown): string => { + const err = e as { code?: string; cause?: { code?: string; message?: string }; message?: string }; + if (err?.code === "ENONETWORK") return err.message ?? ""; + if (err?.cause?.code === "ENONETWORK") return err.cause.message ?? ""; + return ""; +}; + +// A stand-in for a networking tool, named like one: it records that it ran. +async function fakeTool(name: string): Promise<{ bin: string; ran: string; dir: string }> { + const dir = await mkdtemp(path.join(tmpdir(), "no-network-")); + const ran = path.join(dir, "ran"); + const bin = path.join(dir, name); + await writeFile(bin, `#!/bin/sh\necho "$@" >> ${JSON.stringify(ran)}\n`); + await chmod(bin, 0o755); + return { bin, ran, dir }; +} + +test("the switch reads 1 as on, and unset, empty or 0 as off; loopback is every spelling of it", () => { + assert.equal(nn.noNetwork({ ARCHILYZER_NO_NETWORK: "1" }), true); + for (const v of [undefined, "", "0"]) assert.equal(nn.noNetwork({ ARCHILYZER_NO_NETWORK: v }), false); + for (const h of ["localhost", "127.0.0.1", "127.8.9.10", "::1", "[::1]", "::ffff:127.0.0.1", "app.localhost", ""]) assert.equal(nn.isLoopbackHost(h), true, h); + for (const h of [OUT, "odysee.com", "10.0.0.1", "::ffff:192.0.2.1", "localhost.example"]) assert.equal(nn.isLoopbackHost(h), false, h); +}); + +test("door: what children ask by themselves is said off — npm reads its cache only, CLIs send no telemetry", () => { + assert.equal(process.env.npm_config_offline, "true"); + assert.equal(process.env.DO_NOT_TRACK, "1"); + assert.equal(process.env.HYPERFRAMES_NO_TELEMETRY, "1"); +}); + +test("door: fetch to another host is refused before it connects, naming the door", async () => { + await assert.rejects(fetch(`https://${OUT}/x`), (e) => /a connection .* refused \(192\.0\.2\.1:443\)/.test(refusedBy(e))); +}); + +test("door: an http(s) request to another host fails with the socket's error", async () => { + const err = await new Promise<Error>((resolve) => http.get(`http://${OUT}/`).on("error", resolve)); + assert.match(refusedBy(err), /refused \(192\.0\.2\.1:80\)/); +}); + +test("door: a WebSocket to another host closes with an error, never connected", async () => { + const ws = new WebSocket(`wss://${OUT}/announce`); + const ev = await new Promise<string>((resolve) => { + ws.onopen = () => resolve("open"); + ws.onerror = () => resolve("error"); + }); + assert.equal(ev, "error"); +}); + +test("door: a UDP datagram to another host (a UDP tracker) is refused", async () => { + const s = dgram.createSocket("udp4"); + try { + const err = await new Promise<Error | null>((resolve) => s.send("x", 6969, OUT, (e) => resolve(e))); + assert.match(refusedBy(err), /a UDP datagram .* refused \(192\.0\.2\.1\)/); + } finally { + s.close(); + } +}); + +test("loopback is never refused: a test's own server answers", async () => { + const srv = http.createServer((_q, r) => r.end("ok")); + await new Promise<void>((r) => srv.listen(0, "127.0.0.1", () => r())); + try { + const port = (srv.address() as { port: number }).port; + assert.equal(await (await fetch(`http://127.0.0.1:${port}/`)).text(), "ok"); + assert.equal(await (await fetch(`http://localhost:${port}/`)).text(), "ok"); + } finally { + await new Promise<void>((r) => srv.close(() => r())); + } +}); + +test("door: yt-dlp (or ffmpeg, gallery-dl…) spawned for another host is refused — spawn, spawnSync, execFile, exec, execa", async () => { + const yt = await fakeTool("yt-dlp"); + try { + const url = `https://${OUT}/watch?v=x`; + assert.throws(() => spawn(yt.bin, ["--no-playlist", url]), (e) => /spawning yt-dlp for https:\/\/192\.0\.2\.1/.test(refusedBy(e))); + assert.throws(() => spawnSync(yt.bin, [url]), (e) => refusedBy(e) !== ""); + assert.throws(() => execFileSync(yt.bin, [url]), (e) => refusedBy(e) !== ""); + assert.throws(() => exec(`${yt.bin} ${url}`), (e) => refusedBy(e) !== ""); + assert.throws(() => spawnSync("sh", ["-c", `ffmpeg -i ${url} out.mp4`]), (e) => /spawning ffmpeg/.test(refusedBy(e))); + // The repo's yt-dlp runner spawns through execa: the same door. + const { execa } = await import("execa"); + await assert.rejects(execa(yt.bin, [url]), (e) => refusedBy(e) !== ""); + await assert.rejects(readFile(yt.ran, "utf8"), "it never ran"); + // Loopback, and a test's fake named as one (fake-ytdlp.mjs), run. + assert.equal(spawnSync(yt.bin, ["http://127.0.0.1:4000/v"]).status, 0); + const fake = await fakeTool("fake-ytdlp.mjs"); + assert.equal(spawnSync(fake.bin, [url]).status, 0); + await rm(fake.dir, { recursive: true, force: true }); + assert.match(await readFile(yt.ran, "utf8"), /127\.0\.0\.1/); + } finally { + await rm(yt.dir, { recursive: true, force: true }); + } +}); + +test("door: a browser is given a proxy that does not answer; on another host's URL, or Firefox, it is refused", () => { + const g = nn.guardSpawn("/x/ms-playwright/chromium_headless_shell-1/chrome-linux/headless_shell", ["--headless", "--remote-debugging-pipe", "about:blank"]); + assert.ok("args" in g && g.args.includes("--proxy-server=http://127.0.0.1:9"), JSON.stringify(g)); + const own = nn.guardSpawn("/usr/bin/chromium", ["--proxy-server=http://127.0.0.1:3128", "file:///tmp/card.html"]); + assert.ok("args" in own && !own.args.includes("--proxy-server=http://127.0.0.1:9"), "its own proxy is kept"); + assert.ok("refuse" in nn.guardSpawn("google-chrome", ["--headless", "https://odysee.com/@x"])); + assert.ok("refuse" in nn.guardSpawn("/usr/lib/firefox/firefox", ["-headless"])); + // Not a networking tool: untouched. + assert.deepEqual(nn.guardSpawn("node", ["script.mjs", "https://odysee.com/"]), { args: ["script.mjs", "https://odysee.com/"] }); +}); + +test("a tool or browser is one only where it is the command: an argument value is not", () => { + const url = "https://x.com/someone"; + // A fake gallery-dl told which browser's cookies to read starts no Firefox; one told where ffmpeg is runs no ffmpeg. + assert.ok("args" in nn.guardSpawn("/tmp/t/fake-gallery-dl.mjs", ["--cookies-from-browser", "firefox", url])); + assert.ok("args" in nn.guardSpawn("/tmp/t/fake-ytdlp.mjs", ["--cookies-from-browser", "chrome", "--ffmpeg-location", "ffmpeg", url])); + // What a wrapper or a shell runs is a command. + assert.ok("refuse" in nn.guardSpawn("timeout", ["30", "yt-dlp", url])); + assert.ok("refuse" in nn.guardSpawn("xvfb-run", ["-a", "chromium", url])); + assert.ok("refuse" in nn.guardSpawn("sh", ["-c", `cat list | ffmpeg -i ${url} -f null -`])); + assert.ok("refuse" in nn.guardSpawn("bash", ["-c", `FOO=1 nice -n 10 gallery-dl ${url}`])); + const wrapped = nn.guardSpawn("xvfb-run", ["-a", "/usr/bin/chromium", "--headless"]); + assert.ok("args" in wrapped && wrapped.args.includes("--proxy-server=http://127.0.0.1:9")); +}); + +test("promisify(execFile) and promisify(exec) keep their {stdout, stderr} answer, and are guarded", async () => { + const { promisify } = await import("node:util"); + const cp = await import("node:child_process"); + const run = promisify(cp.execFile); + const r = await run("sh", ["-c", "echo hi"]); + assert.equal(r.stdout, "hi\n"); + assert.equal((await promisify(cp.exec)("echo there")).stdout, "there\n"); + await assert.rejects(run("sh", ["-c", `curl https://${OUT}/`]), (e) => /spawning curl/.test(refusedBy(e))); +}); + +test("door: the Odysee player-page opener refuses by name, before any browser", async () => { + const { openPlayerPage } = await import("../ytdlp/storedUrlPageOpen"); + const lines: string[] = []; + const r = await openPlayerPage({ pageUrl: "https://odysee.com/@demo:1/x:1", cdnHost: "player.odycdn.com", signal: new AbortController().signal, onLog: (l) => lines.push(l) }); + assert.equal(r.ok, false); + assert.match(r.error ?? "", /ARCHILYZER_NO_NETWORK=1: the Odysee player-page opener refused/); + assert.match(lines.join(""), /player-page opener refused/); +}); + +test("named doors: assertNetworkAllowed refuses another host and passes loopback; with the switch off it passes all", () => { + assert.throws(() => nn.assertNetworkAllowed("a door", "https://archive.org/x"), /a door refused/); + nn.assertNetworkAllowed("a door", "http://127.0.0.1:3001/api"); + nn.assertNetworkAllowed("a door", "https://archive.org/x", {}); +}); + +test("review 2: spawn with shell: true is read as the shell would", () => { + assert.throws(() => spawnSync(`curl --max-time 1 http://${OUT}/ || true`, { shell: true }), (e) => /spawning curl/.test(refusedBy(e))); + assert.equal(spawnSync("echo ok", { shell: true, encoding: "utf8" }).stdout, "ok\n"); +}); + +test("review 2: a child given its own environment (env: {}) keeps the switch and the preload", () => { + const code = `const s=require('net').connect(80,'${OUT}');s.on('error',e=>{console.log(e.code);process.exit()});setTimeout(()=>{console.log('pending');process.exit()},2500)`; + const r = spawnSync(process.execPath, ["-e", code], { env: {}, encoding: "utf8" }); + assert.equal(r.stdout.trim(), "ENONETWORK"); + const env = nn.guardedChildEnv({ NODE_OPTIONS: "--max-old-space-size=100" }); + assert.equal(env.ARCHILYZER_NO_NETWORK, "1"); + assert.match(env.NODE_OPTIONS ?? "", /^--import=file:\/\/.*noNetwork\.mjs --max-old-space-size=100$/); + assert.equal(nn.withPreload(env.NODE_OPTIONS), env.NODE_OPTIONS, "once"); +}); + +test("review 2: a worker thread is guarded — an eval worker and a file worker", async () => { + const { Worker } = await import("node:worker_threads"); + const ask = (w: InstanceType<typeof Worker>) => + new Promise<string>((resolve) => { + w.once("message", resolve); + w.once("error", (e) => resolve(`worker error ${e.message}`)); + }); + const body = `const s=require('node:net').connect(80,'${OUT}');s.on('error',e=>require('node:worker_threads').parentPort.postMessage(e.code));s.on('connect',()=>require('node:worker_threads').parentPort.postMessage('CONNECTED'))`; + assert.equal(await ask(new Worker(body, { eval: true })), "ENONETWORK"); + const dir = await mkdtemp(path.join(tmpdir(), "no-network-w-")); + try { + const file = path.join(dir, "w.mjs"); + await writeFile(file, `import net from "node:net"; import { parentPort, workerData } from "node:worker_threads"; const s = net.connect(80, workerData.host); s.on("error", (e) => parentPort.postMessage(e.code));`); + assert.equal(await ask(new Worker(file, { workerData: { host: OUT } })), "ENONETWORK"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("review 2: git, ssh, scp, rsync, gh, pip and python are doors too — by their own rules", () => { + const refuse = (f: string, a: string[]) => assert.ok("refuse" in nn.guardSpawn(f, a), `${f} ${a.join(" ")}`); + const pass = (f: string, a: string[]) => assert.ok("args" in nn.guardSpawn(f, a), `${f} ${a.join(" ")}`); + refuse("git", ["ls-remote", `http://${OUT}/x.git`]); + refuse("git", ["clone", "git@github.invalid:me/x.git"]); + pass("git", ["log", "--oneline", "-1"]); + pass("git", ["show", "d5c884d3a00bc2fefb45d05198f3a4c342e779b6:reports/x/report.json"]); + pass("git", ["cat-file", "-p", "HEAD:README.md"]); + pass("git", ["commit", "-m", "see https://example.invalid/x"]); + refuse("git", ["fetch", `https://${OUT}/x.git`]); + pass("scp", ["a.txt", "me@localhost:/tmp/"]); + pass("git", ["clone", "/tmp/local-repo", "/tmp/copy"]); + refuse("ssh", ["-p", "2222", "me@box.invalid", "ls"]); + pass("ssh", ["-o", "BatchMode=yes", "localhost", "true"]); + refuse("scp", ["a.txt", "me@box.invalid:/tmp/"]); + refuse("rsync", ["-a", "dir/", "box.invalid:dir/"]); + pass("rsync", ["-a", "dir/", "/mnt/other/dir/"]); + refuse("gh", ["api", "repos/x/y"]); + pass("gh", ["--version"]); + refuse("pip", ["install", "requests"]); + refuse("python3", ["-m", "pip", "install", "x"]); + refuse("uv", ["sync"]); + pass("pip", ["list"]); + refuse("python3", ["fetch.py", `https://${OUT}/data`]); + pass("python3", ["scripts/speaker-embed.py", "--emb", "x", "req.json"]); +}); + +test("review 2: ffmpeg and ffprobe are judged by their inputs and output, not any URL in their arguments", () => { + const url = `https://${OUT}/v.mp4`; + assert.ok("refuse" in nn.guardSpawn("ffmpeg", ["-headers", "Referer: https://odysee.com/", "-i", url, "-c", "copy", "out.mp4"])); + assert.ok("refuse" in nn.guardSpawn("ffmpeg", ["-i", `concat:${url}|${url}`, "out.mp4"])); + assert.ok("refuse" in nn.guardSpawn("ffmpeg", ["-i", "in.mp4", "-f", "flv", `rtmp://${OUT}/live`])); + assert.ok("refuse" in nn.guardSpawn("ffprobe", ["-v", "error", url])); + assert.ok("args" in nn.guardSpawn("ffmpeg", ["-headers", "Referer: https://odysee.com/", "-i", "local.mp4", "out.mp4"])); + assert.ok("args" in nn.guardSpawn("ffmpeg", ["-f", "lavfi", "-i", "nullsrc", "-vf", "drawtext=text='https\\://youtu.be/x'", "-metadata", "comment=https://youtu.be/x", "-f", "null", "-"])); +}); + +test("review 2: a connected UDP socket's send with a string message is not read as a host", async () => { + const peer = dgram.createSocket("udp4"); + await new Promise<void>((r) => peer.bind(0, "127.0.0.1", () => r())); + const got = new Promise<string>((r) => peer.once("message", (m) => r(String(m)))); + const s = dgram.createSocket("udp4"); + try { + await new Promise<void>((r) => s.connect((peer.address() as { port: number }).port, "127.0.0.1", () => r())); + await new Promise<void>((resolve, reject) => s.send("hello from 192.0.2.1 land", (e) => (e ? reject(e) : resolve()))); + assert.equal(await got, "hello from 192.0.2.1 land"); + } finally { + s.close(); + peer.close(); + } +}); + +test("review 2: a loopback name whose lookup answers another host is refused", async () => { + const net = await import("node:net"); + const lookup = (_h: string, o: { all?: boolean }, cb: (...a: unknown[]) => void) => (o?.all ? cb(null, [{ address: OUT, family: 4 }]) : cb(null, OUT, 4)); + const err = await new Promise<Error>((resolve) => { + const sock = net.connect({ host: "localhost", port: 80, lookup: lookup as never }); + sock.once("error", resolve); + sock.once("connect", () => resolve(new Error("CONNECTED"))); + }); + assert.match(refusedBy(err), /lookup \(localhost\) refused \(localhost → 192\.0\.2\.1\)/); +}); + +test("review 2: installed outside a test run, it says so on stderr; under the harness it is silent", () => { + // A guarded process puts the preload back into any child's environment, so + // the child here is reached through env(1), which takes away what each case needs gone. + const run = (drop: string[], set: string[] = []) => + spawnSync("env", [...drop.flatMap((k) => ["-u", k]), ...set, process.execPath, "--input-type=module", "-e", `await import(${JSON.stringify(MODULE)});`], { encoding: "utf8" }).stderr; + assert.match(run(["NODE_TEST_CONTEXT", "NODE_OPTIONS"]), /ARCHILYZER_NO_NETWORK=1: this process refuses every non-loopback connection/); + assert.equal(run(["NODE_OPTIONS"], ["NODE_TEST_CONTEXT=child-v8"]), ""); + assert.equal(run(["NODE_TEST_CONTEXT"]), "", "the harness's preload in NODE_OPTIONS"); +}); + +test("unset, nothing changes: the guard is not installed and a tool runs for any URL", async () => { + const yt = await fakeTool("yt-dlp"); + try { + const probe = ` + const cp = await import("node:child_process"); + const net = await import("node:net"); + await import(${JSON.stringify(MODULE)}); + const r = cp.spawnSync(${JSON.stringify(yt.bin)}, ["https://${OUT}/watch?v=x"]); + console.log(JSON.stringify({ spawnGuarded: cp.spawn.name === "guarded", connectGuarded: net.Socket.prototype.connect.name === "guardedConnect", status: r.status }));`; + // Through env(1): a guarded process would put the switch back into a child's own environment. + const out = execFileSync("env", ["-u", "ARCHILYZER_NO_NETWORK", "-u", "NODE_OPTIONS", process.execPath, "--input-type=module", "-e", probe], { encoding: "utf8" }); + assert.deepEqual(JSON.parse(out), { spawnGuarded: false, connectGuarded: false, status: 0 }); + // (And set, the same probe sees both guarded — the names are the guard's.) + const on = execFileSync("env", ["-u", "NODE_OPTIONS", "ARCHILYZER_NO_NETWORK=1", process.execPath, "--input-type=module", "-e", probe.replace(/const r = [^;]+;/, "const r = { status: 0 };")], { encoding: "utf8" }); + assert.deepEqual(JSON.parse(on), { spawnGuarded: true, connectGuarded: true, status: 0 }); + assert.match(await readFile(yt.ran, "utf8"), /192\.0\.2\.1/, "the tool ran: nothing refused"); + } finally { + await rm(yt.dir, { recursive: true, force: true }); + } +}); diff --git a/common/lib/paths.ts b/common/lib/paths.ts @@ -1,3 +1,6 @@ +// ARCHILYZER_NO_NETWORK=1 (lib/noNetwork.mjs): imported for its effect — with the switch set, this +// process's outward doors refuse before any request. +import "./noNetwork.mjs"; import fs from "node:fs"; import path from "node:path"; import os from "node:os"; diff --git a/common/package.json b/common/package.json @@ -54,6 +54,7 @@ "./lib/montage/voiceMatch.mjs": "./lib/montage/voiceMatch.mjs", "./lib/montage/speakerCheck.mjs": "./lib/montage/speakerCheck.mjs", "./lib/ports.mjs": "./lib/ports.mjs", + "./lib/noNetwork.mjs": "./lib/noNetwork.mjs", "./lib/renderPriority.mjs": "./lib/renderPriority.mjs", "./lib/heavyQueue.mjs": "./lib/heavyQueue.mjs", "./lib/report/drafted.mjs": "./lib/report/drafted.mjs", @@ -85,7 +86,7 @@ "./testing/*": "./testing/*" }, "scripts": { - "test": "tsx --test \"*.test.ts\" \"{lib,controller,jobs,social,ytdlp,components,views,publish,bin,testing}/*.test.ts\" \"{lib,controller,jobs,social,ytdlp,components,views,publish,bin,testing}/*/*.test.ts\" \"{lib,controller,jobs,publish,testing}/*/*/*.test.ts\" \"lib/*/*/*/*.test.ts\"" + "test": "ARCHILYZER_NO_NETWORK=1 NODE_OPTIONS=\"--import=\\\"$PWD/lib/noNetwork.mjs\\\" $NODE_OPTIONS\" tsx --test \"*.test.ts\" \"{lib,controller,jobs,social,ytdlp,components,views,publish,bin,testing}/*.test.ts\" \"{lib,controller,jobs,social,ytdlp,components,views,publish,bin,testing}/*/*.test.ts\" \"{lib,controller,jobs,publish,testing}/*/*/*.test.ts\" \"lib/*/*/*/*.test.ts\"" }, "dependencies": { "@aws-sdk/client-s3": "^3.1080.0", diff --git a/common/publish/build.test.ts b/common/publish/build.test.ts @@ -82,7 +82,8 @@ test("buildSiteSteps: data phase, compose, next build — all in export/, one en assert.deepEqual(steps, [ { command: "pnpm", args: ["run", "build:data"], cwd: "/repo/export", env }, { command: "pnpm", args: ["run", "compose:site"], cwd: "/repo/export", env }, - { command: "pnpm", args: ["exec", "next", "build"], cwd: "/repo/export", env }, + // Next's telemetry is off for every build. + { command: "pnpm", args: ["exec", "next", "build"], cwd: "/repo/export", env: { ...env, NEXT_TELEMETRY_DISABLED: "1" } }, ]); }); @@ -173,7 +174,7 @@ test("buildHubSteps: compose:hub, then next build with INSTANCE_MODE=hub, in exp command: "pnpm", args: ["exec", "next", "build"], cwd: "/repo/export", - env: { ...env, INSTANCE_MODE: "hub" }, + env: { ...env, INSTANCE_MODE: "hub", NEXT_TELEMETRY_DISABLED: "1" }, }, ]); }); diff --git a/common/publish/build.ts b/common/publish/build.ts @@ -111,7 +111,9 @@ export function buildSiteSteps(opts: { * it at a fake that copies the composed public dir to out/ (a real build there * would rebuild the app beside its running dev server). */ -export function nextBuildStep(paths: Paths, env: NodeJS.ProcessEnv): BuildStep { +export function nextBuildStep(paths: Paths, envIn: NodeJS.ProcessEnv): BuildStep { + // Next's usage telemetry is off for every build (the operator's rule: nothing about his work goes out). + const env: NodeJS.ProcessEnv = { ...envIn, NEXT_TELEMETRY_DISABLED: "1" }; const bin = env.EXPORT_NEXT_BIN?.trim(); return bin ? { command: bin, args: ["build"], cwd: paths.exportDir, env } @@ -752,7 +754,7 @@ export async function buildHomepage( opts.nextBuild ?? ((o: { env: NodeJS.ProcessEnv; onLog: (line: string) => void; signal: AbortSignal }) => runSteps(o.onLog, o.signal, [ - heavyGated(paths, { command: "pnpm", args: ["exec", "next", "build"], cwd: homepageDir(paths), env: o.env }), + heavyGated(paths, { command: "pnpm", args: ["exec", "next", "build"], cwd: homepageDir(paths), env: { ...o.env, NEXT_TELEMETRY_DISABLED: "1" } }), ])); const compose = opts.compose ?? ((o: { private: boolean }) => composeHomepage({ paths, onLog, signal, private: o.private })); if (opts.private) return buildPrivateHomepage(paths, onLog, signal, nextBuild, compose); diff --git a/common/social/playwrightRuntime.ts b/common/social/playwrightRuntime.ts @@ -16,6 +16,9 @@ // an editor server action), then resolve from the running process's directory, // then from the workspace packages that actually install it. +// ARCHILYZER_NO_NETWORK=1 (lib/noNetwork.mjs): imported for its effect — with the switch set, this +// process's outward doors refuse before any request. +import "../lib/noNetwork.mjs"; import { createRequire } from "node:module"; import path from "node:path"; import { pathToFileURL } from "node:url"; diff --git a/common/testing/README.md b/common/testing/README.md @@ -40,3 +40,32 @@ As committed at S0, the `paragraphs` manifest showed two owed bugs: the title ca the Coverage section became a bare chapter card. Release 27 S7 fixed both and regenerated the files: every title card has `foot: ""`, and a section with nothing to show (Coverage; `posts-only`'s Posts) gets no chapter card. + +## Jobs and the seeder + +| File | What it is | +| --- | --- | +| `jobs/quiesce.ts` | `quiesceJobs()` and `settleJob(id)` for a test that runs managed jobs over a temp corpus. A job's status reads `done` before it stops writing: its log and sidecar, and the report regeneration its end arms, about 1 s later (`channels/<slug>/snapshot.json`). `quiesceJobs` waits for all of it, firing a pending regeneration at once, before the test removes the corpus. `settleJob` waits for one job's end and sidecar. Their deadlines are backstops that throw naming what is still live. Import it as `yt-dlp-transcript-common/testing/jobs/quiesce.js`: TypeScript maps the `.js` to the `.ts` through the package's `exports`, tsx does the same, and `quiesce.ts` would need `allowImportingTsExtensions`. | +| `seeder/fixture.ts` | The seeder tests' tracker, synthetic playable torrent and WebTorrent clients (`seederFixture`, `newClient`, `destroyClient`, `until`), and `childExecArgv()`: this process's flags without the test runner's, a value written after a space included. | +| `seeder/webrtcScenario.ts` | The WebRTC seed-and-leech scenario as its own process. `controller/seeder.test.ts` runs it and reads its `RESULT`, `OPEN` and `STILL-ALIVE` lines. The child must report every tracker socket closed and exit by itself, or the parent kills it and fails saying what it last reported. | + +**A test file under a `[slug]` directory, run by path, runs nothing.** `tsx --test <path>` reads each path as a +glob, so `[slug]` is a character class: no file matches, 0 tests run, and the run exits 0. The package's own +`test` script is unaffected (its `app/**/*.test.ts` walks into the directory). For a few files by path, use +`pnpm test:files <package> <file>…` (`scripts/test-files.mjs`): it escapes the path and fails a run of 0 +tests. **No test reaches another host: `ARCHILYZER_NO_NETWORK=1`.** Every test script sets it (each package's +`test`, `pnpm test:scripts`, `pnpm test:files`) and preloads `common/lib/noNetwork.mjs` into every node process +the run starts, through `NODE_OPTIONS=--import=…`. Under it, any connection to a host that is not loopback +fails with `ENONETWORK` naming the door, and so does a yt-dlp, ffmpeg, gallery-dl or curl spawn aimed at one. A +browser gets a dead proxy. Loopback fakes keep working. **A test run by hand must export the same two:** + +```sh +ARCHILYZER_NO_NETWORK=1 NODE_OPTIONS="--import=$PWD/common/lib/noNetwork.mjs" tsx --test <file> # from the repo root +``` + +`ARCHILYZER_NO_NETWORK_LOG=<file>` writes one line per refusal, which finds a test whose code swallowed one. + +**Do not run a test file with a bare `tsx <file>` instead.** It runs, but outside the test runner +`NODE_TEST_CONTEXT` is unset, and guards keyed on it are off. Under it the Odysee player-page opener +(`ytdlp/storedUrlPageOpen.ts`) launches headless Chromium on odysee.com. The two stored-URL editor tests now +name an empty `E2E_ODYSEE_PAGE_FIXTURE`, which keeps it closed whichever way they run. diff --git a/common/testing/seeder/fixture.ts b/common/testing/seeder/fixture.ts @@ -54,3 +54,21 @@ export async function seederFixture(trackerUrl: (port: number) => string) { export function seederSettings(): SeederSettings { return { ...DEFAULT_SEEDER_SETTINGS, sites: ["demo-site"], maxConnections: 10 }; } + +// The flags a child of a test file should run with: this process's (the tsx +// loader), less the test runner's own — `--test-name-pattern=x` and +// `--test-name-pattern x` alike (the value too). The flags that take no value +// are named; every other `--test-*` written without `=` takes the next word. +const TEST_FLAGS_WITHOUT_VALUE = new Set(["--test", "--test-only", "--test-force-exit", "--test-update-snapshots"]); +export function childExecArgv(execArgv: readonly string[] = process.execArgv): string[] { + const out: string[] = []; + for (let i = 0; i < execArgv.length; i += 1) { + const a = execArgv[i]; + if (!a.startsWith("--test") && !a.startsWith("--experimental-test")) { + out.push(a); + continue; + } + if (!a.includes("=") && !TEST_FLAGS_WITHOUT_VALUE.has(a) && !a.startsWith("--experimental-test") && i + 1 < execArgv.length && !execArgv[i + 1].startsWith("-")) i += 1; + } + return out; +} diff --git a/common/ytdlp/runYtdlp.ts b/common/ytdlp/runYtdlp.ts @@ -1,3 +1,6 @@ +// ARCHILYZER_NO_NETWORK=1 (lib/noNetwork.mjs): imported for its effect — with the switch set, this +// process's outward doors refuse before any request. +import "../lib/noNetwork.mjs"; import { tierChannelMedia } from "../lib/mediaTier-server"; import path from "node:path"; import { mkdir, readdir, readFile } from "node:fs/promises"; diff --git a/common/ytdlp/storedUrlPageOpen.ts b/common/ytdlp/storedUrlPageOpen.ts @@ -13,6 +13,7 @@ // PAGE_OPEN_PLATFORMS. No cookies, a fresh context each time. import { importPlaywright } from "../social/playwrightRuntime"; +import { assertNetworkAllowed } from "../lib/noNetwork.mjs"; export const PAGE_OPEN_PLATFORMS: readonly string[] = ["odysee"]; @@ -58,6 +59,14 @@ export function abortableWait(ms: number, signal: AbortSignal): Promise<void> { // regardless (the CDN may serve it anyway). export const openPlayerPage: PageOpener = async ({ pageUrl, cdnHost, signal, onLog }) => { const mediaStatuses: number[] = []; + // ARCHILYZER_NO_NETWORK (lib/noNetwork.mjs), first and by name: set by every + // test harness, it holds however the test file was started. + try { + assertNetworkAllowed("the Odysee player-page opener", pageUrl); + } catch (e) { + onLog(`${(e as Error).message}\n`); + return { ok: false, mediaStatuses, error: (e as Error).message }; + } // NEVER A BROWSER UNDER A TEST RUNNER (release 32 R9). node's runner (and // tsx --test) sets NODE_TEST_CONTEXT in every test file's process: a test // that reaches the real opener — an editor route test running the whole cut — diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -5,12 +5,17 @@ The signal handlers used to go on only after the claim (the state file and the editor's lanes, held over HTTP), so a signal in that time killed the process with its hold and its lanes left for the heartbeat to find. Now the claim finishes, is released, and the process exits 128+signal; the take's work never starts. + - A second signal (Ctrl-C twice) waits for the first one's release instead of cutting it off, and the exit + code is the first signal's. - **umtool: `umtool queue wait` and `status` no longer call a step failed in the moment after it exits.** Between the step's exit and the runner writing its end, a reader saw "the step's process is gone", so `queue wait` could exit 1 on a step that then read done. A step whose runner is alive is running until that runner records its end; the runner's start time is now recorded on the step, so a reused pid is not taken for it. - The queue lock is no longer broken while another process is writing its pid into it (an empty lock file is - waited for; one empty for 5 s is a dead holder's). + waited for; one empty for 5 s is a dead holder's, and so is one whose time is 5 s ahead, after the clock was + stepped back). A lock file that cannot be read is waited for until the timeout, never spun on. + - A step whose end cannot be written (the lock's timeout) is retried twice. If it still fails, the runner lets + go of the step and its next turn marks it failed. Before, the step read running until the app restarted. - **Seeder: a scrape that fails no longer leaks a tracker client.** On an error or a warning, bittorrent-tracker's scrape left its client alive, sharing the WebSocket tracker's socket and reconnecting forever. Every outcome now destroys it, and a tracker that does not answer in 20 s is given up on for that poll. diff --git a/editor/app/api/media/fetch-window/route.remote.test.ts b/editor/app/api/media/fetch-window/route.remote.test.ts @@ -65,7 +65,7 @@ const { POST } = await import("./route"); // A job's end still writes after its status reads done (its sidecar, and the // report regeneration it arms — snapshot.json in the channel dir): waited for // before the corpus is removed (testing/jobs/quiesce.ts). -const { quiesceJobs, settleJob } = await import("../../../../../common/testing/jobs/quiesce"); +const { quiesceJobs, settleJob } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); test.after(async () => { await quiesceJobs(); await rm(ROOT, { recursive: true, force: true }); diff --git a/editor/app/api/media/fetch-window/route.storedUrl.test.ts b/editor/app/api/media/fetch-window/route.storedUrl.test.ts @@ -51,6 +51,12 @@ process.env.TRANSCRIPTS_DIR = ROOT; process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); process.env.YTDLP_BIN = YTDLP; process.env.FFMPEG_BIN = FFMPEG; +// NO BROWSER, HOWEVER THIS FILE IS RUN. The real player-page opener stays off +// under `node --test` (NODE_TEST_CONTEXT), but a bare `tsx <file>` sets no such +// thing, and this file's stored-URL cuts then opened odysee.com in headless +// Chromium. With a (empty) page fixture named, the opener opens nothing. +process.env.E2E_ODYSEE_PAGE_FIXTURE = path.join(ROOT, "odysee-pages.json"); +await writeFile(process.env.E2E_ODYSEE_PAGE_FIXTURE, "{}"); // The fallback's pause, as on the e2e server. process.env.E2E_CLIP_WINDOW_GAP_MS = "0"; await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ minFreeDiskGB: 0 })); @@ -80,7 +86,7 @@ await video("n1", false); const { POST } = await import("./route"); const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); -const { quiesceJobs, settleJob } = await import("../../../../../common/testing/jobs/quiesce"); +const { quiesceJobs, settleJob } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); // The jobs' ends still write after their status reads done — the sidecars, and // the report regeneration each end arms (snapshot.json in the channel dir): all // of it is waited for before the corpus is removed. diff --git a/editor/app/api/media/fetch-window/route.test.ts b/editor/app/api/media/fetch-window/route.test.ts @@ -27,7 +27,14 @@ await writeFile( JSON.stringify({ name: "Demo", handling: "youtube", url: "https://www.youtube.com/@demo" }), ); const { POST } = await import("./route"); -test.after(() => rm(ROOT, { recursive: true, force: true })); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); +test.after(async () => { + await quiesceJobs(); + await rm(ROOT, { recursive: true, force: true }); +}); function post(body: Record<string, unknown>): Promise<Response> { return POST( diff --git a/editor/app/api/ops/_frameScan.test.ts b/editor/app/api/ops/_frameScan.test.ts @@ -57,7 +57,12 @@ before(async () => { gen = sanitizeGeneration({ apiKeyFile: keyFile, anthropicBaseUrl: api.url, caps: { daily: 20, max: 10 } }); }); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); after(async () => { + await quiesceJobs(); await api.close(); await rm(tmp, { recursive: true, force: true }); }); diff --git a/editor/app/api/ops/_read.test.ts b/editor/app/api/ops/_read.test.ts @@ -23,7 +23,8 @@ await corpus.writeSettings({ kind: "remote", enabled: false, priority: 1, - remote: { baseUrl: "http://lan-box.local:3001", token: "never-printed" }, + // Loopback, a port nothing serves: the pool probes even a disabled remote, and a test asks no LAN host. + remote: { baseUrl: "http://127.0.0.1:9", token: "never-printed" }, }, ], }); diff --git a/editor/app/api/ops/attach-media/route.test.ts b/editor/app/api/ops/attach-media/route.test.ts @@ -19,7 +19,14 @@ process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); const { POST } = await import("./route"); const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); const { getPaths } = await import("yt-dlp-transcript-common/lib/paths"); -test.after(() => rm(ROOT, { recursive: true, force: true })); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs, settleJob } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); +test.after(async () => { + await quiesceJobs(); + await rm(ROOT, { recursive: true, force: true }); +}); const CH = path.join(ROOT, "channels"); await mkdir(path.join(CH, "tism", "data", "aaaaaaaaaaa"), { recursive: true }); @@ -76,11 +83,7 @@ test("a dry run is a job whose log classifies the archive and writes nothing", a const r = await post({ slug: "tism", source: ZIP, fillDates: true, dryRun: true }); assert.equal(r.status, 200, JSON.stringify(r.json)); assert.ok(r.json.jobId); - for (let i = 0; i < 100; i++) { - const status = getRegistry().get(r.json.jobId!)?.status; - if (status === "done" || status === "failed") break; - await new Promise((res) => setTimeout(res, 50)); - } + await settleJob(r.json.jobId!); assert.equal(getRegistry().get(r.json.jobId!)?.status, "done"); const log = await readFile(path.join(getPaths().jobsDir, `${r.json.jobId}.log`), "utf8"); const summary = JSON.parse(log.split("\n").find((l) => l.startsWith("summary: "))!.slice("summary: ".length)); diff --git a/editor/app/api/ops/browser-lookup/route.test.ts b/editor/app/api/ops/browser-lookup/route.test.ts @@ -58,7 +58,14 @@ await writeFile( const { POST } = await import("./route"); const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); -test.after(() => rm(ROOT, { recursive: true, force: true })); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs, settleJob } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); +test.after(async () => { + await quiesceJobs(); + await rm(ROOT, { recursive: true, force: true }); +}); function post(body: Record<string, unknown>): Promise<Response> { return POST( @@ -72,11 +79,7 @@ function post(body: Record<string, unknown>): Promise<Response> { async function settle(jobId: string): Promise<string | undefined> { const reg = getRegistry(); - for (let i = 0; i < 400; i++) { - const s = reg.get(jobId)?.status; - if (s !== "queued" && s !== "running") break; - await new Promise((res) => setTimeout(res, 50)); - } + await settleJob(jobId); return reg.get(jobId)?.status; } diff --git a/editor/app/api/ops/build-cues/route.test.ts b/editor/app/api/ops/build-cues/route.test.ts @@ -35,7 +35,14 @@ await video(path.join(corpus.transcripts, "channels", "other-yt", "data", "vid00 const { POST } = await import("./route"); const { GET } = await import("../transcript/route"); const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); -test.after(() => corpus.cleanup()); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs, settleJob } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); +test.after(async () => { + await quiesceJobs(); + await corpus.cleanup(); +}); const exists = (p: string) => stat(p).then(() => true, () => false); test("build-cues refusals: keys, ids, a stray id, a channel that does not exist", async () => { @@ -84,11 +91,7 @@ test("build-cues writes cues.json for the named ids only; transcript then reads const r = await callPost(POST, { slug: "demo-yt", ids: ["vid00000001"] }); assert.equal(r.status, 200, JSON.stringify(r.body)); const jobId = r.body.jobId as string; - for (let i = 0; i < 200; i++) { - const s = getRegistry().get(jobId)?.status; - if (s === "done" || s === "failed") break; - await new Promise((res) => setTimeout(res, 50)); - } + await settleJob(jobId); assert.equal(getRegistry().get(jobId)?.status, "done"); const cues = JSON.parse(await readFile(path.join(DATA, "vid00000001", "transcript.cues.json"), "utf8")); assert.equal(cues.cues.length, 2); diff --git a/editor/app/api/ops/evict-clips/route.test.ts b/editor/app/api/ops/evict-clips/route.test.ts @@ -27,16 +27,19 @@ await window("vid00000002", "10.00-40.00"); const { POST } = await import("./route"); const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); -test.after(() => corpus.cleanup()); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs, settleJob } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); +test.after(async () => { + await quiesceJobs(); + await corpus.cleanup(); +}); const exists = (p: string) => stat(p).then(() => true, () => false); const clip = (id: string, name: string) => path.join(DATA, id, "clips", name); async function settle(jobId: string): Promise<string | undefined> { - for (let i = 0; i < 200; i++) { - const s = getRegistry().get(jobId)?.status; - if (s === "done" || s === "failed") return s; - await new Promise((res) => setTimeout(res, 50)); - } + await settleJob(jobId); return getRegistry().get(jobId)?.status; } diff --git a/editor/app/api/ops/fetch-windows/route.test.ts b/editor/app/api/ops/fetch-windows/route.test.ts @@ -17,7 +17,14 @@ process.env.WORKER_TOKEN = "test-token"; process.env.TRANSCRIPTS_DIR = ROOT; process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); const { POST } = await import("./route"); -test.after(() => rm(ROOT, { recursive: true, force: true })); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); +test.after(async () => { + await quiesceJobs(); + await rm(ROOT, { recursive: true, force: true }); +}); // Channels on two platforms, one video each, the YouTube one with a window // already on disk. diff --git a/editor/app/api/ops/local-media-import/route.test.ts b/editor/app/api/ops/local-media-import/route.test.ts @@ -25,7 +25,14 @@ const routes = { "local-media-link": (await import("../local-media-link/route")).POST, }; const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); -test.after(() => rm(ROOT, { recursive: true, force: true })); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs, settleJob } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); +test.after(async () => { + await quiesceJobs(); + await rm(ROOT, { recursive: true, force: true }); +}); const CH = path.join(ROOT, "transcripts", "channels"); const LIB = path.join(ROOT, "library"); @@ -62,11 +69,7 @@ async function post(action: keyof typeof routes, body: Record<string, unknown>): return { status: res.status, json: (await res.json()) as Json }; } async function waitJob(id: string): Promise<string | undefined> { - for (let i = 0; i < 200; i++) { - const status = getRegistry().get(id)?.status; - if (status === "done" || status === "failed") return status; - await new Promise((res) => setTimeout(res, 50)); - } + await settleJob(id); return getRegistry().get(id)?.status; } diff --git a/editor/app/api/ops/prepare-playable/route.test.ts b/editor/app/api/ops/prepare-playable/route.test.ts @@ -17,7 +17,14 @@ process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); const { POST } = await import("./route"); const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); const { getPaths } = await import("yt-dlp-transcript-common/lib/paths"); -test.after(() => rm(ROOT, { recursive: true, force: true })); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs, settleJob } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); +test.after(async () => { + await quiesceJobs(); + await rm(ROOT, { recursive: true, force: true }); +}); await mkdir(path.join(ROOT, "channels", "tism", "data", "aaaaaaaaaaa"), { recursive: true }); await writeFile(path.join(ROOT, "channels", "tism", "config.json"), JSON.stringify({ handling: "youtube", name: "tism" })); @@ -54,11 +61,7 @@ test("refusals before any job", async () => { test("a dry run over a channel with no saved containers is a job that says so", async () => { const r = await post({ slug: "tism", dryRun: true, root: path.join(ROOT, "playable"), trackers: ["wss://tracker.example/announce"] }); assert.equal(r.status, 200, JSON.stringify(r.json)); - for (let i = 0; i < 100; i++) { - const s = getRegistry().get(r.json.jobId!)?.status; - if (s === "done" || s === "failed") break; - await new Promise((res) => setTimeout(res, 50)); - } + await settleJob(r.json.jobId!); assert.equal(getRegistry().get(r.json.jobId!)?.status, "done"); const log = await readFile(path.join(getPaths().jobsDir, `${r.json.jobId}.log`), "utf8"); assert.match(log, /0 video\(s\) with a saved container/); diff --git a/editor/app/api/ops/remote-listing/route.test.ts b/editor/app/api/ops/remote-listing/route.test.ts @@ -26,7 +26,14 @@ await mkdir(path.join(DATA, "imported-elsewhere"), { recursive: true }); const { POST } = await import("./route"); const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); const { getPaths } = await import("yt-dlp-transcript-common/lib/paths"); -test.after(() => corpus.cleanup()); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs, settleJob } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); +test.after(async () => { + await quiesceJobs(); + await corpus.cleanup(); +}); test("refusals before any job: keys, slug, channel, platform, url", async () => { const cases: [Record<string, unknown>, RegExp][] = [ @@ -49,11 +56,7 @@ test("a listing is a job whose last line is the diff against what is held", asyn const r = await callPost(POST, { slug: "demo-odysee" }); assert.equal(r.status, 200, JSON.stringify(r.body)); const jobId = r.body.jobId as string; - for (let i = 0; i < 200; i++) { - const s = getRegistry().get(jobId)?.status; - if (s === "done" || s === "failed") break; - await new Promise((res) => setTimeout(res, 50)); - } + await settleJob(jobId); const log = await readFile(path.join(getPaths().jobsDir, `${jobId}.log`), "utf8"); assert.equal(getRegistry().get(jobId)?.status, "done", log); const line = log.split("\n").find((l) => l.startsWith("@@remote-listing ")); diff --git a/editor/app/api/ops/transcribe-bucket/route.test.ts b/editor/app/api/ops/transcribe-bucket/route.test.ts @@ -36,7 +36,14 @@ await writeFile(path.join(dir, "audio.mp3"), Buffer.alloc(4096, 1)); const { POST } = await import("./route"); const { getRegistry, newJobId } = await import("yt-dlp-transcript-common/jobs/registry"); -test.after(() => corpus.cleanup()); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); +test.after(async () => { + await quiesceJobs(); + await corpus.cleanup(); +}); test("ids the stale report does not hold: the report is regenerated, and the job starts", async () => { const registry = getRegistry(); diff --git a/editor/app/api/ops/transcribe-one/route.test.ts b/editor/app/api/ops/transcribe-one/route.test.ts @@ -33,8 +33,13 @@ const POST = (await import("./route")).POST as Post; const { downloadVideoPipelineAction } = await import("../../../channels/[slug]/videos/[id]/videoActions"); const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); const { getWorkerPool } = await import("yt-dlp-transcript-common/jobs/workerPool"); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); test.after(async () => { getWorkerPool().resumeAll(); + await quiesceJobs(); await corpus.cleanup(); }); diff --git a/editor/app/channels/[slug]/videos/[id]/whisperFromContainer.test.ts b/editor/app/channels/[slug]/videos/[id]/whisperFromContainer.test.ts @@ -82,7 +82,14 @@ async function videoWith(id: string, container: string | null | undefined): Prom const { whisperVideoAction } = await import("./videoActions"); const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); -test.after(() => rm(ROOT, { recursive: true, force: true })); +// A job's end still writes after its status reads done (its log and sidecar, +// and the report regeneration it arms in the channel dir): waited for before +// the corpus is removed (testing/jobs/quiesce.ts). +const { quiesceJobs } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); +test.after(async () => { + await quiesceJobs(); + await rm(ROOT, { recursive: true, force: true }); +}); async function ytdlpCalls(): Promise<number> { return (await readFile(YTDLP_LOG, "utf8").catch(() => "")).split("\n").filter(Boolean).length; diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.test.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.test.ts @@ -68,7 +68,7 @@ await recordDownloadBackoff("youtube", getPaths()); // A job's end still writes after its status reads done (its sidecar, and the // report regeneration it arms — snapshot.json in the channel dir): waited for // before the corpus is removed (testing/jobs/quiesce.ts). -const { quiesceJobs, settleJob } = await import("../../../../../common/testing/jobs/quiesce"); +const { quiesceJobs, settleJob } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); test.after(async () => { await quiesceJobs(); await rm(ROOT, { recursive: true, force: true }); diff --git a/editor/app/channels/[slug]/videos/fetchWindowsStoredUrl.test.ts b/editor/app/channels/[slug]/videos/fetchWindowsStoredUrl.test.ts @@ -49,6 +49,12 @@ process.env.TRANSCRIPTS_DIR = ROOT; process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); process.env.YTDLP_BIN = YTDLP; process.env.FFMPEG_BIN = FFMPEG; +// NO BROWSER, HOWEVER THIS FILE IS RUN. The real player-page opener stays off +// under `node --test` (NODE_TEST_CONTEXT), but a bare `tsx <file>` sets no such +// thing, and this file's stored-URL cuts then opened odysee.com in headless +// Chromium. With a (empty) page fixture named, the opener opens nothing. +process.env.E2E_ODYSEE_PAGE_FIXTURE = path.join(ROOT, "odysee-pages.json"); +await writeFile(process.env.E2E_ODYSEE_PAGE_FIXTURE, "{}"); await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ minFreeDiskGB: 0 })); await mkdir(path.join(ROOT, "channels", SLUG), { recursive: true }); await writeFile( @@ -81,7 +87,7 @@ await recordDownloadBackoff("odysee", getPaths()); // A job's end still writes after its status reads done (its sidecar, and the // report regeneration it arms — snapshot.json in the channel dir): waited for // before the corpus is removed (testing/jobs/quiesce.ts). -const { quiesceJobs, settleJob } = await import("../../../../../common/testing/jobs/quiesce"); +const { quiesceJobs, settleJob } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); test.after(async () => { await quiesceJobs(); await rm(ROOT, { recursive: true, force: true }); diff --git a/editor/instrumentation.ts b/editor/instrumentation.ts @@ -19,6 +19,22 @@ export async function register() { // its transitive imports (runTick -> server actions, lmdb, fs) are Node-only, // so guard the import — and run nothing on Edge. if (process.env.NEXT_RUNTIME !== "nodejs") return; + // ARCHILYZER_NO_NETWORK (common/lib/noNetwork.mjs) is the test harness's switch. A server booted with it reaches + // no site at all, so it is said first and loudly: set by accident in a service unit, it must not pass for a + // normal boot. + try { + const { announceNoNetwork, noNetwork, installNoNetworkGuard } = await import("yt-dlp-transcript-common/lib/noNetwork.mjs"); + if (noNetwork()) { + // Once per process: the guard says it too when it installs, whichever comes first. + announceNoNetwork( + "editor: ARCHILYZER_NO_NETWORK=1 is set — this server refuses every non-loopback connection (no sync, download " + + "or fetch reaches a site). Unset it in the unit unless this is a test server.", + ); + installNoNetworkGuard(); + } + } catch (e) { + console.error(`editor: ARCHILYZER_NO_NETWORK check failed: ${e instanceof Error ? e.message : String(e)}`); + } // Anything a previous process left `queued` was queued before this instant. const bootedAt = Date.now(); diff --git a/editor/package.json b/editor/package.json @@ -4,12 +4,12 @@ "private": true, "type": "module", "scripts": { - "dev": "UV_THREADPOOL_SIZE=${UV_THREADPOOL_SIZE:-16} next dev --port ${EDITOR_PORT:-3001}", - "dev:test": "WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts EXPORT_PUBLIC_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.export-public SETTINGS_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-settings.json EDITOR_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-changelog.md EXPORT_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-export-changelog.md GENERATION_USAGE_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.generation-usage.jsonl YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs next dev --port ${PORT:-3011}", - "start:test": "WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts EXPORT_PUBLIC_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.export-public SETTINGS_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-settings.json EDITOR_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-changelog.md EXPORT_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-export-changelog.md GENERATION_USAGE_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.generation-usage.jsonl YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs next start --port ${PORT:-3011}", - "build": "next build", - "start": "UV_THREADPOOL_SIZE=${UV_THREADPOOL_SIZE:-16} next start --port ${EDITOR_PORT:-3001}", - "test": "tsx --test \"app/**/*.test.ts\" \"e2e/*.unit.ts\"", + "dev": "NEXT_TELEMETRY_DISABLED=1 UV_THREADPOOL_SIZE=${UV_THREADPOOL_SIZE:-16} next dev --port ${EDITOR_PORT:-3001}", + "dev:test": "NEXT_TELEMETRY_DISABLED=1 WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts EXPORT_PUBLIC_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.export-public SETTINGS_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-settings.json EDITOR_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-changelog.md EXPORT_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-export-changelog.md GENERATION_USAGE_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.generation-usage.jsonl YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs next dev --port ${PORT:-3011}", + "start:test": "NEXT_TELEMETRY_DISABLED=1 WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts EXPORT_PUBLIC_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.export-public SETTINGS_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-settings.json EDITOR_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-changelog.md EXPORT_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-export-changelog.md GENERATION_USAGE_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.generation-usage.jsonl YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs next start --port ${PORT:-3011}", + "build": "NEXT_TELEMETRY_DISABLED=1 next build", + "start": "NEXT_TELEMETRY_DISABLED=1 UV_THREADPOOL_SIZE=${UV_THREADPOOL_SIZE:-16} next start --port ${EDITOR_PORT:-3001}", + "test": "ARCHILYZER_NO_NETWORK=1 NODE_OPTIONS=\"--import=\\\"$PWD/../common/lib/noNetwork.mjs\\\" $NODE_OPTIONS\" tsx --test \"app/**/*.test.ts\" \"e2e/*.unit.ts\"", "e2e": "node ../scripts/queue-lock.mjs --name e2e-editor --with e2e-export --estimate 1500 --scale-by E2E_WORKERS --prebuild editor --ports PORT:3011,EXPORT_PORT:3010,OLLAMA_STUB_PORT:11435 -- playwright test", "e2e:ui": "playwright test --ui" }, diff --git a/export/package.json b/export/package.json @@ -4,7 +4,7 @@ "private": true, "type": "module", "scripts": { - "dev": "next dev --port ${EXPORT_DEV_PORT:-3000}", + "dev": "NEXT_TELEMETRY_DISABLED=1 next dev --port ${EXPORT_DEV_PORT:-3000}", "build:index": "NODE_OPTIONS=--max-old-space-size=8192 tsx ../common/bin/archilyzer.ts index", "build:stats": "NODE_OPTIONS=--max-old-space-size=8192 tsx ../common/bin/archilyzer.ts build stats", "build:templates": "tsx ../common/bin/archilyzer.ts build templates", @@ -16,7 +16,7 @@ "build:hub": "tsx ../common/bin/archilyzer.ts build hub", "start": "node scripts/serve-out.mjs out ${EXPORT_DEV_PORT:-3000}", "lint": "eslint", - "test": "tsx --test \"app/**/*.test.ts\"", + "test": "ARCHILYZER_NO_NETWORK=1 NODE_OPTIONS=\"--import=\\\"$PWD/../common/lib/noNetwork.mjs\\\" $NODE_OPTIONS\" tsx --test \"app/**/*.test.ts\"", "e2e": "node ../scripts/queue-lock.mjs --name e2e-export --estimate 1500 --ports EXPORT_E2E_PORT:3020 -- playwright test", "e2e:hub": "node ../scripts/queue-lock.mjs --name e2e-export --estimate 1500 --ports HUB_PORT:3041 -- playwright test --config playwright.hub.config.ts", "e2e:2origin": "node ../scripts/queue-lock.mjs --name e2e-export --estimate 1500 --ports ORIGIN_B_PORT:4610,HUB_A_PORT:4611 -- playwright test --config playwright.2origin.config.ts", diff --git a/homepage/package.json b/homepage/package.json @@ -4,17 +4,17 @@ "private": true, "type": "module", "scripts": { - "dev": "next dev --port ${HOMEPAGE_DEV_PORT:-3030}", + "dev": "NEXT_TELEMETRY_DISABLED=1 next dev --port ${HOMEPAGE_DEV_PORT:-3030}", "build:index": "NODE_OPTIONS=--max-old-space-size=8192 tsx ../common/bin/archilyzer.ts index", "compose": "tsx ../common/bin/archilyzer.ts compose homepage", "build:data": "pnpm run build:index && pnpm run compose", "prebuild": "pnpm run build:data", - "build": "next build", - "build:nodata": "next build", + "build": "NEXT_TELEMETRY_DISABLED=1 next build", + "build:nodata": "NEXT_TELEMETRY_DISABLED=1 next build", "start": "serve out -l ${HOMEPAGE_PORT:-3031}", "start:private": "serve out-private -l ${HOMEPAGE_PRIVATE_PORT:-3032}", "lint": "eslint", - "test": "tsx --test \"app/**/*.test.ts\"", + "test": "ARCHILYZER_NO_NETWORK=1 NODE_OPTIONS=\"--import=\\\"$PWD/../common/lib/noNetwork.mjs\\\" $NODE_OPTIONS\" tsx --test \"app/**/*.test.ts\"", "e2e": "node ../scripts/queue-lock.mjs --name e2e-homepage --estimate 1500 --ports HOMEPAGE_E2E_PORT:3040 -- playwright test", "e2e:ui": "playwright test --ui", "deploy": "tsx ../common/bin/archilyzer.ts deploy homepage" diff --git a/mcp/package.json b/mcp/package.json @@ -14,7 +14,7 @@ }, "scripts": { "start": "tsx src/index.ts", - "test": "tsx --test src/*.test.ts", + "test": "ARCHILYZER_NO_NETWORK=1 NODE_OPTIONS=\"--import=\\\"$PWD/../common/lib/noNetwork.mjs\\\" $NODE_OPTIONS\" tsx --test src/*.test.ts", "typecheck": "tsc --noEmit -p tsconfig.json", "bench": "tsx bench/bench.ts", "smoke": "tsx bench/smoke.ts" diff --git a/package.json b/package.json @@ -24,7 +24,8 @@ "wt": "node scripts/worktree.mjs", "e2e:sharded": "node scripts/run-sharded-e2e.mjs", "e2e:all": "node scripts/e2e-all.mjs", - "test:scripts": "node --test scripts/*.test.mjs umtool/report-to-video/*.test.mjs umtool/report-to-video/modules/*.test.mjs umtool/lib/*.test.mjs umtool/lib/report/*.test.mjs umtool/lib/annotations/*.test.mjs umtool/lib/articles/*.test.mjs umtool/lib/pieces/*.test.mjs umtool/lib/inbox/*.test.mjs umtool/lib/research/*.test.mjs umtool/lib/work/*.test.mjs umtool/lib/create/*.test.mjs umtool/lib/settings/*.test.mjs umtool/lib/queue/*.test.mjs umtool/lib/ingredients/*.test.mjs umtool/lib/cli/*.test.mjs", + "test:files": "node scripts/test-files.mjs", + "test:scripts": "ARCHILYZER_NO_NETWORK=1 NODE_OPTIONS=\"--import=\\\"$PWD/common/lib/noNetwork.mjs\\\" $NODE_OPTIONS\" node --test scripts/*.test.mjs umtool/report-to-video/*.test.mjs umtool/report-to-video/modules/*.test.mjs umtool/lib/*.test.mjs umtool/lib/report/*.test.mjs umtool/lib/annotations/*.test.mjs umtool/lib/articles/*.test.mjs umtool/lib/pieces/*.test.mjs umtool/lib/inbox/*.test.mjs umtool/lib/research/*.test.mjs umtool/lib/work/*.test.mjs umtool/lib/create/*.test.mjs umtool/lib/settings/*.test.mjs umtool/lib/queue/*.test.mjs umtool/lib/ingredients/*.test.mjs umtool/lib/cli/*.test.mjs", "test": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 run test; a=$?; pnpm run test:scripts; b=$?; [ $a -eq 0 ] && [ $b -eq 0 ]", "typecheck": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 exec tsc --noEmit", "lint": "pnpm --filter export run lint", diff --git a/scripts/e2e-stamp.mjs b/scripts/e2e-stamp.mjs @@ -285,7 +285,7 @@ export function buildPackage(name, { root = REPO_ROOT, log = (l) => process.stde const r = spawnSync(cmd[0], cmd.slice(1), { cwd: root, stdio: "inherit", - env: { ...process.env, [spec.distEnv]: spec.distDir }, + env: { ...process.env, [spec.distEnv]: spec.distDir, NEXT_TELEMETRY_DISABLED: "1" }, }); const secs = Math.round((Date.now() - t0) / 1000); if (r.status !== 0) { diff --git a/scripts/test-files.mjs b/scripts/test-files.mjs @@ -0,0 +1,64 @@ +#!/usr/bin/env node +// Run some test files of a package by path — and fail when none ran. +// +// node scripts/test-files.mjs <package dir> <file> [<file>…] +// pnpm test:files editor "app/channels/[slug]/videos/fetchWindowsAction.test.ts" +// +// `tsx --test <path>` (node's test runner) reads each path as a GLOB, so a +// Next route directory like `[slug]` is a character class: the file matches +// nothing, 0 tests run, and it exits 0 — a green run that tested nothing. Here +// a path that names a file is escaped to match only itself, and a run whose +// summary says 0 tests is a failure. It runs under ARCHILYZER_NO_NETWORK=1, as +// every test script does. +import { spawn } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); + +/** A path written so node's test-runner glob matches exactly that file. */ +export function literalGlob(p) { + return p.replace(/[[*?{}()+@]/g, (c) => `[${c}]`); +} + +/** The top-level `# tests N` of a TAP run, or null when there is none. */ +export function testsRan(tap) { + const all = [...tap.matchAll(/^# tests (\d+)$/gm)]; + return all.length ? Number(all.at(-1)[1]) : null; +} + +async function main(argv) { + const [pkg, ...files] = argv; + if (!pkg || files.length === 0) { + process.stderr.write("usage: node scripts/test-files.mjs <package dir> <test file> [<test file>…]\n"); + return 2; + } + const cwd = path.resolve(ROOT, pkg); + const args = files.map((f) => (fs.existsSync(path.resolve(cwd, f)) ? literalGlob(f) : f)); + const tsx = path.join(ROOT, "node_modules", ".bin", "tsx"); + // The test harness's switch (common/lib/noNetwork.mjs): nothing the run starts reaches another host. + const env = { + ...process.env, + ARCHILYZER_NO_NETWORK: "1", + // A file URL: a checkout path with spaces needs no quoting. + NODE_OPTIONS: `--import=${pathToFileURL(path.join(ROOT, "common", "lib", "noNetwork.mjs")).href} ${process.env.NODE_OPTIONS ?? ""}`.trim(), + }; + const child = spawn(tsx, ["--test", ...args], { cwd, env, stdio: ["ignore", "pipe", "inherit"] }); + let out = ""; + child.stdout.on("data", (d) => { + out += d; + process.stdout.write(d); + }); + const code = await new Promise((r) => child.on("close", (c) => r(c ?? 1))); + const ran = testsRan(out); + if (code === 0 && !ran) { + process.stderr.write(`test-files: no test ran (${ran === null ? "no summary" : "0 tests"}) — check the paths: ${files.join(" ")}\n`); + return 1; + } + return code; +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + process.exit(await main(process.argv.slice(2))); +} diff --git a/scripts/test-files.test.mjs b/scripts/test-files.test.mjs @@ -0,0 +1,17 @@ +// scripts/test-files.mjs: a test file named by a path with glob characters +// ([slug]) runs, and a run of nothing fails. Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; +import { literalGlob, testsRan } from "./test-files.mjs"; + +test("a Next route path is escaped to match only itself", () => { + assert.equal(literalGlob("app/channels/[slug]/videos/a.test.ts"), "app/channels/[[]slug]/videos/a.test.ts"); + assert.equal(literalGlob("app/(group)/x?.test.ts"), "app/[(]group[)]/x[?].test.ts"); + assert.equal(literalGlob("lib/plain.test.ts"), "lib/plain.test.ts"); +}); + +test("the run's own summary is what counts, and 0 is no run", () => { + assert.equal(testsRan("TAP version 13\n# tests 0\n# pass 0\n"), 0); + assert.equal(testsRan("ok 1 - x\n # tests 9\n# tests 4\n# pass 4\n"), 4); + assert.equal(testsRan("nothing here"), null); +}); diff --git a/umtool/instrumentation.ts b/umtool/instrumentation.ts @@ -13,6 +13,22 @@ import { isIdleBoot } from "yt-dlp-transcript-common/lib/idleBoot"; export async function register() { if (process.env.NEXT_RUNTIME !== "nodejs") return; + // ARCHILYZER_NO_NETWORK (common/lib/noNetwork.mjs) is the test harness's switch. A server booted with it reaches + // no site at all, so it is said first and loudly: set by accident in a service unit, it must not pass for a + // normal boot. + try { + const { announceNoNetwork, noNetwork, installNoNetworkGuard } = await import("yt-dlp-transcript-common/lib/noNetwork.mjs"); + if (noNetwork()) { + // Once per process: the guard says it too when it installs, whichever comes first. + announceNoNetwork( + "umtool: ARCHILYZER_NO_NETWORK=1 is set — this server refuses every non-loopback connection (no sync, download " + + "or fetch reaches a site). Unset it in the unit unless this is a test server.", + ); + installNoNetworkGuard(); + } + } catch (e) { + console.error(`umtool: ARCHILYZER_NO_NETWORK check failed: ${e instanceof Error ? e.message : String(e)}`); + } // ONE UNDO STACK (umtool redesign L3): every edit made in the app is its own undo point (lib/report/manifest.mjs // autoSnapshot; a terminal keeps the two-minute throttle). A process global, not the environment: the steps // the app spawns (lib/jobs.ts) must keep the terminal's throttle. Set before anything else, idle boot included. diff --git a/umtool/lib/queue/store.mjs b/umtool/lib/queue/store.mjs @@ -115,19 +115,36 @@ export async function withQueueLock(dir, fn, { timeoutMs = 15_000 } = {}) { break; } catch (err) { if (/** @type {NodeJS.ErrnoException} */ (err).code !== "EEXIST") throw err; - const text = await readFile(/* turbopackIgnore: true */ file, "utf8").catch(() => null); - if (text === null) continue; // released meanwhile: try again - const [pid, host, at] = text.trim().split(" "); + /** @type {NodeJS.ErrnoException | null} */ + let readError = null; + const text = await readFile(/* turbopackIgnore: true */ file, "utf8").catch((e) => { + if (e?.code === "ENOENT") return null; + readError = e; + return null; + }); + if (text === null && !readError) continue; // released meanwhile: try again + // A lock that cannot be read (EACCES, EIO…) is waited for up to the + // deadline like a held one — never spun on, never broken. + const [pid, host, at] = (text ?? "").trim().split(" "); // An EMPTY lock is one another process has created and not yet written // its pid into (open, then write): it was broken at once, and both held - // the lock. It is a dead holder's only once it has stayed empty a while. - const emptyFor = text ? 0 : await stat(/* turbopackIgnore: true */ file).then((st) => Date.now() - st.mtimeMs, () => 0); - const stale = (host === os.hostname() && !processAlive(Number(pid))) || (Number(at) > 0 && Date.now() - Number(at) > 30_000) || emptyFor > 5_000; + // the lock. It is a dead holder's only once it has stayed empty a while — + // either way: an mtime in the future is a clock stepped back. + const emptyFor = text === "" ? await stat(/* turbopackIgnore: true */ file).then((st) => Date.now() - st.mtimeMs, () => 0) : 0; + const stale = + text !== null && + ((host === os.hostname() && !processAlive(Number(pid))) || (Number(at) > 0 && Date.now() - Number(at) > 30_000) || Math.abs(emptyFor) > 5_000); if (stale) { await unlink(file).catch(() => {}); continue; } - if (Date.now() > deadline) throw new Error(`the queue is locked by pid ${pid} (${file})`); + if (Date.now() > deadline) { + throw new Error( + readError + ? `the queue lock cannot be read (${/** @type {NodeJS.ErrnoException} */ (readError).code ?? readError}) (${file})` + : `the queue is locked by pid ${pid} (${file})`, + ); + } await sleep(25 + Math.random() * 50); } } @@ -483,7 +500,9 @@ export async function releaseLease(dir, { pid = process.pid } = {}) { * @param {{ busy: () => string | null, start: (step: any, o: { logFile: string, onEnd: (end: any) => void }) => { pid: number | null, jobId?: string | null, cancel: () => void }, * describe?: (step: any) => Promise<string | null> }} exec * @param {{ held: Map<string, any>, now?: () => Date, runnerPid?: number, alive?: (pid: number, start?: number | null) => boolean, - * onChange?: () => void }} state + * onChange?: () => void, + * endWrite?: { tries?: number, pauseMs?: number, before?: (qid: string, attempt: number) => void | Promise<void> } }} state + * `endWrite`: how recording a step's end is retried (`before`, a test's fault, runs ahead of each try) * @returns {Promise<{ started: string | null, recovered: string[], blocked: string[], waiting: string | null }>} */ export async function queueTick(dir, exec, state) { @@ -545,12 +564,11 @@ export async function queueTick(dir, exec, state) { started = exec.start(step, { logFile, onEnd: (end) => { - void finishStep(dir, step.qid, end, exec, state).catch(() => {}); + void recordEnd(dir, step.qid, end, exec, state).catch(() => {}); }, }); } catch (e) { - state.held.delete(step.qid); - await finishStep(dir, step.qid, { exitCode: null, error: e instanceof Error ? e.message : String(e) }, exec, state, { notStarted: true }); + await recordEnd(dir, step.qid, { exitCode: null, error: e instanceof Error ? e.message : String(e) }, exec, state, { notStarted: true }).catch(() => {}); return out; } handle.cancel = started.cancel; @@ -593,8 +611,36 @@ async function finishStep(dir, qid, end, exec, state, { notStarted = false } = { await putStep(dir, s); if (r.state !== "done") await blockDependents(dir, s); }); - state.held.delete(qid); - state.onChange?.(); +} + +export const END_WRITE_TRIES = 3; +export const END_WRITE_PAUSE_MS = 2_000; + +/** + * Record a step's end (finishStep), a few times if writing it fails (the queue + * lock's timeout on a loaded machine) — and, whatever happens, let go of the + * step: a step this runner no longer holds and whose process is gone is the + * runner's own recovery's to mark failed on its next turn. It used to stay + * held when the write threw, reading running until the app restarted. + */ +async function recordEnd(dir, qid, end, exec, state, opts = {}) { + const tries = state.endWrite?.tries ?? END_WRITE_TRIES; + const pauseMs = state.endWrite?.pauseMs ?? END_WRITE_PAUSE_MS; + try { + for (let attempt = 1; ; attempt += 1) { + try { + await state.endWrite?.before?.(qid, attempt); + await finishStep(dir, qid, end, exec, state, opts); + return; + } catch (e) { + if (attempt >= tries) throw e; + await sleep(pauseMs); + } + } + } finally { + state.held.delete(qid); + state.onChange?.(); + } } /** diff --git a/umtool/lib/queue/store.test.mjs b/umtool/lib/queue/store.test.mjs @@ -291,6 +291,56 @@ test("the queue lock: an empty lock file is one being written, not a dead holder } }); +test("recording a step's end is retried; one that cannot be recorded is let go, and the runner's recovery fails it", async () => { + const dir = await tmp(); + try { + // Fails once (the lock's timeout on a loaded machine), then records: done. + const a = await addStep(dir, { argv: js("0"), label: "once" }); + const tries = []; + const once = { held: new Map(), endWrite: { tries: 3, pauseMs: 10, before: (qid, n) => { tries.push(n); if (n === 1) throw new Error("the queue is locked"); } } }; + const steps = await drain(dir, spawnExec(), once); + assert.equal(steps.find((s) => s.qid === a.qid)?.state, "done"); + assert.deepEqual(tries, [1, 2]); + assert.equal(once.held.size, 0); + + // Never records: let go after the tries, and the next turn's recovery + // marks it failed — it does not read running until the app restarts. + const b = await addStep(dir, { argv: js("0"), label: "never" }); + const c = await addStep(dir, { argv: js("0"), label: "after it" }); + const never = { held: new Map(), endWrite: { tries: 2, pauseMs: 10, before: () => { throw new Error("the queue is locked"); } } }; + const after = await drain(dir, spawnExec(), never); + const bb = after.find((s) => s.qid === b.qid); + assert.equal(bb?.state, "failed"); + assert.match(bb?.error ?? "", /process is gone/); + assert.equal(after.find((s) => s.qid === c.qid)?.state, "failed", "it too: every end write fails"); + assert.equal(never.held.size, 0); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("the queue lock: an unreadable lock is waited for to the deadline, not spun on; an empty one from the future is stale", async () => { + const dir = await tmp(); + try { + await withQueueLock(dir, async () => {}); // makes the dirs + const lock = path.join(dir, ".lock"); + // A directory where the lock file should be: open(wx) says EEXIST, read says EISDIR. + const { mkdir, utimes } = await import("node:fs/promises"); + await mkdir(lock); + const t0 = Date.now(); + await assert.rejects(withQueueLock(dir, async () => "mine", { timeoutMs: 300 }), /the queue lock cannot be read \(EISDIR\)/); + assert.ok(Date.now() - t0 >= 300, "waited to the deadline"); + await rm(lock, { recursive: true }); + // Empty, its mtime an hour ahead: the clock was stepped back. Broken. + await writeFile(lock, ""); + const ahead = new Date(Date.now() + 3_600_000); + await utimes(lock, ahead, ahead); + assert.equal(await withQueueLock(dir, async () => "mine", { timeoutMs: 300 }), "mine"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + test("the lease: one runner per queue dir; a dead holder's lease is taken", async () => { const dir = await tmp(); try { diff --git a/umtool/lib/report/renderMode.mjs b/umtool/lib/report/renderMode.mjs @@ -111,23 +111,28 @@ export async function withRenderHold(o, fn) { const lanes = o.lanes !== undefined ? o.lanes : editorLanes(editorConfig(env)); /** @type {string | null} the claimed hold's token, once the claim is in */ let token = null; - let ended = false; /** @type {NodeJS.Signals | null} */ let signalled = null; - const end = async () => { - if (ended || token === null) return; - ended = true; - if (env[RENDER_PRIORITY_TOKEN_ENV] === token) delete env[RENDER_PRIORITY_TOKEN_ENV]; - try { - const off = await renderModeOff({ file, token, lanes }); - o.log( - `render mode off${off.released.length ? ` — lanes released: ${off.released.join(", ")}` : ""}` + - (off.failed.length ? `; NOT released: ${off.failed.map((f) => `${f.lane} (${f.error})`).join(", ")} — the editor releases them when it next looks` : ""), - ); - } catch (e) { - o.log(`render mode: could not end it (${e instanceof Error ? e.message : String(e)}) — it ends by itself, this process being gone`); - } - }; + // ONE RELEASE, AWAITED BY EVERY CALLER. A second signal (Ctrl-C twice, a + // runner's TERM then its group's) used to find `ended` set, return at once + // and exit — cutting off the first caller's release of the lanes mid-way. + /** @type {Promise<void> | null} */ + let ending = null; + const end = () => + (ending ??= (async () => { + if (token === null) return; + const t = token; + if (env[RENDER_PRIORITY_TOKEN_ENV] === t) delete env[RENDER_PRIORITY_TOKEN_ENV]; + try { + const off = await renderModeOff({ file, token: t, lanes }); + o.log( + `render mode off${off.released.length ? ` — lanes released: ${off.released.join(", ")}` : ""}` + + (off.failed.length ? `; NOT released: ${off.failed.map((f) => `${f.lane} (${f.error})`).join(", ")} — the editor releases them when it next looks` : ""), + ); + } catch (e) { + o.log(`render mode: could not end it (${e instanceof Error ? e.message : String(e)}) — it ends by itself, this process being gone`); + } + })()); // A signal ends the hold before this process goes (the job runner's Cancel // signals the group; Ctrl-C the same). Then exit as the signal would. // @@ -144,8 +149,9 @@ export async function withRenderHold(o, fn) { if (o.signals !== false) { for (const sig of /** @type {NodeJS.Signals[]} */ (["SIGINT", "SIGTERM", "SIGHUP"])) { const h = () => { - const code = 128 + ({ SIGINT: 2, SIGTERM: 15, SIGHUP: 1 }[sig] ?? 0); signalled ??= sig; + // The FIRST signal's code, whichever handler's exit runs. + const code = 128 + ({ SIGINT: 2, SIGTERM: 15, SIGHUP: 1 }[signalled] ?? 0); try { o.onSignal?.(sig); } catch { @@ -197,8 +203,9 @@ export async function withRenderHold(o, fn) { try { return { ran: true, value: await fn(/** @type {string} */ (token)) }; } finally { - unhook(); + // Unhooked only once the release is done: a signal meanwhile joins it. await end(); + unhook(); } } diff --git a/umtool/lib/report/renderMode.test.mjs b/umtool/lib/report/renderMode.test.mjs @@ -86,7 +86,7 @@ test("take --priority: a failed take lets go too", async () => { * signal sent then lands mid-claim. The child is killed whatever the test does * (`stop`), so a failed assertion cannot leave it holding the runner open. */ -function spawnTake({ slowLane = null } = {}) { +function spawnTake({ slowLane = null, slowRelease = null } = {}) { const dir = mkdtempSync(path.join(tmpdir(), "render-mode-sig-")); const file = path.join(dir, "state.json"); const log = path.join(dir, "lanes.log"); @@ -96,6 +96,7 @@ function spawnTake({ slowLane = null } = {}) { `import { appendFileSync } from "node:fs"; import { withTakePriority } from ${JSON.stringify(path.join(HERE, "renderMode.mjs"))}; const slow = ${JSON.stringify(slowLane)}; +const slowRelease = ${JSON.stringify(slowRelease)}; const lanes = { isHeld: async () => false, hold: async (l) => { @@ -105,7 +106,13 @@ const lanes = { await new Promise((r) => setTimeout(r, 400)); } }, - release: async (l) => appendFileSync(${JSON.stringify(log)}, "release " + l + "\\n"), + release: async (l) => { + if (l === slowRelease) { + console.log("releasing " + l); + await new Promise((r) => setTimeout(r, 400)); + } + appendFileSync(${JSON.stringify(log)}, "release " + l + "\\n"); + }, }; await withTakePriority({ priority: true, project: "p", take: "t", log: (l) => console.log(l), env: {}, file: ${JSON.stringify(file)}, lanes }, async () => { console.log("rendering"); @@ -158,6 +165,25 @@ test("take --priority killed by a signal: the hold ends before the process does" } }); +test("take --priority signalled twice: the second signal waits for the first's release, and the exit is the first's", { timeout: 180_000 }, async () => { + // The second signal used to find the release begun, return at once and + // exit — mid-way through letting the lanes go. + const take = spawnTake({ slowRelease: "download" }); + try { + await take.waitFor(/rendering/); + take.child.kill("SIGTERM"); + await take.waitFor(/releasing download/); + take.child.kill("SIGINT"); + const { code, signal } = await take.exited; + assert.equal(code, 143, `exited ${code ?? signal}: ${take.out()}`); + assert.equal(existsSync(take.file), false, "the state file is gone"); + assert.equal(readFileSync(take.log, "utf8"), "hold transcription\nhold download\nhold backfill\nrelease transcription\nrelease download\nrelease backfill\n"); + assert.equal(take.out().match(/render mode off/g)?.length, 1, `released once: ${take.out()}`); + } finally { + await take.stop(); + } +}); + test("take --priority signalled while it claims: the claim finishes, is let go, and the take never starts", { timeout: 180_000 }, async () => { // The window the old order left open: the handlers went on only after the // claim, so a signal while the lanes were being held killed the process diff --git a/umtool/package.json b/umtool/package.json @@ -4,11 +4,11 @@ "private": true, "type": "module", "scripts": { - "dev": "next dev --port ${UMTOOL_PORT:-3050}", - "build": "next build", - "start": "next start --port ${UMTOOL_PORT:-3050}", + "dev": "NEXT_TELEMETRY_DISABLED=1 next dev --port ${UMTOOL_PORT:-3050}", + "build": "NEXT_TELEMETRY_DISABLED=1 next build", + "start": "NEXT_TELEMETRY_DISABLED=1 next start --port ${UMTOOL_PORT:-3050}", "typecheck": "tsc --noEmit", - "test": "tsx --test lib/brandIcon.test.ts lib/privacy.test.ts lib/articles/*.test.ts lib/research/*.test.ts lib/inbox/*.test.ts lib/clips/*.test.ts components/projects/bench/*.test.ts", + "test": "ARCHILYZER_NO_NETWORK=1 NODE_OPTIONS=\"--import=\\\"$PWD/../common/lib/noNetwork.mjs\\\" $NODE_OPTIONS\" tsx --test lib/brandIcon.test.ts lib/privacy.test.ts lib/articles/*.test.ts lib/research/*.test.ts lib/inbox/*.test.ts lib/clips/*.test.ts components/projects/bench/*.test.ts", "e2e": "node ../scripts/worktree.mjs run -- node ../scripts/queue-lock.mjs --name e2e-umtool --estimate 1500 --prebuild umtool --ports UMTOOL_E2E_PORT:3051,EDITOR_STUB_PORT:3052 -- playwright test" }, "dependencies": { diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -3155,10 +3155,10 @@ export async function analysisAudioSource(clip, audio, meta, render, local, opts /** The analysis page measured (chrome-analysis.mjs `?measure`): its sentences, empty when it fits. */ export async function measureAnalysisPage(projDir, render) { - const { rendererEnv } = await import("./compose-chrome.mjs"); + const { CHROME_QUIET_FLAGS, rendererEnv } = await import("./compose-chrome.mjs"); const { measuredProblems } = await import("./chrome-analysis.mjs"); const { stdout } = await execFileP(process.env.CHROME ?? "/usr/bin/chromium", [ - "--headless", "--disable-gpu", "--no-sandbox", "--hide-scrollbars", `--window-size=${render.width},${render.height}`, + "--headless", "--disable-gpu", "--no-sandbox", "--hide-scrollbars", ...CHROME_QUIET_FLAGS, `--window-size=${render.width},${render.height}`, "--virtual-time-budget=8000", "--dump-dom", `file://${path.join(projDir, "index.html")}?measure=1`, ], { maxBuffer: 1 << 26, env: rendererEnv() }); const problems = measuredProblems(stdout); diff --git a/umtool/report-to-video/compose-chrome.mjs b/umtool/report-to-video/compose-chrome.mjs @@ -40,7 +40,7 @@ import { dateKey } from "./ledger-totals.mjs"; import { makeLinker } from "./link-or-copy.mjs"; import { selectVariant } from "./build-video.mjs"; import { ensureWriteDir } from "../lib/report/storage.mjs"; -import { chromeCacheKey, frameCount, pageDuration, hyperframesCommand, sha256, transitionOf } from "./deck.mjs"; +import { chromeCacheKey, frameCount, pageDuration, hyperframesCommand, RENDERER_OPT_OUTS, sha256, transitionOf } from "./deck.mjs"; import { GSAP_FILE } from "./chrome-deck.mjs"; import { anonymiseManifest } from "./post-anon.mjs"; import { projectAnonymousSet } from "./project-characters-file.mjs"; @@ -51,6 +51,7 @@ import { poolFor, poolFrame, poolFrameEvents, poolPutFrames } from "./render-poo import { regionCaching, regionModule } from "./modules/index.mjs"; import { stackedDeckWanted, verticalRender } from "./vertical.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; +import { withPreload } from "yt-dlp-transcript-common/lib/noNetwork.mjs"; const run = promisify(execFile); @@ -788,14 +789,130 @@ async function framesOnDisk(dir) { * SwiftShader tries to connect to it, fails, and every render dies with * "assertSwiftShader ... vendor=''". */ -export function rendererEnv(env = process.env) { +export function rendererEnv(env = process.env, { guarded = true, refusalLog = null } = {}) { const { DISPLAY: _d, WAYLAND_DISPLAY: _w, ...rest } = env; - return rest; + // And always the opt-outs (deck.mjs RENDERER_OPT_OUTS): no telemetry, no + // update notice, no auto-install. + const out = { ...rest, ...RENDERER_OPT_OUTS }; + // OUTWARD CONNECTIONS REFUSED, IN THE CHILD ONLY (common/lib/noNetwork.mjs). + // The CLI's own flags do not stop it asking: at start it checks the npm + // registry for a newer version and raw.githubusercontent.com for its skills + // (fire-and-forget, once a day). So the renderer, npx and everything they start + // run with the guard preloaded: loopback only, and the browser gets a proxy + // that does not answer, so local pages still load. This process is not guarded. + if (guarded) { + out.ARCHILYZER_NO_NETWORK = "1"; + out.NODE_OPTIONS = withPreload(rest.NODE_OPTIONS); + if (refusalLog) out.ARCHILYZER_NO_NETWORK_LOG = refusalLog; + } else { + delete out.ARCHILYZER_NO_NETWORK; + delete out.ARCHILYZER_NO_NETWORK_LOG; + } + return out; +} + +/** + * Flags for a headless Chromium this pipeline starts itself (the review still, + * the analysis page's measure): no background networking, component updates, + * pings, metrics upload, sync or crash reports. (Playwright's launches set + * these by default.) + */ +export const CHROME_QUIET_FLAGS = Object.freeze([ + "--disable-background-networking", + "--disable-component-update", + "--disable-domain-reliability", + "--disable-sync", + "--disable-breakpad", + "--metrics-recording-only", + "--no-pings", + "--no-first-run", + "--disable-default-apps", +]); + +/** Run the renderer, its chatter to stderr (stdout may be a build's NDJSON), with `env` (rendererEnv's). */ +export function runRenderer(cmd, args, env = rendererEnv()) { + return runRendererOnce(cmd, args, env); +} + +/** + * The one DOWNLOAD a guarded first run needs, from a failed run's output: the + * pinned package missing from the npm cache, or the renderer's browser not + * downloaded yet. `null` for any other failure (it is the render's own). + * @returns {{ what: string, from: string, args: string[] } | null} + */ +export function firstRunDownload(hf, message) { + if (hf.fallbackArgs && /ENOTCACHED/.test(message)) { + // `--help`: the CLI skips its update and skills checks for it. + return { kind: "package", what: hf.version, from: "the npm registry (registry.npmjs.org)", args: [...hf.fallbackArgs, "--help"] }; + } + if (/Failed to download chrome-headless-shell/.test(message)) { + // `--json` anywhere in the argv: the CLI skips its update and skills checks. + return { kind: "browser", what: "the renderer's browser (chrome-headless-shell)", from: "Chrome for Testing (storage.googleapis.com)", args: [...hf.args, "browser", "ensure", "--json"] }; + } + return null; +} + +/** The hosts a refusal log names, counted. */ +async function refusedHosts(file) { + const text = await readFile(file, "utf8").catch(() => ""); + const hosts = new Map(); + for (const line of text.split("\n").filter(Boolean)) { + try { + const { target } = JSON.parse(line); + const host = /^[a-z]+:\/\//i.test(target) ? new URL(target).hostname : String(target).replace(/:\d+$/, "").replace(/^spawning \S+ for /, ""); + hosts.set(host, (hosts.get(host) ?? 0) + 1); + } catch { + /* a line cut short */ + } + } + return hosts; +} + +/** + * A HyperFrames CLI run, guarded (rendererEnv): loopback only, its refusals + * logged in `<workDir>/.renderer-refused.jsonl` and said as a NOTE after the + * run — evidence, never an error (the CLI's update and skills checks are + * fire-and-forget, and a refused one changes nothing in the render). + * + * FIRST RUN: when the guarded run fails because something must be DOWNLOADED + * (firstRunDownload), that one step runs unguarded, after a line naming what is + * fetched and from where. Then the render is run guarded again. Each download + * happens at most once per call. + * @param {{ cmd: string, args: string[], fallbackArgs?: string[], version: string }} hf + * @param {string[]} cliArgs the CLI's own arguments; the last is the project dir + * @param {{ workDir?: string }} [opts] + */ +export async function runHyperframes(hf, cliArgs, { workDir = cliArgs.at(-1) } = {}) { + const refusalLog = path.join(String(workDir), ".renderer-refused.jsonl"); + await rm(refusalLog, { force: true }); + const fetched = new Set(); + for (;;) { + try { + await runRendererOnce(hf.cmd, [...hf.args, ...cliArgs], rendererEnv(process.env, { refusalLog })); + break; + } catch (e) { + const step = firstRunDownload(hf, String(e?.message)); + if (!step || fetched.has(step.kind)) throw e; + fetched.add(step.kind); + process.stderr.write( + `umtool: first run — fetching ${step.what} from ${step.from}; this one step runs with outward connections allowed, the render after it does not\n`, + ); + await runRendererOnce(hf.cmd, step.args, rendererEnv(process.env, { guarded: false })); + } + } + const hosts = await refusedHosts(refusalLog); + if (hosts.size) { + const n = [...hosts.values()].reduce((a, b) => a + b, 0); + process.stderr.write( + `umtool: note — ${n} outward request${n === 1 ? "" : "s"} from the renderer refused: ${[...hosts.keys()].join(", ")} (it runs with loopback only; ${path.basename(refusalLog)} has them)\n`, + ); + } + return { refused: hosts }; } -export function runRenderer(cmd, args) { +function runRendererOnce(cmd, args, env) { return new Promise((resolve, reject) => { - const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"], env: rendererEnv() }); + const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"], env }); let tail = ""; const keep = (b) => { process.stderr.write(b); @@ -977,7 +1094,7 @@ export async function composeChrome({ const out = path.resolve(png ?? path.join(projDir, `still-${fmtSeconds(Number(still))}.png`)); await mkdir(path.dirname(out), { recursive: true }); await run(CHROME, [ - "--headless", "--disable-gpu", "--no-sandbox", "--hide-scrollbars", + "--headless", "--disable-gpu", "--no-sandbox", "--hide-scrollbars", ...CHROME_QUIET_FLAGS, "--default-background-color=00000000", `--window-size=${size.width},${size.height}`, "--virtual-time-budget=6000", @@ -1048,8 +1165,8 @@ export async function composeChrome({ await rm(target, { recursive: true, force: true }); } - await withWorkers(frames ?? 0, (w) => runRenderer(hf.cmd, [ - ...hf.args, "render", + await withWorkers(frames ?? 0, (w) => runHyperframes(hf, [ + "render", "--format", format, "--quality", quality, "--fps", String(rate), ...(w != null ? ["-w", String(w)] : []), @@ -1240,8 +1357,8 @@ async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf await writeFile(path.join(capProj, "index.html"), page, "utf8"); await writeFile(path.join(capProj, "hyperframes.json"), HF_JSON + "\n", "utf8"); await rm(capDir, { recursive: true, force: true }); - await withWorkers(capture.length, (w) => runRenderer(hf.cmd, [ - ...hf.args, "render", "--format", "png-sequence", "--quality", quality, "--fps", String(rate), + await withWorkers(capture.length, (w) => runHyperframes(hf, [ + "render", "--format", "png-sequence", "--quality", quality, "--fps", String(rate), ...(w != null ? ["-w", String(w)] : []), "--no-browser-gpu", "--output", capDir, capProj, ])); const got = await framesOnDisk(capDir); diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -3870,13 +3870,32 @@ export const pageDuration = (seconds, fps) => /** * How to invoke HyperFrames. `HYPERFRAMES_BIN` (an executable taking the CLI's - * own arguments, e.g. an e2e stub) wins; else `npx --yes <HYPERFRAMES_PKG>`, + * own arguments, e.g. an e2e stub) wins; else npx of `<HYPERFRAMES_PKG>`, * pinned by default. `version` is what the cache key records. + * + * NOTHING ASKED OF THE NPM REGISTRY ON A NORMAL RENDER (the operator's rule: + * nothing about his work goes to outside services). `npx --yes <pkg>` asked the + * registry on every run. The pinned package runs from the npm cache + * (`--offline`). Only when it is not there does the renderer run + * `fallbackArgs` (`--prefer-offline`), saying first that it asks the registry + * once and why (compose-chrome.mjs runRenderer). */ export function hyperframesCommand(env = process.env) { if (env.HYPERFRAMES_BIN) { return { cmd: env.HYPERFRAMES_BIN, args: [], version: `bin:${env.HYPERFRAMES_BIN}` }; } const pkg = env.HYPERFRAMES_PKG ?? HYPERFRAMES_PKG_DEFAULT; - return { cmd: "npx", args: ["--yes", pkg], version: pkg }; + return { cmd: "npx", args: ["--offline", "--yes", pkg], fallbackArgs: ["--prefer-offline", "--yes", pkg], version: pkg }; } + +/** + * The renderer's opt-outs, set on every HyperFrames run (rendererEnv): no + * usage telemetry (PostHog), no update check, no installing of anything by + * itself. The Docker image has set DO_NOT_TRACK all along; a host render did not. + */ +export const RENDERER_OPT_OUTS = Object.freeze({ + DO_NOT_TRACK: "1", + HYPERFRAMES_NO_TELEMETRY: "1", + HYPERFRAMES_NO_UPDATE_CHECK: "1", + HYPERFRAMES_NO_AUTO_INSTALL: "1", +}); diff --git a/umtool/report-to-video/deck.test.mjs b/umtool/report-to-video/deck.test.mjs @@ -238,7 +238,13 @@ test("chromeCacheKey is stable and sensitive", () => { }); test("hyperframesCommand: pinned by default, overridable", () => { - assert.deepEqual(hyperframesCommand({}), { cmd: "npx", args: ["--yes", HYPERFRAMES_PKG_DEFAULT], version: HYPERFRAMES_PKG_DEFAULT }); + // From the npm cache; the registry only as the logged fallback (renderer-env.test.mjs). + assert.deepEqual(hyperframesCommand({}), { + cmd: "npx", + args: ["--offline", "--yes", HYPERFRAMES_PKG_DEFAULT], + fallbackArgs: ["--prefer-offline", "--yes", HYPERFRAMES_PKG_DEFAULT], + version: HYPERFRAMES_PKG_DEFAULT, + }); assert.equal(hyperframesCommand({ HYPERFRAMES_PKG: "hyperframes@1.0.0" }).version, "hyperframes@1.0.0"); assert.deepEqual(hyperframesCommand({ HYPERFRAMES_BIN: "/stub" }), { cmd: "/stub", args: [], version: "bin:/stub" }); }); diff --git a/umtool/report-to-video/intro.mjs b/umtool/report-to-video/intro.mjs @@ -483,15 +483,15 @@ export async function renderIntro({ entry, render, encode, manifestDir = process await rm(proj, { recursive: true, force: true }); await rm(framesDir, { recursive: true, force: true }); await mkdir(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ proj, "assets"), { recursive: true }); - const { HF_JSON, runRenderer } = await import("./compose-chrome.mjs"); + const { HF_JSON, runHyperframes } = await import("./compose-chrome.mjs"); const { GSAP_FILE } = await import("./chrome-deck.mjs"); await copyFile(/* turbopackIgnore: true */ GSAP_FILE, path.join(/* turbopackIgnore: true */ proj, "assets", "gsap.min.js")); // The words' face, when the page draws words (introHtml links it only then). if (entry.title || entry.lines?.length) await copyFile(/* turbopackIgnore: true */ INTRO_FONT_FILE, path.join(/* turbopackIgnore: true */ proj, INTRO_FONT_ASSET)); await writeFile(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ proj, "index.html"), html, "utf8"); await writeFile(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ proj, "hyperframes.json"), HF_JSON + "\n", "utf8"); - await runRenderer(hf.cmd, [ - ...hf.args, "render", "--format", "png-sequence", "--quality", "high", "--fps", String(fps), + await runHyperframes(hf, [ + "render", "--format", "png-sequence", "--quality", "high", "--fps", String(fps), "-w", String(workers), "--no-browser-gpu", "--output", framesDir, proj, ]); const got = (await readdir(/* turbopackIgnore: true */ framesDir).catch(() => [])).filter((f) => /^frame_\d+\.png$/.test(f)).length; diff --git a/umtool/report-to-video/renderer-env.test.mjs b/umtool/report-to-video/renderer-env.test.mjs @@ -0,0 +1,182 @@ +// The renderer asks no outside service (the operator's rule). Every HyperFrames +// run happens in a child with outward connections refused (common/lib/noNetwork.mjs +// preloaded), plus the opt-outs. Its refusals are a NOTE, never an error. A +// first run's one download (the package, the browser) happens unguarded, once, +// and is said first. The parent process is never guarded. +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { CHROME_QUIET_FLAGS, firstRunDownload, rendererEnv, runHyperframes } from "./compose-chrome.mjs"; +import { HYPERFRAMES_PKG_DEFAULT, hyperframesCommand, RENDERER_OPT_OUTS } from "./deck.mjs"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const OPT_OUTS = { DO_NOT_TRACK: "1", HYPERFRAMES_NO_TELEMETRY: "1", HYPERFRAMES_NO_UPDATE_CHECK: "1", HYPERFRAMES_NO_AUTO_INSTALL: "1" }; +const OUT = "192.0.2.1"; // TEST-NET-1: nothing answers there + +test("rendererEnv: the opt-outs always, no display, and the child guarded (switch and preload) unless asked not to be", () => { + assert.deepEqual({ ...RENDERER_OPT_OUTS }, OPT_OUTS); + const env = rendererEnv({ PATH: "/bin", DISPLAY: ":0", WAYLAND_DISPLAY: "w", DO_NOT_TRACK: "0", NODE_OPTIONS: "--max-old-space-size=100" }, { refusalLog: "/w/r.jsonl" }); + assert.equal(env.DISPLAY, undefined); + assert.equal(env.WAYLAND_DISPLAY, undefined); + for (const [k, v] of Object.entries(OPT_OUTS)) assert.equal(env[k], v, k); + assert.equal(env.ARCHILYZER_NO_NETWORK, "1"); + assert.match(env.NODE_OPTIONS, /^--import=file:\/\/.*\/common\/lib\/noNetwork\.mjs --max-old-space-size=100$/); + assert.equal(env.ARCHILYZER_NO_NETWORK_LOG, "/w/r.jsonl"); + const open = rendererEnv({ PATH: "/bin", ARCHILYZER_NO_NETWORK: "1", ARCHILYZER_NO_NETWORK_LOG: "/x" }, { guarded: false }); + assert.deepEqual(open, { PATH: "/bin", ...OPT_OUTS }); +}); + +test("hyperframesCommand: npx from the cache (--offline); --prefer-offline only for a first run's download", () => { + assert.deepEqual(hyperframesCommand({}), { + cmd: "npx", + args: ["--offline", "--yes", HYPERFRAMES_PKG_DEFAULT], + fallbackArgs: ["--prefer-offline", "--yes", HYPERFRAMES_PKG_DEFAULT], + version: HYPERFRAMES_PKG_DEFAULT, + }); + assert.deepEqual(hyperframesCommand({ HYPERFRAMES_BIN: "/x/hf" }), { cmd: "/x/hf", args: [], version: "bin:/x/hf" }); +}); + +test("firstRunDownload: only the package missing from the cache, or the browser not downloaded — each a quiet one-off step", () => { + const hf = hyperframesCommand({}); + assert.deepEqual(firstRunDownload(hf, "npm error code ENOTCACHED")?.args, ["--prefer-offline", "--yes", HYPERFRAMES_PKG_DEFAULT, "--help"]); + assert.deepEqual(firstRunDownload(hf, "Error: Failed to download chrome-headless-shell 1.2.3: …")?.args, ["--offline", "--yes", HYPERFRAMES_PKG_DEFAULT, "browser", "ensure", "--json"]); + assert.equal(firstRunDownload(hf, "render failed: a frame timed out"), null); + assert.equal(firstRunDownload(hf, `ARCHILYZER_NO_NETWORK=1: a connection refused (registry.npmjs.org:443)`), null, "a refused update check is not a download"); +}); + +test("the headless Chromium the pipeline starts itself is told to stay quiet", () => { + for (const f of ["--disable-background-networking", "--disable-component-update", "--no-pings", "--metrics-recording-only", "--disable-sync", "--disable-breakpad"]) { + assert.ok(CHROME_QUIET_FLAGS.includes(f), f); + } +}); + +/** A HyperFrames stand-in (a node script, so the preload reaches it): records its argv and env, then does `body`. */ +async function stub(dir, body) { + const seen = path.join(dir, "seen.jsonl"); + const file = path.join(dir, "fake-hf.mjs"); + await writeFile( + file, + `#!/usr/bin/env node +import { appendFileSync } from "node:fs"; +import net from "node:net"; +const args = process.argv.slice(2); +const pick = (k) => process.env[k] ?? null; +appendFileSync(${JSON.stringify(seen)}, JSON.stringify({ args, env: { ARCHILYZER_NO_NETWORK: pick("ARCHILYZER_NO_NETWORK"), NODE_OPTIONS: pick("NODE_OPTIONS"), DO_NOT_TRACK: pick("DO_NOT_TRACK"), HYPERFRAMES_NO_TELEMETRY: pick("HYPERFRAMES_NO_TELEMETRY"), HYPERFRAMES_NO_UPDATE_CHECK: pick("HYPERFRAMES_NO_UPDATE_CHECK"), HYPERFRAMES_NO_AUTO_INSTALL: pick("HYPERFRAMES_NO_AUTO_INSTALL") }, guarded: net.Socket.prototype.connect.name === "guardedConnect" }) + "\\n"); +${body} +`, + ); + await chmod(file, 0o755); + return { file, runs: async () => (await readFile(seen, "utf8")).trim().split("\n").map((l) => JSON.parse(l)) }; +} + +async function captureStderr(fn) { + const said = []; + const write = process.stderr.write.bind(process.stderr); + process.stderr.write = (chunk, ...rest) => { + said.push(String(chunk)); + return write(chunk, ...rest); + }; + try { + return { value: await fn(), said: said.join("") }; + } finally { + process.stderr.write = write; + } +} + +test("runHyperframes: the child is guarded; its outward requests (an update check) are refused, the render succeeds, and a NOTE names them", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "renderer-env-")); + try { + const proj = path.join(dir, "proj"); + await mkdir(proj); + // What the CLI does at start: a fire-and-forget check of another host, its failure ignored; then it renders. + const s = await stub(dir, `const c = net.connect(443, ${JSON.stringify(OUT)}); c.on("error", () => {}); setTimeout(() => process.exit(0), 300);`); + const hf = { cmd: s.file, args: [], version: "bin:stub" }; + const { value, said } = await captureStderr(() => runHyperframes(hf, ["render", "--output", path.join(dir, "frames"), proj])); + const [run] = await s.runs(); + assert.equal(run.guarded, true, "the guard is installed in the child"); + assert.equal(run.env.ARCHILYZER_NO_NETWORK, "1"); + assert.match(run.env.NODE_OPTIONS, /noNetwork\.mjs/); + for (const [k, v] of Object.entries(OPT_OUTS)) assert.equal(run.env[k], v, k); + assert.deepEqual([...value.refused.keys()], [OUT]); + assert.match(said, /note — 1 outward request from the renderer refused: 192\.0\.2\.1/); + assert.match(await readFile(path.join(proj, ".renderer-refused.jsonl"), "utf8"), /192\.0\.2\.1:443/); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("runHyperframes, first run: the package missing from the npm cache is fetched once, unguarded and said, then the render runs guarded", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "renderer-env-")); + try { + const proj = path.join(dir, "proj"); + await mkdir(proj); + const flag = path.join(dir, "cached"); + // --offline with an empty cache answers ENOTCACHED, as npm does; the --prefer-offline step "caches" it. + const s = await stub(dir, `import { existsSync, writeFileSync } from "node:fs"; +if (args[0] === "--prefer-offline") { writeFileSync(${JSON.stringify(flag)}, ""); process.exit(0); } +if (!existsSync(${JSON.stringify(flag)})) { process.stderr.write("npm error code ENOTCACHED\\n"); process.exit(1); }`); + const hf = { ...hyperframesCommand({}), cmd: s.file }; + const { said } = await captureStderr(() => runHyperframes(hf, ["render", proj])); + const runs = await s.runs(); + assert.deepEqual(runs.map((r) => r.args[0]), ["--offline", "--prefer-offline", "--offline"]); + assert.deepEqual(runs[1].args.slice(-1), ["--help"], "the one-off step skips the CLI's checks"); + assert.match(said, /first run — fetching hyperframes@[\d.]+ from the npm registry \(registry\.npmjs\.org\); this one step runs with outward connections allowed/); + assert.equal(said.match(/first run —/g).length, 1); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("runHyperframes, first run: the browser not downloaded is fetched once (browser ensure), then the render; a second failure is the render's", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "renderer-env-")); + try { + const proj = path.join(dir, "proj"); + await mkdir(proj); + // Always missing: the step runs once, the retry fails the same way, and that failure is the render's. + const s = await stub(dir, `if (args.includes("ensure")) process.exit(0); +process.stderr.write("Error: Failed to download chrome-headless-shell 1.2.3: ARCHILYZER_NO_NETWORK=1: a connection refused (storage.googleapis.com:443)\\n"); process.exit(1);`); + const hf = { ...hyperframesCommand({}), cmd: s.file }; + const { value } = await captureStderr(() => runHyperframes(hf, ["render", proj]).then(() => "ok", (e) => e)); + assert.match(String(value?.message), /Failed to download chrome-headless-shell/); + const runs = await s.runs(); + assert.deepEqual(runs.map((r) => r.args.slice(3).join(" ")), ["render " + proj, "browser ensure --json", "render " + proj]); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("the parent is never guarded: a process with the switch unset renders, and its own connections are its own", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "renderer-env-")); + try { + const proj = path.join(dir, "proj"); + await mkdir(proj); + const s = await stub(dir, `process.exit(0);`); + const probe = ` + import http from "node:http"; + import net from "node:net"; + const { runHyperframes } = await import(${JSON.stringify(path.join(HERE, "compose-chrome.mjs"))}); + await runHyperframes({ cmd: ${JSON.stringify(s.file)}, args: [], version: "bin:stub" }, ["render", ${JSON.stringify(proj)}]); + const srv = http.createServer((q, r) => r.end("ok")); + await new Promise((r) => srv.listen(0, "127.0.0.1", r)); + const body = await (await fetch("http://127.0.0.1:" + srv.address().port + "/")).text(); + srv.close(); + // An outward connect is not refused here (it is left pending at TEST-NET-1 and dropped). + const c = net.connect(443, ${JSON.stringify(OUT)}); + const outcome = await new Promise((r) => { c.on("error", (e) => r(e.code)); setTimeout(() => r("not refused"), 300); }); + c.destroy(); + console.log(JSON.stringify({ body, outcome, guarded: net.Socket.prototype.connect.name === "guardedConnect" }));`; + // Through env(1): this test file runs under the harness's switch, which a child would otherwise inherit. + const r = spawnSync("env", ["-u", "ARCHILYZER_NO_NETWORK", "-u", "NODE_OPTIONS", process.execPath, "--input-type=module", "-e", probe], { encoding: "utf8" }); + assert.equal(r.status, 0, r.stderr); + assert.deepEqual(JSON.parse(r.stdout.trim().split("\n").at(-1)), { body: "ok", outcome: "not refused", guarded: false }); + const [run] = await s.runs(); + assert.equal(run.guarded, true, "while its renderer child is guarded"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/report-to-video/threads.test.mjs b/umtool/report-to-video/threads.test.mjs @@ -201,5 +201,9 @@ test("railLayout: cards share the height, capped, the stack centred", () => { test("the renderer runs without a display: a stale DISPLAY would break SwiftShader", async () => { const { rendererEnv } = await import("./compose-chrome.mjs"); const env = rendererEnv({ DISPLAY: ":0.0", WAYLAND_DISPLAY: "wayland-0", PATH: "/usr/bin", HOME: "/h" }); - assert.deepEqual(env, { PATH: "/usr/bin", HOME: "/h" }); + assert.equal(env.DISPLAY, undefined); + assert.equal(env.WAYLAND_DISPLAY, undefined); + assert.equal(env.PATH, "/usr/bin"); + assert.equal(env.HOME, "/h"); + // (And the opt-outs and the no-network guard for the child: renderer-env.test.mjs.) });