// The renderer asks no outside service (the operator's rule). Every HyperFrames // run happens in a child with outward connections refused (common/lib/noNetwork.mjs // preloaded), plus the opt-outs. Its refusals are a NOTE, never an error. A // first run's one download (the package, the browser) happens unguarded, once, // and is said first. The parent process is never guarded. // Run with: pnpm test:scripts import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import test from "node:test"; import { fileURLToPath } from "node:url"; import { CHROME_QUIET_FLAGS, firstRunDownload, rendererEnv, runHyperframes } from "./compose-chrome.mjs"; import { HYPERFRAMES_PKG_DEFAULT, hyperframesCommand, RENDERER_OPT_OUTS } from "./deck.mjs"; const HERE = path.dirname(fileURLToPath(import.meta.url)); const OPT_OUTS = { DO_NOT_TRACK: "1", HYPERFRAMES_NO_TELEMETRY: "1", HYPERFRAMES_NO_UPDATE_CHECK: "1", HYPERFRAMES_NO_AUTO_INSTALL: "1" }; const OUT = "192.0.2.1"; // TEST-NET-1: nothing answers there test("rendererEnv: the opt-outs always, no display, and the child guarded (switch and preload) unless asked not to be", () => { assert.deepEqual({ ...RENDERER_OPT_OUTS }, OPT_OUTS); const env = rendererEnv({ PATH: "/bin", DISPLAY: ":0", WAYLAND_DISPLAY: "w", DO_NOT_TRACK: "0", NODE_OPTIONS: "--max-old-space-size=100" }, { refusalLog: "/w/r.jsonl" }); assert.equal(env.DISPLAY, undefined); assert.equal(env.WAYLAND_DISPLAY, undefined); for (const [k, v] of Object.entries(OPT_OUTS)) assert.equal(env[k], v, k); assert.equal(env.ARCHILYZER_NO_NETWORK, "1"); assert.match(env.NODE_OPTIONS, /^--import=file:\/\/.*\/common\/lib\/noNetwork\.mjs --max-old-space-size=100$/); assert.equal(env.ARCHILYZER_NO_NETWORK_LOG, "/w/r.jsonl"); const open = rendererEnv({ PATH: "/bin", ARCHILYZER_NO_NETWORK: "1", ARCHILYZER_NO_NETWORK_LOG: "/x" }, { guarded: false }); assert.deepEqual(open, { PATH: "/bin", ...OPT_OUTS }); }); test("hyperframesCommand: npx from the cache (--offline); --prefer-offline only for a first run's download", () => { assert.deepEqual(hyperframesCommand({}), { cmd: "npx", args: ["--offline", "--yes", HYPERFRAMES_PKG_DEFAULT], fallbackArgs: ["--prefer-offline", "--yes", HYPERFRAMES_PKG_DEFAULT], version: HYPERFRAMES_PKG_DEFAULT, }); assert.deepEqual(hyperframesCommand({ HYPERFRAMES_BIN: "/x/hf" }), { cmd: "/x/hf", args: [], version: "bin:/x/hf" }); }); test("firstRunDownload: only the package missing from the cache, or the browser not downloaded — each a quiet one-off step", () => { const hf = hyperframesCommand({}); assert.deepEqual(firstRunDownload(hf, "npm error code ENOTCACHED")?.args, ["--prefer-offline", "--yes", HYPERFRAMES_PKG_DEFAULT, "--help"]); assert.deepEqual(firstRunDownload(hf, "Error: Failed to download chrome-headless-shell 1.2.3: …")?.args, ["--offline", "--yes", HYPERFRAMES_PKG_DEFAULT, "browser", "ensure", "--json"]); assert.equal(firstRunDownload(hf, "render failed: a frame timed out"), null); assert.equal(firstRunDownload(hf, `ARCHILYZER_NO_NETWORK=1: a connection refused (registry.npmjs.org:443)`), null, "a refused update check is not a download"); }); test("the headless Chromium the pipeline starts itself is told to stay quiet", () => { for (const f of ["--disable-background-networking", "--disable-component-update", "--no-pings", "--metrics-recording-only", "--disable-sync", "--disable-breakpad"]) { assert.ok(CHROME_QUIET_FLAGS.includes(f), f); } }); /** A HyperFrames stand-in (a node script, so the preload reaches it): records its argv and env, then does `body`. */ async function stub(dir, body) { const seen = path.join(dir, "seen.jsonl"); const file = path.join(dir, "fake-hf.mjs"); await writeFile( file, `#!/usr/bin/env node import { appendFileSync } from "node:fs"; import net from "node:net"; const args = process.argv.slice(2); const pick = (k) => process.env[k] ?? null; appendFileSync(${JSON.stringify(seen)}, JSON.stringify({ args, env: { ARCHILYZER_NO_NETWORK: pick("ARCHILYZER_NO_NETWORK"), NODE_OPTIONS: pick("NODE_OPTIONS"), DO_NOT_TRACK: pick("DO_NOT_TRACK"), HYPERFRAMES_NO_TELEMETRY: pick("HYPERFRAMES_NO_TELEMETRY"), HYPERFRAMES_NO_UPDATE_CHECK: pick("HYPERFRAMES_NO_UPDATE_CHECK"), HYPERFRAMES_NO_AUTO_INSTALL: pick("HYPERFRAMES_NO_AUTO_INSTALL") }, guarded: net.Socket.prototype.connect.name === "guardedConnect" }) + "\\n"); ${body} `, ); await chmod(file, 0o755); return { file, runs: async () => (await readFile(seen, "utf8")).trim().split("\n").map((l) => JSON.parse(l)) }; } async function captureStderr(fn) { const said = []; const write = process.stderr.write.bind(process.stderr); process.stderr.write = (chunk, ...rest) => { said.push(String(chunk)); return write(chunk, ...rest); }; try { return { value: await fn(), said: said.join("") }; } finally { process.stderr.write = write; } } test("runHyperframes: the child is guarded; its outward requests (an update check) are refused, the render succeeds, and a NOTE names them", async () => { const dir = await mkdtemp(path.join(tmpdir(), "renderer-env-")); try { const proj = path.join(dir, "proj"); await mkdir(proj); // What the CLI does at start: a fire-and-forget check of another host, its failure ignored; then it renders. const s = await stub(dir, `const c = net.connect(443, ${JSON.stringify(OUT)}); c.on("error", () => {}); setTimeout(() => process.exit(0), 300);`); const hf = { cmd: s.file, args: [], version: "bin:stub" }; const { value, said } = await captureStderr(() => runHyperframes(hf, ["render", "--output", path.join(dir, "frames"), proj])); const [run] = await s.runs(); assert.equal(run.guarded, true, "the guard is installed in the child"); assert.equal(run.env.ARCHILYZER_NO_NETWORK, "1"); assert.match(run.env.NODE_OPTIONS, /noNetwork\.mjs/); for (const [k, v] of Object.entries(OPT_OUTS)) assert.equal(run.env[k], v, k); assert.deepEqual([...value.refused.keys()], [OUT]); assert.match(said, /note — 1 outward request from the renderer refused: 192\.0\.2\.1/); assert.match(await readFile(path.join(proj, ".renderer-refused.jsonl"), "utf8"), /192\.0\.2\.1:443/); } finally { await rm(dir, { recursive: true, force: true }); } }); test("runHyperframes, first run: the package missing from the npm cache is fetched once, unguarded and said, then the render runs guarded", async () => { const dir = await mkdtemp(path.join(tmpdir(), "renderer-env-")); try { const proj = path.join(dir, "proj"); await mkdir(proj); const flag = path.join(dir, "cached"); // --offline with an empty cache answers ENOTCACHED, as npm does; the --prefer-offline step "caches" it. const s = await stub(dir, `import { existsSync, writeFileSync } from "node:fs"; if (args[0] === "--prefer-offline") { writeFileSync(${JSON.stringify(flag)}, ""); process.exit(0); } if (!existsSync(${JSON.stringify(flag)})) { process.stderr.write("npm error code ENOTCACHED\\n"); process.exit(1); }`); const hf = { ...hyperframesCommand({}), cmd: s.file }; const { said } = await captureStderr(() => runHyperframes(hf, ["render", proj])); const runs = await s.runs(); assert.deepEqual(runs.map((r) => r.args[0]), ["--offline", "--prefer-offline", "--offline"]); assert.deepEqual(runs[1].args.slice(-1), ["--help"], "the one-off step skips the CLI's checks"); assert.match(said, /first run — fetching hyperframes@[\d.]+ from the npm registry \(registry\.npmjs\.org\); this one step runs with outward connections allowed/); assert.equal(said.match(/first run —/g).length, 1); } finally { await rm(dir, { recursive: true, force: true }); } }); test("runHyperframes, first run: the browser not downloaded is fetched once (browser ensure), then the render; a second failure is the render's", async () => { const dir = await mkdtemp(path.join(tmpdir(), "renderer-env-")); try { const proj = path.join(dir, "proj"); await mkdir(proj); // Always missing: the step runs once, the retry fails the same way, and that failure is the render's. const s = await stub(dir, `if (args.includes("ensure")) process.exit(0); process.stderr.write("Error: Failed to download chrome-headless-shell 1.2.3: ARCHILYZER_NO_NETWORK=1: a connection refused (storage.googleapis.com:443)\\n"); process.exit(1);`); const hf = { ...hyperframesCommand({}), cmd: s.file }; const { value } = await captureStderr(() => runHyperframes(hf, ["render", proj]).then(() => "ok", (e) => e)); assert.match(String(value?.message), /Failed to download chrome-headless-shell/); const runs = await s.runs(); assert.deepEqual(runs.map((r) => r.args.slice(3).join(" ")), ["render " + proj, "browser ensure --json", "render " + proj]); } finally { await rm(dir, { recursive: true, force: true }); } }); test("the parent is never guarded: a process with the switch unset renders, and its own connections are its own", async () => { const dir = await mkdtemp(path.join(tmpdir(), "renderer-env-")); try { const proj = path.join(dir, "proj"); await mkdir(proj); const s = await stub(dir, `process.exit(0);`); const probe = ` import http from "node:http"; import net from "node:net"; const { runHyperframes } = await import(${JSON.stringify(path.join(HERE, "compose-chrome.mjs"))}); await runHyperframes({ cmd: ${JSON.stringify(s.file)}, args: [], version: "bin:stub" }, ["render", ${JSON.stringify(proj)}]); const srv = http.createServer((q, r) => r.end("ok")); await new Promise((r) => srv.listen(0, "127.0.0.1", r)); const body = await (await fetch("http://127.0.0.1:" + srv.address().port + "/")).text(); srv.close(); // An outward connect is not refused here (it is left pending at TEST-NET-1 and dropped). const c = net.connect(443, ${JSON.stringify(OUT)}); const outcome = await new Promise((r) => { c.on("error", (e) => r(e.code)); setTimeout(() => r("not refused"), 300); }); c.destroy(); console.log(JSON.stringify({ body, outcome, guarded: net.Socket.prototype.connect.name === "guardedConnect" }));`; // Through env(1): this test file runs under the harness's switch, which a child would otherwise inherit. const r = spawnSync("env", ["-u", "ARCHILYZER_NO_NETWORK", "-u", "NODE_OPTIONS", process.execPath, "--input-type=module", "-e", probe], { encoding: "utf8" }); assert.equal(r.status, 0, r.stderr); assert.deepEqual(JSON.parse(r.stdout.trim().split("\n").at(-1)), { body: "ok", outcome: "not refused", guarded: false }); const [run] = await s.runs(); assert.equal(run.guarded, true, "while its renderer child is guarded"); } finally { await rm(dir, { recursive: true, force: true }); } });