// ARCHILYZER_NO_NETWORK (lib/noNetwork.mjs): every door refuses a host that is // not loopback, loopback still works, and with the switch unset nothing changes. // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/noNetwork.test.ts // // The "outward" address is 192.0.2.1 (TEST-NET-1, documentation only: nothing // answers there), so even a broken guard would reach no real site. import { test } from "node:test"; import assert from "node:assert/strict"; import { execFileSync, exec, spawn, spawnSync } from "node:child_process"; import dgram from "node:dgram"; import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import http from "node:http"; import { tmpdir } from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; // This file holds the switch itself, however it is run. process.env.ARCHILYZER_NO_NETWORK = "1"; const nn = await import("./noNetwork.mjs"); nn.installNoNetworkGuard(); const OUT = "192.0.2.1"; const MODULE = fileURLToPath(new URL("./noNetwork.mjs", import.meta.url)); const refusedBy = (e: unknown): string => { const err = e as { code?: string; cause?: { code?: string; message?: string }; message?: string }; if (err?.code === "ENONETWORK") return err.message ?? ""; if (err?.cause?.code === "ENONETWORK") return err.cause.message ?? ""; return ""; }; // A stand-in for a networking tool, named like one: it records that it ran. async function fakeTool(name: string): Promise<{ bin: string; ran: string; dir: string }> { const dir = await mkdtemp(path.join(tmpdir(), "no-network-")); const ran = path.join(dir, "ran"); const bin = path.join(dir, name); await writeFile(bin, `#!/bin/sh\necho "$@" >> ${JSON.stringify(ran)}\n`); await chmod(bin, 0o755); return { bin, ran, dir }; } test("the switch reads 1 as on, and unset, empty or 0 as off; loopback is every spelling of it", () => { assert.equal(nn.noNetwork({ ARCHILYZER_NO_NETWORK: "1" }), true); for (const v of [undefined, "", "0"]) assert.equal(nn.noNetwork({ ARCHILYZER_NO_NETWORK: v }), false); for (const h of ["localhost", "127.0.0.1", "127.8.9.10", "::1", "[::1]", "::ffff:127.0.0.1", "app.localhost", ""]) assert.equal(nn.isLoopbackHost(h), true, h); for (const h of [OUT, "odysee.com", "10.0.0.1", "::ffff:192.0.2.1", "localhost.example"]) assert.equal(nn.isLoopbackHost(h), false, h); }); test("door: what children ask by themselves is said off — npm reads its cache only, CLIs send no telemetry", () => { assert.equal(process.env.npm_config_offline, "true"); assert.equal(process.env.DO_NOT_TRACK, "1"); assert.equal(process.env.HYPERFRAMES_NO_TELEMETRY, "1"); }); test("door: fetch to another host is refused before it connects, naming the door", async () => { await assert.rejects(fetch(`https://${OUT}/x`), (e) => /a connection .* refused \(192\.0\.2\.1:443\)/.test(refusedBy(e))); }); test("door: an http(s) request to another host fails with the socket's error", async () => { const err = await new Promise((resolve) => http.get(`http://${OUT}/`).on("error", resolve)); assert.match(refusedBy(err), /refused \(192\.0\.2\.1:80\)/); }); test("door: a WebSocket to another host closes with an error, never connected", async () => { const ws = new WebSocket(`wss://${OUT}/announce`); const ev = await new Promise((resolve) => { ws.onopen = () => resolve("open"); ws.onerror = () => resolve("error"); }); assert.equal(ev, "error"); }); test("door: a UDP datagram to another host (a UDP tracker) is refused", async () => { const s = dgram.createSocket("udp4"); try { const err = await new Promise((resolve) => s.send("x", 6969, OUT, (e) => resolve(e))); assert.match(refusedBy(err), /a UDP datagram .* refused \(192\.0\.2\.1\)/); } finally { s.close(); } }); test("loopback is never refused: a test's own server answers", async () => { const srv = http.createServer((_q, r) => r.end("ok")); await new Promise((r) => srv.listen(0, "127.0.0.1", () => r())); try { const port = (srv.address() as { port: number }).port; assert.equal(await (await fetch(`http://127.0.0.1:${port}/`)).text(), "ok"); assert.equal(await (await fetch(`http://localhost:${port}/`)).text(), "ok"); } finally { await new Promise((r) => srv.close(() => r())); } }); test("door: yt-dlp (or ffmpeg, gallery-dl…) spawned for another host is refused — spawn, spawnSync, execFile, exec, execa", async () => { const yt = await fakeTool("yt-dlp"); try { const url = `https://${OUT}/watch?v=x`; assert.throws(() => spawn(yt.bin, ["--no-playlist", url]), (e) => /spawning yt-dlp for https:\/\/192\.0\.2\.1/.test(refusedBy(e))); assert.throws(() => spawnSync(yt.bin, [url]), (e) => refusedBy(e) !== ""); assert.throws(() => execFileSync(yt.bin, [url]), (e) => refusedBy(e) !== ""); assert.throws(() => exec(`${yt.bin} ${url}`), (e) => refusedBy(e) !== ""); assert.throws(() => spawnSync("sh", ["-c", `ffmpeg -i ${url} out.mp4`]), (e) => /spawning ffmpeg/.test(refusedBy(e))); // The repo's yt-dlp runner spawns through execa: the same door. const { execa } = await import("execa"); await assert.rejects(execa(yt.bin, [url]), (e) => refusedBy(e) !== ""); await assert.rejects(readFile(yt.ran, "utf8"), "it never ran"); // Loopback, and a test's fake named as one (fake-ytdlp.mjs), run. assert.equal(spawnSync(yt.bin, ["http://127.0.0.1:4000/v"]).status, 0); const fake = await fakeTool("fake-ytdlp.mjs"); assert.equal(spawnSync(fake.bin, [url]).status, 0); await rm(fake.dir, { recursive: true, force: true }); assert.match(await readFile(yt.ran, "utf8"), /127\.0\.0\.1/); } finally { await rm(yt.dir, { recursive: true, force: true }); } }); test("door: a browser is given a proxy that does not answer; on another host's URL, or Firefox, it is refused", () => { const g = nn.guardSpawn("/x/ms-playwright/chromium_headless_shell-1/chrome-linux/headless_shell", ["--headless", "--remote-debugging-pipe", "about:blank"]); assert.ok("args" in g && g.args.includes("--proxy-server=http://127.0.0.1:9"), JSON.stringify(g)); const own = nn.guardSpawn("/usr/bin/chromium", ["--proxy-server=http://127.0.0.1:3128", "file:///tmp/card.html"]); assert.ok("args" in own && !own.args.includes("--proxy-server=http://127.0.0.1:9"), "its own proxy is kept"); assert.ok("refuse" in nn.guardSpawn("google-chrome", ["--headless", "https://odysee.com/@x"])); assert.ok("refuse" in nn.guardSpawn("/usr/lib/firefox/firefox", ["-headless"])); // Not a networking tool: untouched. assert.deepEqual(nn.guardSpawn("node", ["script.mjs", "https://odysee.com/"]), { args: ["script.mjs", "https://odysee.com/"] }); }); test("a tool or browser is one only where it is the command: an argument value is not", () => { const url = "https://x.com/someone"; // A fake gallery-dl told which browser's cookies to read starts no Firefox; one told where ffmpeg is runs no ffmpeg. assert.ok("args" in nn.guardSpawn("/tmp/t/fake-gallery-dl.mjs", ["--cookies-from-browser", "firefox", url])); assert.ok("args" in nn.guardSpawn("/tmp/t/fake-ytdlp.mjs", ["--cookies-from-browser", "chrome", "--ffmpeg-location", "ffmpeg", url])); // What a wrapper or a shell runs is a command. assert.ok("refuse" in nn.guardSpawn("timeout", ["30", "yt-dlp", url])); assert.ok("refuse" in nn.guardSpawn("xvfb-run", ["-a", "chromium", url])); assert.ok("refuse" in nn.guardSpawn("sh", ["-c", `cat list | ffmpeg -i ${url} -f null -`])); assert.ok("refuse" in nn.guardSpawn("bash", ["-c", `FOO=1 nice -n 10 gallery-dl ${url}`])); const wrapped = nn.guardSpawn("xvfb-run", ["-a", "/usr/bin/chromium", "--headless"]); assert.ok("args" in wrapped && wrapped.args.includes("--proxy-server=http://127.0.0.1:9")); }); test("promisify(execFile) and promisify(exec) keep their {stdout, stderr} answer, and are guarded", async () => { const { promisify } = await import("node:util"); const cp = await import("node:child_process"); const run = promisify(cp.execFile); const r = await run("sh", ["-c", "echo hi"]); assert.equal(r.stdout, "hi\n"); assert.equal((await promisify(cp.exec)("echo there")).stdout, "there\n"); await assert.rejects(run("sh", ["-c", `curl https://${OUT}/`]), (e) => /spawning curl/.test(refusedBy(e))); }); test("door: the Odysee player-page opener refuses by name, before any browser", async () => { const { openPlayerPage } = await import("../ytdlp/storedUrlPageOpen"); const lines: string[] = []; const r = await openPlayerPage({ pageUrl: "https://odysee.com/@demo:1/x:1", cdnHost: "player.odycdn.com", signal: new AbortController().signal, onLog: (l) => lines.push(l) }); assert.equal(r.ok, false); assert.match(r.error ?? "", /ARCHILYZER_NO_NETWORK=1: the Odysee player-page opener refused/); assert.match(lines.join(""), /player-page opener refused/); }); test("named doors: assertNetworkAllowed refuses another host and passes loopback; with the switch off it passes all", () => { assert.throws(() => nn.assertNetworkAllowed("a door", "https://archive.org/x"), /a door refused/); nn.assertNetworkAllowed("a door", "http://127.0.0.1:3001/api"); nn.assertNetworkAllowed("a door", "https://archive.org/x", {}); }); test("review 2: spawn with shell: true is read as the shell would", () => { assert.throws(() => spawnSync(`curl --max-time 1 http://${OUT}/ || true`, { shell: true }), (e) => /spawning curl/.test(refusedBy(e))); assert.equal(spawnSync("echo ok", { shell: true, encoding: "utf8" }).stdout, "ok\n"); }); test("review 2: a child given its own environment (env: {}) keeps the switch and the preload", () => { const code = `const s=require('net').connect(80,'${OUT}');s.on('error',e=>{console.log(e.code);process.exit()});setTimeout(()=>{console.log('pending');process.exit()},2500)`; const r = spawnSync(process.execPath, ["-e", code], { env: {}, encoding: "utf8" }); assert.equal(r.stdout.trim(), "ENONETWORK"); const env = nn.guardedChildEnv({ NODE_OPTIONS: "--max-old-space-size=100" }); assert.equal(env.ARCHILYZER_NO_NETWORK, "1"); assert.match(env.NODE_OPTIONS ?? "", /^--import=file:\/\/.*noNetwork\.mjs --max-old-space-size=100$/); assert.equal(nn.withPreload(env.NODE_OPTIONS), env.NODE_OPTIONS, "once"); }); test("review 2: a worker thread is guarded — an eval worker and a file worker", async () => { const { Worker } = await import("node:worker_threads"); const ask = (w: InstanceType) => new Promise((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((r) => peer.bind(0, "127.0.0.1", () => r())); const got = new Promise((r) => peer.once("message", (m) => r(String(m)))); const s = dgram.createSocket("udp4"); try { await new Promise((r) => s.connect((peer.address() as { port: number }).port, "127.0.0.1", () => r())); await new Promise((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((resolve) => { const sock = net.connect({ host: "localhost", port: 80, lookup: lookup as never }); sock.once("error", resolve); sock.once("connect", () => resolve(new Error("CONNECTED"))); }); assert.match(refusedBy(err), /lookup \(localhost\) refused \(localhost → 192\.0\.2\.1\)/); }); test("review 2: installed outside a test run, it says so on stderr; under the harness it is silent", () => { // A guarded process puts the preload back into any child's environment, so // the child here is reached through env(1), which takes away what each case needs gone. const run = (drop: string[], set: string[] = []) => spawnSync("env", [...drop.flatMap((k) => ["-u", k]), ...set, process.execPath, "--input-type=module", "-e", `await import(${JSON.stringify(MODULE)});`], { encoding: "utf8" }).stderr; assert.match(run(["NODE_TEST_CONTEXT", "NODE_OPTIONS"]), /ARCHILYZER_NO_NETWORK=1: this process refuses every non-loopback connection/); assert.equal(run(["NODE_OPTIONS"], ["NODE_TEST_CONTEXT=child-v8"]), ""); assert.equal(run(["NODE_TEST_CONTEXT"]), "", "the harness's preload in NODE_OPTIONS"); }); test("unset, nothing changes: the guard is not installed and a tool runs for any URL", async () => { const yt = await fakeTool("yt-dlp"); try { const probe = ` const cp = await import("node:child_process"); const net = await import("node:net"); await import(${JSON.stringify(MODULE)}); const r = cp.spawnSync(${JSON.stringify(yt.bin)}, ["https://${OUT}/watch?v=x"]); console.log(JSON.stringify({ spawnGuarded: cp.spawn.name === "guarded", connectGuarded: net.Socket.prototype.connect.name === "guardedConnect", status: r.status }));`; // Through env(1): a guarded process would put the switch back into a child's own environment. const out = execFileSync("env", ["-u", "ARCHILYZER_NO_NETWORK", "-u", "NODE_OPTIONS", process.execPath, "--input-type=module", "-e", probe], { encoding: "utf8" }); assert.deepEqual(JSON.parse(out), { spawnGuarded: false, connectGuarded: false, status: 0 }); // (And set, the same probe sees both guarded — the names are the guard's.) const on = execFileSync("env", ["-u", "NODE_OPTIONS", "ARCHILYZER_NO_NETWORK=1", process.execPath, "--input-type=module", "-e", probe.replace(/const r = [^;]+;/, "const r = { status: 0 };")], { encoding: "utf8" }); assert.deepEqual(JSON.parse(on), { spawnGuarded: true, connectGuarded: true, status: 0 }); assert.match(await readFile(yt.ran, "utf8"), /192\.0\.2\.1/, "the tool ran: nothing refused"); } finally { await rm(yt.dir, { recursive: true, force: true }); } });