Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 8da28f0fe4531af9393c9216ca7e8e750ddb381c
parent d02a49d1496fb4ba1e2eafec1daa45e22fcbd5ab
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 14 Nov 2026 09:54:43 -0500

Product renders run the HyperFrames CLI with outward connections refused; first-run downloads are the one logged exception

The final review of d02a49d14 found that "no update check" was false. The cached CLI (hyperframes@0.8.24)
checks the npm registry and raw.githubusercontent.com (its skills) at the start of every render command,
throttled daily. HYPERFRAMES_NO_UPDATE_CHECK only silences the notice. Rather than chase its flags:

- rendererEnv() gives the CHILD ARCHILYZER_NO_NETWORK=1 and the noNetwork.mjs preload in its NODE_OPTIONS,
  plus the opt-outs. The CLI, npx and everything they start reach loopback only, and the browser gets the dead
  proxy. The parent process is never guarded.
- runHyperframes logs the child's refusals to <project>/.renderer-refused.jsonl. After the run it prints
  `note — N outward requests from the renderer refused: <hosts>`, a note and never an error.
  - In the dist, the update and skills checks are fire-and-forget (`.catch(() => null)`), so a refused one
    changes nothing in the render.
  - A failed check is not recorded in ~/.hyperframes/config.json either (only an answered one is), so under
    the guard it is tried and refused on every render.
- First run (firstRunDownload): when the guarded run fails because something must be downloaded, that one
  step runs unguarded, after a line naming what is fetched and from where, and the render then runs guarded
  again. Each kind runs at most once per call.
  - The package missing from the npm cache (ENOTCACHED): `npx --prefer-offline --yes <pkg> --help`.
    `--help` skips the CLI's checks.
  - The browser not downloaded ("Failed to download chrome-headless-shell"): `<cli> browser ensure --json`.
    `--json` skips the checks. Checked here, guarded and offline, against the cached browser.
- The CLI finds its config through $HOME (`homedir()/.hyperframes`); it has no variable of its own. Its
  browser cache (~/.cache/hyperframes/chrome) and npx's cache are under $HOME too. Pointing a render's HOME
  elsewhere would force both downloads and change font lookup, so renders keep the operator's HOME. A guarded
  render writes nothing there for its checks.
- One boot banner: announceNoNetwork prints once per process, the guard's line or the editor's/umtool's
  instrumentation line, whichever comes first.
- OPERATING.md says what is blocked and how, that first-run downloads are the logged exception, and that
  `hyperframes telemetry disable` turns off telemetry only for by-hand use. By-hand runs still make the
  daily update and skills checks.
- Tests (renderer-env.test.mjs, 8):
  - the child carries the switch, the preload and the opt-outs;
  - a CLI stub's outward connect is refused, the render succeeds, and the note names the host;
  - the ENOTCACHED and browser-missing first runs each run their one unguarded step once and log it;
  - a parent with the switch unset renders, and its own connections are its own.
  - threads.test is updated.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
MOPERATING.md | 25++++++++++++++++++++-----
Mcommon/lib/noNetwork.d.mts | 1+
Mcommon/lib/noNetwork.mjs | 18+++++++++++++++---
Meditor/instrumentation.ts | 5+++--
Mumtool/instrumentation.ts | 5+++--
Mumtool/report-to-video/compose-chrome.mjs | 120+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------
Mumtool/report-to-video/renderer-env.test.mjs | 160+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------
Mumtool/report-to-video/threads.test.mjs | 7+++++--
8 files changed, 271 insertions(+), 70 deletions(-)

diff --git a/OPERATING.md b/OPERATING.md @@ -1255,17 +1255,32 @@ pnpm ops compaction-markers --json '{"clear":{"slug":"example","id":"<videoId>"} 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. +- **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. -For HyperFrames run by hand on the host, `hyperframes telemetry disable` does the same once. +**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 diff --git a/common/lib/noNetwork.d.mts b/common/lib/noNetwork.d.mts @@ -14,3 +14,4 @@ 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 @@ -494,6 +494,20 @@ function checkedLookup(lookup, host) { } 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() { @@ -502,9 +516,7 @@ export function installNoNetworkGuard() { // 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`); - } + 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 diff --git a/editor/instrumentation.ts b/editor/instrumentation.ts @@ -23,9 +23,10 @@ export async function register() { // 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"); + const { announceNoNetwork, noNetwork, installNoNetworkGuard } = await import("yt-dlp-transcript-common/lib/noNetwork.mjs"); if (noNetwork()) { - console.error( + // 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.", ); diff --git a/umtool/instrumentation.ts b/umtool/instrumentation.ts @@ -17,9 +17,10 @@ export async function register() { // 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"); + const { announceNoNetwork, noNetwork, installNoNetworkGuard } = await import("yt-dlp-transcript-common/lib/noNetwork.mjs"); if (noNetwork()) { - console.error( + // 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.", ); diff --git a/umtool/report-to-video/compose-chrome.mjs b/umtool/report-to-video/compose-chrome.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,10 +789,26 @@ 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; - // And always the opt-outs (deck.mjs RENDERER_OPT_OUTS): no telemetry, no update check, no auto-install. - return { ...rest, ...RENDERER_OPT_OUTS }; + // 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; } /** @@ -812,35 +829,90 @@ export const CHROME_QUIET_FLAGS = Object.freeze([ "--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); +} + /** - * 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 + * 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 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)]); +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; } -/** 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 } : {}); +/** 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 }; } -function runRendererOnce(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); diff --git a/umtool/report-to-video/renderer-env.test.mjs b/umtool/report-to-video/renderer-env.test.mjs @@ -1,24 +1,37 @@ -// 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. +// 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 { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +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 { CHROME_QUIET_FLAGS, rendererEnv, runHyperframes } from "./compose-chrome.mjs"; +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 four opt-outs always, whatever the environment said; no display", () => { +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", HYPERFRAMES_NO_TELEMETRY: "" }); - assert.deepEqual(env, { PATH: "/bin", ...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), the registry only as the logged fallback (--prefer-offline)", () => { +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], @@ -28,28 +41,40 @@ test("hyperframesCommand: npx from the cache (--offline), the registry only as t 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); } }); -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-")); +/** 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"); - // A stand-in for npx: --offline with an empty cache answers ENOTCACHED, as npm does. - const fake = path.join(dir, "fake-npx.mjs"); + const file = path.join(dir, "fake-hf.mjs"); await writeFile( - fake, + 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: { 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); } +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(fake, 0o755); + 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) => { @@ -57,29 +82,100 @@ if (args[0] === "--offline") { process.stderr.write("npm error code ENOTCACHED\\ 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("")); + 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("runHyperframes: any other failure is not retried against the registry", async () => { +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-")); - 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"); + 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,6 +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" }); - // (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" }); + 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.) });