commit d02a49d1496fb4ba1e2eafec1daa45e22fcbd5ab parent 4790929909c26334e7c8c9766d0504c10f29e583 Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Sat, 14 Nov 2026 09:09:28 -0500 No-network review fixes, and the renderer and builds stop sending anything out The guard (common/lib/noNetwork.mjs), for each bypass in review 2's probe; every probe is now refused or passes as it should: - M1 spawn/spawnSync/execFile… with `shell: true` is read as a shell command line, as exec is. - M2 a child given its own environment (`env: {}`) gets the switch, the preload (merged into its NODE_OPTIONS), npm_config_offline and the telemetry opt-outs put back. - The process's own NODE_OPTIONS carries the preload too, once the guard installs. - M3 worker threads: worker_threads.Worker is wrapped so every worker, eval or file, runs the guard first. - L1 new doors, each judged only in a command position: - git's network subcommands, by URL or user@host:path (revisions such as `<sha>:path` pass). - ssh/sftp/mosh by their destination; scp/rsync by host:path. - gh always (but --version/--help); pip/uv/pipx/bun/cargo/go when they install; python when its args name a URL. - npm, pnpm and npx run offline. - L2 ffmpeg/ffprobe are judged by their inputs (-i, concat:) and output only. A -metadata comment, a drawtext or -headers for a local input pass. - L3 dgram send reads the address by argument position: a connected socket's string message is not a host. - L4 a loopback NAME's lookup is checked: a custom lookup or hosts entry mapping it elsewhere is refused. - L7 installed outside a test run (no NODE_TEST_CONTEXT, no preload), it says so on stderr. The editor's and umtool's instrumentation say it again at boot. - L8 the preload path is quoted in every package script, and test:files uses a file URL, so a path with spaces works. - The header lists the known limits: unix sockets, native WebRTC/addon sockets, dns.resolve*, processes this one did not start. - Tests: lib/noNetwork.test.ts covers each item (22 tests). - Its unset and outside-a-test-run probes reach their child through env(1). A guarded process now puts the switch back into any child's own environment. Privacy (the operator's rule: nothing about his work goes to outside services): - HyperFrames: - rendererEnv() always sets DO_NOT_TRACK, HYPERFRAMES_NO_TELEMETRY, HYPERFRAMES_NO_UPDATE_CHECK and HYPERFRAMES_NO_AUTO_INSTALL (deck.mjs RENDERER_OPT_OUTS). That is every HyperFrames run: compose-chrome's two renders and the intro's, now through runHyperframes. - npx runs the pinned package from the cache (--offline). Only on ENOTCACHED does it run once with --prefer-offline, after a line saying it asks the registry and why. - Tested in renderer-env.test.mjs; deck.test and threads.test are updated. - Chromium: the two headless runs the pipeline starts itself (the review still, the analysis measure) get CHROME_QUIET_FLAGS: no background networking, component updates, pings, metrics, sync or breakpad. Playwright's launches set those already. - Next.js telemetry is off (NEXT_TELEMETRY_DISABLED=1) for every app's dev/build/start script, the publish stages' site, hub and homepage builds, and the e2e builds (scripts/e2e-stamp.mjs). The service units already set it. - OPERATING.md has a new section, "What renders and builds send out: nothing". It says what is off and that `hyperframes telemetry disable` does the same for by-hand CLI use. Co-Authored-By: Claude <noreply@anthropic.com> Diffstat:
24 files changed, 644 insertions(+), 82 deletions(-)
diff --git a/OPERATING.md b/OPERATING.md @@ -1251,6 +1251,22 @@ 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 `DO_NOT_TRACK=1`, `HYPERFRAMES_NO_TELEMETRY=1`, + `HYPERFRAMES_NO_UPDATE_CHECK=1` and `HYPERFRAMES_NO_AUTO_INSTALL=1`. That means no PostHog telemetry, no update + check and no installing of its own. It runs from the npm cache (`npx --offline`). Only when the pinned package is + not in the cache does it ask the npm registry, once, with a line in the render's log saying so. +- **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. + +For HyperFrames run by hand on the host, `hyperframes telemetry disable` does the same once. + ## Publish ```sh diff --git a/common/lib/noNetwork.d.mts b/common/lib/noNetwork.d.mts @@ -11,3 +11,6 @@ export class NoNetworkError extends Error { 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>; diff --git a/common/lib/noNetwork.mjs b/common/lib/noNetwork.mjs @@ -13,30 +13,52 @@ // 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 (yt-dlp, gallery-dl, ffmpeg, curl, -// wget, streamlink, a browser…) spawned with a non-loopback URL in its -// command line is refused (the spawn throws). A browser is always given a -// proxy that does not answer: anything it asks of another host fails, while -// loopback and file:// pages still load. Playwright reaches its browser this -// way too. A tool named differently, such as a test's `fake-ytdlp.mjs`, is -// not refused. +// - 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. +// 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 --import …/noNetwork.mjs`), and the door modules -// import it too, so a test run is covered however it is started. +// 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"; @@ -111,7 +133,19 @@ export function assertNetworkAllowed(door, url, env = process.env) { // --- 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|ffmpeg|ffprobe|ffplay|curl|wget|streamlink|aria2c|rclone|wrangler|nitter|twitch-dl)(\.(exe|py|sh))?$/; +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; @@ -142,42 +176,119 @@ const WRAPPERS = /^(xvfb-run|env|nice|ionice|timeout|setsid|stdbuf|nohup|systemd const SHELLS = /^(sh|bash|dash|zsh|ash|ksh)$/; /** - * The words of a command line that are COMMANDS — the executable, what a - * wrapper runs, the first word of a shell string and of each of its pipeline - * stages — each with 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. + * 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 }>} + * @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 && (/^\w+=/.test(toks[i]) || WRAPPERS.test(base(toks[i])) || /^-/.test(toks[i]) || /^\d+[smhd]?$/.test(toks[i]))) i += 1; - if (toks[i]) out.push({ word: toks[i], at: -1 }); + 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); - out.push({ word: w, at: i }); 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 && (/^-/.test(words[i]) || /^\w+=/.test(words[i]) || /^\d+[smhd]?$/.test(words[i]))) 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. @@ -187,13 +298,15 @@ function commandWords(words) { export function guardSpawn(file, args) { const words = [String(file), ...args.map(String)]; const commands = commandWords(words); - const urls = outwardUrls(words); - const tool = commands.find((c) => NETWORK_TOOLS.test(base(c.word))); - if (tool && urls.length) return { refuse: `spawning ${base(tool.word)} for ${urls[0]}` }; + 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. @@ -203,6 +316,12 @@ export function guardSpawn(file, args) { 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; @@ -210,6 +329,56 @@ function splitArgs(argList) { 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. @@ -232,9 +401,11 @@ function keepCustomPromisify(guarded, orig, check) { function wrapFileStyle(orig, name) { const check = (argList) => { const [file, args, rest] = splitArgs(argList); - const g = guardSpawn(String(file), args); + 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, g.args, ...rest]; + return [file, opts?.shell ? args : g.args, ...guardOptions(rest)]; }; const guarded = function guarded(...argList) { return orig.apply(this, check(argList)); @@ -245,9 +416,9 @@ function wrapFileStyle(orig, name) { function wrapShellStyle(orig, name) { const check = (argList) => { // exec runs its command line in /bin/sh: read as the shell would. - const g = guardSpawn("sh", ["-c", String(argList[0])]); + const g = guardShell(argList[0]); if ("refuse" in g) throw new NoNetworkError(`child_process.${name} (${caller()})`, g.refuse); - return argList; + return [argList[0], ...guardOptions(argList.slice(1))]; }; const guarded = function guarded(...argList) { return orig.apply(this, check(argList)); @@ -255,6 +426,31 @@ function wrapShellStyle(orig, name) { 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. */ @@ -270,19 +466,54 @@ function connectHost(args) { 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; /** 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 && workerThreads.isMainThread) { + process.stderr.write(`${NO_NETWORK_ENV}=1: this process refuses every non-loopback connection\n`); + } // 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). Children inherit this environment. + // (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); @@ -292,13 +523,27 @@ export function installNoNetworkGuard() { 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 strings = args.filter((x) => typeof x === "string"); - const address = strings.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)); @@ -322,9 +567,11 @@ export function installNoNetworkGuard() { for (const name of ["exec", "execSync"]) { childProcess[name] = wrapShellStyle(childProcess[name], name); } - // ESM named imports of node:child_process are live bindings of the CJS - // exports: this makes `import { spawn } from "node:child_process"`, done - // anywhere, before or after, see the guarded functions. + 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(); } diff --git a/common/lib/noNetwork.test.ts b/common/lib/noNetwork.test.ts @@ -166,22 +166,127 @@ test("named doors: assertNetworkAllowed refuses another host and passes loopback 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 env: Record<string, string | undefined> = { ...process.env }; - delete env.ARCHILYZER_NO_NETWORK; - delete env.NODE_OPTIONS; 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 }));`; - const out = execFileSync(process.execPath, ["--input-type=module", "-e", probe], { env: env as NodeJS.ProcessEnv, encoding: "utf8" }); + // 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(process.execPath, ["--input-type=module", "-e", probe.replace(/const r = [^;]+;/, "const r = { status: 0 };")], { env: { ...env, ARCHILYZER_NO_NETWORK: "1" } as NodeJS.ProcessEnv, encoding: "utf8" }); + 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 { diff --git a/common/package.json b/common/package.json @@ -86,7 +86,7 @@ "./testing/*": "./testing/*" }, "scripts": { - "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\"" + "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/editor/instrumentation.ts b/editor/instrumentation.ts @@ -19,6 +19,21 @@ 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 { noNetwork, installNoNetworkGuard } = await import("yt-dlp-transcript-common/lib/noNetwork.mjs"); + if (noNetwork()) { + console.error( + "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": "ARCHILYZER_NO_NETWORK=1 NODE_OPTIONS=\"--import=$PWD/../common/lib/noNetwork.mjs $NODE_OPTIONS\" 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": "ARCHILYZER_NO_NETWORK=1 NODE_OPTIONS=\"--import=$PWD/../common/lib/noNetwork.mjs $NODE_OPTIONS\" 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": "ARCHILYZER_NO_NETWORK=1 NODE_OPTIONS=\"--import=$PWD/../common/lib/noNetwork.mjs $NODE_OPTIONS\" 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": "ARCHILYZER_NO_NETWORK=1 NODE_OPTIONS=\"--import=$PWD/../common/lib/noNetwork.mjs $NODE_OPTIONS\" 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 @@ -25,7 +25,7 @@ "e2e:sharded": "node scripts/run-sharded-e2e.mjs", "e2e:all": "node scripts/e2e-all.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: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 @@ -13,7 +13,7 @@ import { spawn } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; -import { fileURLToPath } from "node:url"; +import { fileURLToPath, pathToFileURL } from "node:url"; const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); @@ -41,7 +41,8 @@ async function main(argv) { const env = { ...process.env, ARCHILYZER_NO_NETWORK: "1", - NODE_OPTIONS: `--import=${path.join(ROOT, "common", "lib", "noNetwork.mjs")} ${process.env.NODE_OPTIONS ?? ""}`.trim(), + // 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 = ""; diff --git a/umtool/instrumentation.ts b/umtool/instrumentation.ts @@ -13,6 +13,21 @@ 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 { noNetwork, installNoNetworkGuard } = await import("yt-dlp-transcript-common/lib/noNetwork.mjs"); + if (noNetwork()) { + console.error( + "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/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": "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", + "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"; @@ -790,10 +790,55 @@ async function framesOnDisk(dir) { */ export function rendererEnv(env = process.env) { const { DISPLAY: _d, WAYLAND_DISPLAY: _w, ...rest } = env; - return rest; + // And always the opt-outs (deck.mjs RENDERER_OPT_OUTS): no telemetry, no update check, no auto-install. + return { ...rest, ...RENDERER_OPT_OUTS }; } -export function runRenderer(cmd, args) { +/** + * 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. A HyperFrames run through npx whose pinned package is not + * in the npm cache (`--offline` answers ENOTCACHED) is run once more with + * `fallbackArgs` (deck.mjs hyperframesCommand) after a line saying it asks the + * registry and why. + * @param {string} cmd @param {string[]} args + * @param {{ fallbackArgs?: string[], prefix?: string[] }} [opts] `prefix`: the args the fallback replaces + */ +export async function runRenderer(cmd, args, opts = {}) { + try { + return await runRendererOnce(cmd, args); + } catch (e) { + const { fallbackArgs, prefix } = opts; + if (!fallbackArgs || !prefix || !/ENOTCACHED/.test(String(e?.message))) throw e; + process.stderr.write( + `umtool: ${prefix.at(-1)} is not in the npm cache — asking the npm registry for it once (npx ${fallbackArgs.join(" ")}); later renders run it from the cache\n`, + ); + return runRendererOnce(cmd, [...fallbackArgs, ...args.slice(prefix.length)]); + } +} + +/** A HyperFrames CLI run: its command, args, and the npx cache fallback. */ +export function runHyperframes(hf, cliArgs) { + return runRenderer(hf.cmd, [...hf.args, ...cliArgs], hf.fallbackArgs ? { fallbackArgs: hf.fallbackArgs, prefix: hf.args } : {}); +} + +function runRendererOnce(cmd, args) { return new Promise((resolve, reject) => { const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"], env: rendererEnv() }); let tail = ""; @@ -977,7 +1022,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 +1093,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 +1285,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,86 @@ +// The renderer asks no outside service (the operator's rule): every HyperFrames +// run carries the opt-outs, npx runs the pinned package from the npm cache, and +// only a package missing from the cache asks the registry, once and said so. +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { CHROME_QUIET_FLAGS, rendererEnv, runHyperframes } from "./compose-chrome.mjs"; +import { HYPERFRAMES_PKG_DEFAULT, hyperframesCommand, RENDERER_OPT_OUTS } from "./deck.mjs"; + +const OPT_OUTS = { DO_NOT_TRACK: "1", HYPERFRAMES_NO_TELEMETRY: "1", HYPERFRAMES_NO_UPDATE_CHECK: "1", HYPERFRAMES_NO_AUTO_INSTALL: "1" }; + +test("rendererEnv: the four opt-outs always, whatever the environment said; no display", () => { + assert.deepEqual({ ...RENDERER_OPT_OUTS }, OPT_OUTS); + const env = rendererEnv({ PATH: "/bin", DISPLAY: ":0", WAYLAND_DISPLAY: "w", DO_NOT_TRACK: "0", HYPERFRAMES_NO_TELEMETRY: "" }); + assert.deepEqual(env, { PATH: "/bin", ...OPT_OUTS }); +}); + +test("hyperframesCommand: npx from the cache (--offline), the registry only as the logged fallback (--prefer-offline)", () => { + 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("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); + } +}); + +test("runHyperframes: the spawned env carries the opt-outs; a package not in the cache is asked for once, said first", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "renderer-env-")); + const seen = path.join(dir, "seen.jsonl"); + // A stand-in for npx: --offline with an empty cache answers ENOTCACHED, as npm does. + const fake = path.join(dir, "fake-npx.mjs"); + await writeFile( + fake, + `#!/usr/bin/env node +import { appendFileSync } from "node:fs"; +const args = process.argv.slice(2); +const pick = (k) => process.env[k] ?? null; +appendFileSync(${JSON.stringify(seen)}, JSON.stringify({ args, env: { 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") } }) + "\\n"); +if (args[0] === "--offline") { process.stderr.write("npm error code ENOTCACHED\\nnpm error request to https://registry.npmjs.org/hyperframes failed: cache mode is 'only-if-cached'\\n"); process.exit(1); } +`, + ); + await chmod(fake, 0o755); + const said = []; + const write = process.stderr.write.bind(process.stderr); + process.stderr.write = (chunk, ...rest) => { + said.push(String(chunk)); + return write(chunk, ...rest); + }; + try { + const hf = { ...hyperframesCommand({}), cmd: fake }; + await runHyperframes(hf, ["render", "--output", "out", "proj"]); + const runs = (await readFile(seen, "utf8")).trim().split("\n").map((l) => JSON.parse(l)); + assert.equal(runs.length, 2); + assert.deepEqual(runs[0].args, ["--offline", "--yes", HYPERFRAMES_PKG_DEFAULT, "render", "--output", "out", "proj"]); + assert.deepEqual(runs[1].args, ["--prefer-offline", "--yes", HYPERFRAMES_PKG_DEFAULT, "render", "--output", "out", "proj"]); + for (const r of runs) assert.deepEqual(r.env, OPT_OUTS); + assert.ok(said.some((l) => /is not in the npm cache — asking the npm registry for it once/.test(l)), said.join("")); + } finally { + process.stderr.write = write; + await rm(dir, { recursive: true, force: true }); + } +}); + +test("runHyperframes: any other failure is not retried against the registry", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "renderer-env-")); + const count = path.join(dir, "n"); + const fake = path.join(dir, "fake-npx.mjs"); + await writeFile(fake, `#!/usr/bin/env node\nimport { appendFileSync } from "node:fs";\nappendFileSync(${JSON.stringify(count)}, "x");\nprocess.stderr.write("render failed: a frame timed out\\n");\nprocess.exit(1);\n`); + await chmod(fake, 0o755); + try { + await assert.rejects(runHyperframes({ ...hyperframesCommand({}), cmd: fake }, ["render"]), /a frame timed out/); + assert.equal(await readFile(count, "utf8"), "x"); + } 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,6 @@ 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" }); + // (And the renderer's opt-outs, always: renderer-env.test.mjs.) + assert.deepEqual(env, { PATH: "/usr/bin", HOME: "/h", DO_NOT_TRACK: "1", HYPERFRAMES_NO_TELEMETRY: "1", HYPERFRAMES_NO_UPDATE_CHECK: "1", HYPERFRAMES_NO_AUTO_INSTALL: "1" }); });