Archilyzer · Source

archilyzer

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

commit 4790929909c26334e7c8c9766d0504c10f29e583
parent 1f63880440d6a104ed4653a39f16526ad8276408
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 14 Nov 2026 08:16:29 -0500

ARCHILYZER_NO_NETWORK=1: no test run can reach another host, however it is started

Four runs of this lane opened headless Chromium on odysee.com for made-up fixture videos. Those were bare
`tsx <file>` runs, which skip the NODE_TEST_CONTEXT guard. Under one switch, the process's outward doors now
refuse before any request, naming the door.

- common/lib/noNetwork.mjs (typed by noNetwork.d.mts, exported) is the choke point, in product code:
  - Connections: net.Socket#connect, which every fetch, http(s), WebSocket and tracker announce goes through,
    fails with ENONETWORK for a host that is not loopback. So does dgram (UDP trackers).
  - Child processes: child_process spawn/spawnSync/execFile/execFileSync/fork/exec/execSync are synced into
    the ESM bindings, and execa goes through them. They refuse a networking tool (yt-dlp, gallery-dl, ffmpeg,
    ffprobe, curl, wget, streamlink…) whose command line names a non-loopback URL. The tool counts only in a
    command position (the executable, what a wrapper or shell runs), so `--cookies-from-browser firefox` and a
    test's `fake-ytdlp.mjs` pass.
  - Browsers: one started with no URL argument gets a proxy that does not answer, so loopback and file://
    pages still load; one started on another host's URL, and Firefox, are refused.
  - promisify.custom is kept, so promisify(execFile) still resolves {stdout, stderr}.
  - It installs itself on import when the switch is set. The harness preloads it, and lib/paths.ts,
    ytdlp/runYtdlp.ts and social/playwrightRuntime.ts import it.
  - ARCHILYZER_NO_NETWORK_LOG=<file> logs each refusal.
- Named doors: the Odysee player-page opener refuses by name, first. The seeder names no STUN servers under the
  switch, because native WebRTC sockets are past the JS guard.
- The harness sets the switch and preloads the guard into every node process the run starts
  (NODE_OPTIONS=--import=…): each package's `test` (common, editor, export, homepage, mcp, umtool),
  `pnpm test:scripts` and `pnpm test:files`. common/testing/README.md gives the line a by-hand run must export.
- ENVIRONMENT.md lists ARCHILYZER_NO_NETWORK and ARCHILYZER_NO_NETWORK_LOG (from lib/envVars.ts).
- lib/noNetwork.test.ts proves each door refuses (fetch, http, WebSocket, UDP, spawn/spawnSync/execFile/exec/
  execa, shells and wrappers, browsers, the opener, promisified exec) and that loopback still answers. It also
  proves that with the switch unset nothing is installed and a tool runs for any URL. Its outward address is
  TEST-NET-1 (192.0.2.1), so a broken guard reaches no real site either.
- On install the guard also sets npm_config_offline=true, DO_NOT_TRACK=1 and HYPERFRAMES_NO_TELEMETRY=1
  (unless already set), for the run's children.
- Found by the refusal log in a full run of every suite (tests that reached past loopback in normal
  `node --test` runs):
  - umtool/report-to-video/analysis-build.test.mjs: its real `npx --yes hyperframes@…` render asked
    registry.npmjs.org, and HyperFrames sent PostHog telemetry (us.i.posthog.com), even though the build ran
    with noNetwork: true.
  - editor/app/api/ops/_read.test.ts: a disabled remote worker's fixture URL (lan-box.local:3001) was probed.
    It is now 127.0.0.1:9.
  - Both passed before and pass now.
- The two stored-URL editor tests keep their empty E2E_ODYSEE_PAGE_FIXTURE as a second guard.

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

Diffstat:
MENVIRONMENT.md | 4++++
Mcommon/controller/seeder.ts | 4++++
Mcommon/lib/envVars.ts | 4++++
Acommon/lib/noNetwork.d.mts | 13+++++++++++++
Acommon/lib/noNetwork.mjs | 331+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/noNetwork.test.ts | 190+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/paths.ts | 3+++
Mcommon/package.json | 3++-
Mcommon/social/playwrightRuntime.ts | 3+++
Mcommon/testing/README.md | 14+++++++++++++-
Mcommon/ytdlp/runYtdlp.ts | 3+++
Mcommon/ytdlp/storedUrlPageOpen.ts | 9+++++++++
Meditor/app/api/ops/_read.test.ts | 3++-
Meditor/package.json | 2+-
Mexport/package.json | 2+-
Mhomepage/package.json | 2+-
Mmcp/package.json | 2+-
Mpackage.json | 2+-
Mscripts/test-files.mjs | 11+++++++++--
Mumtool/package.json | 2+-
20 files changed, 596 insertions(+), 11 deletions(-)

diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -189,6 +189,10 @@ The publish pipeline sets these for a process it spawns. Listed so a reader know | `GGML_BACKEND_PATH` | settings.tts.orpheus.ggmlBackendPath | The ggml backend llama-server loads (Vulkan by default), set for the Orpheus server the editor starts — from `settings.tts.orpheus.ggmlBackendPath`, never the environment. | common/lib/ttsApps.ts | | `HOMEPAGE_DIST_DIR` | unset (`homepage/out`) | Where the homepage's `next build` writes its export; `archilyzer build homepage --private` sets it to `out-private`, so the private build never replaces the deployable `homepage/out`. | homepage/next.config.ts, common/publish/build.ts | | `HOMEPAGE_PUBLIC_DIR` | `<repo>/homepage/public` | Where `compose homepage` and `source publish` write. | common/bin/compose-homepage.ts, common/publish/source.ts | +| `ARCHILYZER_NO_NETWORK` | unset (no effect) | `1`: nothing in the process reaches a host that is not loopback. A connection (every fetch, http(s) request, WebSocket and UDP datagram) to another host fails with an `ENONETWORK` error naming the door. Spawning yt-dlp, gallery-dl, ffmpeg, curl or wget with such a URL is refused. A browser gets a proxy that does not answer, and Firefox is refused. The Odysee player-page opener refuses by name. Every test script sets it (each package's `test`, `pnpm test:scripts`, `pnpm test:files`) and preloads the guard into every node process the run starts, through `NODE_OPTIONS=--import=…/common/lib/noNetwork.mjs`. A test file run by hand must do the same. | common/lib/noNetwork.mjs (installed by the test harness's `--import`, and by lib/paths.ts, ytdlp/runYtdlp.ts, social/playwrightRuntime.ts on import), common/ytdlp/storedUrlPageOpen.ts, common/controller/seeder.ts, scripts/test-files.mjs | +| `ARCHILYZER_NO_NETWORK_LOG` | unset (no log) | A file. Under `ARCHILYZER_NO_NETWORK`, each refused door adds one JSON line to it: the door, the target and the process's argv. It finds the tests that reach for the network even when their code swallows the failure. | common/lib/noNetwork.mjs | +| `DO_NOT_TRACK` | unset | The common opt-out of CLI telemetry. Set to `1` for the run's children when `ARCHILYZER_NO_NETWORK` is on, unless already set. | common/lib/noNetwork.mjs | +| `HYPERFRAMES_NO_TELEMETRY` | unset (HyperFrames sends usage telemetry) | `1`: the HyperFrames CLI sends no telemetry. Set to `1` for the run's children when `ARCHILYZER_NO_NETWORK` is on, unless already set. Outside test runs, nothing sets it. | common/lib/noNetwork.mjs (for the HyperFrames CLI umtool renders through) | ## Docker diff --git a/common/controller/seeder.ts b/common/controller/seeder.ts @@ -34,6 +34,7 @@ import WebTorrent, { type Torrent } from "webtorrent"; import { Client as TrackerClient, Server as TrackerServer, type ScrapeData } from "bittorrent-tracker"; import parseTorrent from "parse-torrent"; import type { Paths } from "../lib/paths"; +import { noNetwork } from "../lib/noNetwork.mjs"; import { getSite, siteChannelSlugs } from "../lib/site"; import { readChannelConfig } from "./channels"; import { defaultPlayableRoot, loadPlayableManifest } from "./preparePlayable"; @@ -239,6 +240,9 @@ export async function runSeeder(opts: RunSeederOptions): Promise<void> { natPmp: false, utp: false, webSeeds: false, + // The STUN servers WebRTC would ask are native code's sockets, past the + // process guard: under ARCHILYZER_NO_NETWORK none are named. + ...(noNetwork() ? { tracker: { rtcConfig: { iceServers: [] } } } : {}), }); onLog(`seeder: WebRTC ${WebTorrent.WEBRTC_SUPPORT ? "available" : "NOT available (TCP peers only)"}; sites ${settings.sites.join(", ")}`); diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -221,6 +221,10 @@ const DECLARED: EnvVarDecl[] = [ { name: "ARCHILYZER_OLLAMA_TAG", audience: "docker", default: "`0.40.5`", readBy: "docker-compose.yml", doc: "The `ollama/ollama` image tag the `ollama` profile runs." }, // ── test: harnesses, fakes and test-mode branches ────────────────────── + { name: "ARCHILYZER_NO_NETWORK", audience: "internal", default: "unset (no effect)", readBy: "common/lib/noNetwork.mjs (installed by the test harness's `--import`, and by lib/paths.ts, ytdlp/runYtdlp.ts, social/playwrightRuntime.ts on import), common/ytdlp/storedUrlPageOpen.ts, common/controller/seeder.ts, scripts/test-files.mjs", doc: "`1`: nothing in the process reaches a host that is not loopback. A connection (every fetch, http(s) request, WebSocket and UDP datagram) to another host fails with an `ENONETWORK` error naming the door. Spawning yt-dlp, gallery-dl, ffmpeg, curl or wget with such a URL is refused. A browser gets a proxy that does not answer, and Firefox is refused. The Odysee player-page opener refuses by name. Every test script sets it (each package's `test`, `pnpm test:scripts`, `pnpm test:files`) and preloads the guard into every node process the run starts, through `NODE_OPTIONS=--import=…/common/lib/noNetwork.mjs`. A test file run by hand must do the same." }, + { name: "ARCHILYZER_NO_NETWORK_LOG", audience: "internal", default: "unset (no log)", readBy: "common/lib/noNetwork.mjs", doc: "A file. Under `ARCHILYZER_NO_NETWORK`, each refused door adds one JSON line to it: the door, the target and the process's argv. It finds the tests that reach for the network even when their code swallows the failure." }, + { name: "DO_NOT_TRACK", audience: "internal", default: "unset", readBy: "common/lib/noNetwork.mjs", doc: "The common opt-out of CLI telemetry. Set to `1` for the run's children when `ARCHILYZER_NO_NETWORK` is on, unless already set." }, + { name: "HYPERFRAMES_NO_TELEMETRY", audience: "internal", default: "unset (HyperFrames sends usage telemetry)", readBy: "common/lib/noNetwork.mjs (for the HyperFrames CLI umtool renders through)", doc: "`1`: the HyperFrames CLI sends no telemetry. Set to `1` for the run's children when `ARCHILYZER_NO_NETWORK` is on, unless already set. Outside test runs, nothing sets it." }, { name: "E2E_TEST_ROUTES", audience: "test", default: "off", readBy: "editor/app/api/test/_guard.ts, editor/instrumentation.ts", doc: "`1` opens the editor's `/api/test/*` routes and marks a test server at boot. Set by `editor/playwright.config.ts` on its test server, and by nothing else." }, { name: "E2E_MODE", audience: "test", default: "`start`", readBy: "editor/playwright.config.ts, umtool/playwright.config.ts, scripts/e2e-stamp.mjs", doc: "`start`: the editor and umtool suites run against `next start` from a build `scripts/e2e-stamp.mjs` vouches for, rebuilt through the heavy slot when the tree moved. `dev`: against `next dev`, for iterating on one spec. The export and homepage suites always run `next dev` (static exports) and say so when asked for `start`." }, { name: "E2E_NEXT_DIST_DIR", audience: "test", default: "`.next`", readBy: "editor/next.config.ts, export/next.config.ts", doc: "The editor's build directory for the e2e suite's start mode (`.next/e2e`), so a test build never replaces the `.next` a running editor serves from. Set by `scripts/e2e-stamp.mjs` for its build and by `editor/playwright.config.ts` for its test server — and for the editor suite's export dev server (`.next/e2e-editor`), which then runs beside the export suite's own (Next allows one `next dev` per dist dir)." }, diff --git a/common/lib/noNetwork.d.mts b/common/lib/noNetwork.d.mts @@ -0,0 +1,13 @@ +// Types for ./noNetwork.mjs: the ARCHILYZER_NO_NETWORK switch. +export const NO_NETWORK_ENV: "ARCHILYZER_NO_NETWORK"; +export function noNetwork(env?: Record<string, string | undefined>): boolean; +export function isLoopbackHost(host: string | null | undefined): boolean; +export class NoNetworkError extends Error { + constructor(door: string, target: string); + code: "ENONETWORK"; + door: string; + target: string; +} +export function assertNetworkAllowed(door: string, url: string | URL, env?: Record<string, string | undefined>): void; +export function guardSpawn(file: string, args: readonly string[]): { refuse: string } | { args: string[] }; +export function installNoNetworkGuard(): void; diff --git a/common/lib/noNetwork.mjs b/common/lib/noNetwork.mjs @@ -0,0 +1,331 @@ +// ARCHILYZER_NO_NETWORK=1: NOTHING IN THIS PROCESS REACHES ANOTHER HOST. +// +// The operator's rule is that nothing fetches outside the editor's paced +// paths, and a burst of requests from a test run is exactly what makes a site +// challenge him. Every test harness sets this switch (every package's test +// script, `pnpm test:scripts`, `pnpm test:files`). With it set, the process's +// outward doors refuse before any request is made, and the error names the +// door. The default (unset) changes nothing. +// +// A door is one of: +// - a connection: net.Socket#connect, which every fetch, http(s) request, +// WebSocket and tracker announce in this process goes through, and dgram, +// for UDP trackers. A connection to a host that is not loopback fails with +// the socket's usual `error` event, so a caller handles it like any other +// failed connection. +// - a child process: a networking tool (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 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. +// +// 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. +// +// 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 { syncBuiltinESMExports } from "node:module"; +import net from "node:net"; +import path from "node:path"; +import { promisify } from "node:util"; + +export const NO_NETWORK_ENV = "ARCHILYZER_NO_NETWORK"; + +/** @param {Record<string, string | undefined>} [env] */ +export function noNetwork(env = process.env) { + const v = env[NO_NETWORK_ENV]; + return v !== undefined && v !== "" && v !== "0"; +} + +/** @param {string | null | undefined} host */ +export function isLoopbackHost(host) { + if (host === undefined || host === null || host === "") return true; // node's default host: localhost + const h = String(host).replace(/^\[|\]$/g, "").toLowerCase(); + if (h === "localhost" || h.endsWith(".localhost")) return true; + if (/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h)) return true; + if (h === "::1" || h === "0:0:0:0:0:0:0:1") return true; + if (/^::ffff:127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h)) return true; + return false; +} + +export class NoNetworkError extends Error { + /** @param {string} door @param {string} target */ + constructor(door, target) { + super(`${NO_NETWORK_ENV}=1: ${door} refused (${target}) — nothing in this process may reach another host`); + this.name = "NoNetworkError"; + this.code = "ENONETWORK"; + this.door = door; + this.target = target; + // ARCHILYZER_NO_NETWORK_LOG: every refusal, one JSON line, for a run that + // wants to know which tests reach for the network — including those whose + // code swallows the failure and passes anyway. + const log = process.env.ARCHILYZER_NO_NETWORK_LOG; + if (log) { + try { + appendFileSync(/* turbopackIgnore: true */ log, `${JSON.stringify({ door, target, argv: process.argv.slice(1, 4), cwd: process.cwd() })}\n`); + } catch { + /* the log is a convenience */ + } + } + } +} + +/** The first frame outside this module and node's internals: where a door was asked from. */ +function caller() { + const lines = (new Error().stack ?? "").split("\n").slice(1); + for (const l of lines) { + if (l.includes("noNetwork.mjs") || l.includes("node:") || l.includes("(native)")) continue; + const m = /\(?((?:file:\/\/)?\/[^():]+):(\d+):\d+\)?\s*$/.exec(l); + if (m) return `${path.relative(/* turbopackIgnore: true */ process.cwd(), m[1].replace(/^file:\/\//, ""))}:${m[2]}`; + } + return "unknown caller"; +} + +/** + * A named door's check, before it makes a request: refuses (throws a + * NoNetworkError) when the switch is set and `url`'s host is not loopback. + * @param {string} door what is asking, e.g. "the Odysee player-page opener" + * @param {string | URL} url + * @param {Record<string, string | undefined>} [env] + */ +export function assertNetworkAllowed(door, url, env = process.env) { + if (!noNetwork(env)) return; + let host = ""; + try { + host = new URL(String(url)).hostname; + } catch { + host = String(url); + } + if (!isLoopbackHost(host)) throw new NoNetworkError(door, String(url)); +} + +// --- child processes ---------------------------------------------------------- + +// A networking tool, by its basename (an extension and a version suffix are allowed). +const NETWORK_TOOLS = /^(yt-dlp(_linux|_macos)?|youtube-dl|gallery-dl|ffmpeg|ffprobe|ffplay|curl|wget|streamlink|aria2c|rclone|wrangler|nitter|twitch-dl)(\.(exe|py|sh))?$/; +const BROWSERS = /^(chrome|chromium|chromium-browser|google-chrome(-stable)?|chrome-headless-shell|headless_shell|msedge|brave(-browser)?)$/; +const FIREFOX = /^(firefox(-esr)?|librewolf)$/; +const URL_IN = /\b(?:https?|wss?|rtmps?|rtsp|ftp):\/\/[^\s"'<>]+/gi; +// A proxy nobody listens on: a browser asking another host gets a refused +// connection, and the implicit bypass keeps loopback direct. +const DEAD_PROXY = "--proxy-server=http://127.0.0.1:9"; + +/** @param {string} w */ +const base = (w) => path.basename(String(w)).replace(/\.(cmd|exe)$/i, ""); + +/** The non-loopback URLs a command line names. @param {readonly string[]} words */ +function outwardUrls(words) { + const out = []; + for (const w of words) { + for (const m of String(w).matchAll(URL_IN)) { + try { + if (!isLoopbackHost(new URL(m[0]).hostname)) out.push(m[0]); + } catch { + /* not a URL after all */ + } + } + } + return out; +} + +// Words that run the next word as a command (`xvfb-run chrome …`, `timeout 30 yt-dlp …`). +const WRAPPERS = /^(xvfb-run|env|nice|ionice|timeout|setsid|stdbuf|nohup|systemd-run|sudo|exec|time|chrt|taskset)$/; +const SHELLS = /^(sh|bash|dash|zsh|ash|ksh)$/; + +/** + * The 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. + * @param {readonly string[]} words + * @returns {Array<{ word: string, at: number }>} + */ +function commandWords(words) { + const out = []; + 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 }); + } + }; + 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)) { + const c = words.indexOf("-c", i + 1); + if (c > 0 && words[c + 1] !== undefined) shellString(words[c + 1]); + break; + } + 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; + } + return out; +} + +/** + * What the switch does to one spawn: `{refuse}` with the door, or the argv to + * run (a browser's with the dead proxy added). Pure; exported for its test. + * @param {string} file @param {readonly string[]} args + * @returns {{ refuse: string } | { args: string[] }} + */ +export function guardSpawn(file, args) { + const words = [String(file), ...args.map(String)]; + const commands = commandWords(words); + 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]}` }; + 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) { + if (urls.length) return { refuse: `starting ${base(browser.word)} on ${urls[0]}` }; + const all = [...words]; + // In a shell string the flag cannot be placed; a browser there with no URL asks nothing yet. + if (browser.at >= 0 && !all.some((w) => w.startsWith("--proxy-server="))) all.splice(browser.at + 1, 0, DEAD_PROXY); + return { args: all.slice(1) }; + } + return { args: [...args] }; +} + +/** spawn/execFile-style (file, args?, options?, cb?) → [file, args, rest]. */ +function splitArgs(argList) { + const [file, maybeArgs, ...rest] = argList; + if (Array.isArray(maybeArgs)) return [file, maybeArgs, rest]; + return [file, [], maybeArgs === undefined ? rest : [maybeArgs, ...rest]]; +} + +// exec/execFile carry a custom promisified form (resolving {stdout, stderr}); +// a wrapper keeps it, guarded the same way, or `promisify(execFile)` would +// resolve to stdout alone. +function keepCustomPromisify(guarded, orig, check) { + const custom = orig[promisify.custom]; + if (typeof custom === "function") { + guarded[promisify.custom] = function guardedPromisified(...argList) { + let next; + try { + next = check(argList); + } catch (e) { + return Promise.reject(e); // a promise-returning door refuses as a rejection + } + return custom.apply(this, next); + }; + } + return guarded; +} + +function wrapFileStyle(orig, name) { + const check = (argList) => { + const [file, args, rest] = splitArgs(argList); + const g = guardSpawn(String(file), args); + if ("refuse" in g) throw new NoNetworkError(`child_process.${name} (${caller()})`, g.refuse); + return [file, g.args, ...rest]; + }; + const guarded = function guarded(...argList) { + return orig.apply(this, check(argList)); + }; + return keepCustomPromisify(guarded, orig, check); +} + +function wrapShellStyle(orig, name) { + const check = (argList) => { + // exec runs its command line in /bin/sh: read as the shell would. + const g = guardSpawn("sh", ["-c", String(argList[0])]); + if ("refuse" in g) throw new NoNetworkError(`child_process.${name} (${caller()})`, g.refuse); + return argList; + }; + const guarded = function guarded(...argList) { + return orig.apply(this, check(argList)); + }; + return keepCustomPromisify(guarded, orig, check); +} + +// --- connections --------------------------------------------------------------- + +/** The host a Socket#connect call names, or null for a unix socket / pipe. */ +function connectHost(args) { + let a = args; + if (Array.isArray(a[0])) a = a[0]; // net's own normalized [options, cb] + const first = a[0]; + if (first && typeof first === "object") { + if (first.path) return null; + return first.host ?? first.hostname ?? "localhost"; + } + if (typeof first === "string" && !/^\d+$/.test(first)) return null; // a path + return typeof a[1] === "string" ? a[1] : "localhost"; +} + +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; + // 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. + process.env.npm_config_offline ??= "true"; + process.env.DO_NOT_TRACK ??= "1"; + process.env.HYPERFRAMES_NO_TELEMETRY ??= "1"; + const origConnect = net.Socket.prototype.connect; + net.Socket.prototype.connect = function guardedConnect(...args) { + const host = connectHost(args); + if (host !== null && !isLoopbackHost(host)) { + const port = Array.isArray(args[0]) ? args[0][0]?.port : typeof args[0] === "object" ? args[0]?.port : args[0]; + const err = new NoNetworkError(`a connection (${caller()})`, `${host}:${port ?? "?"}`); + process.nextTick(() => this.destroy(err)); + return this; + } + 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; + if (address !== null && !isLoopbackHost(address)) { + const err = new NoNetworkError(`a UDP datagram (${caller()})`, address); + if (cb) process.nextTick(() => cb(err)); + else process.nextTick(() => this.emit("error", err)); + return; + } + return origSend.apply(this, args); + }; + const origUdpConnect = dgram.Socket.prototype.connect; + dgram.Socket.prototype.connect = function guardedUdpConnect(port, address, ...rest) { + if (typeof address === "string" && !isLoopbackHost(address)) { + const err = new NoNetworkError(`a UDP connect (${caller()})`, `${address}:${port}`); + process.nextTick(() => this.emit("error", err)); + return; + } + return origUdpConnect.call(this, port, address, ...rest); + }; + for (const name of ["spawn", "spawnSync", "execFile", "execFileSync", "fork"]) { + childProcess[name] = wrapFileStyle(childProcess[name], name); + } + for (const name of ["exec", "execSync"]) { + childProcess[name] = wrapShellStyle(childProcess[name], name); + } + // 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. + syncBuiltinESMExports(); +} + +if (noNetwork()) installNoNetworkGuard(); diff --git a/common/lib/noNetwork.test.ts b/common/lib/noNetwork.test.ts @@ -0,0 +1,190 @@ +// ARCHILYZER_NO_NETWORK (lib/noNetwork.mjs): every door refuses a host that is +// not loopback, loopback still works, and with the switch unset nothing changes. +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/noNetwork.test.ts +// +// The "outward" address is 192.0.2.1 (TEST-NET-1, documentation only: nothing +// answers there), so even a broken guard would reach no real site. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { execFileSync, exec, spawn, spawnSync } from "node:child_process"; +import dgram from "node:dgram"; +import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import http from "node:http"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +// This file holds the switch itself, however it is run. +process.env.ARCHILYZER_NO_NETWORK = "1"; +const nn = await import("./noNetwork.mjs"); +nn.installNoNetworkGuard(); + +const OUT = "192.0.2.1"; +const MODULE = fileURLToPath(new URL("./noNetwork.mjs", import.meta.url)); + +const refusedBy = (e: unknown): string => { + const err = e as { code?: string; cause?: { code?: string; message?: string }; message?: string }; + if (err?.code === "ENONETWORK") return err.message ?? ""; + if (err?.cause?.code === "ENONETWORK") return err.cause.message ?? ""; + return ""; +}; + +// A stand-in for a networking tool, named like one: it records that it ran. +async function fakeTool(name: string): Promise<{ bin: string; ran: string; dir: string }> { + const dir = await mkdtemp(path.join(tmpdir(), "no-network-")); + const ran = path.join(dir, "ran"); + const bin = path.join(dir, name); + await writeFile(bin, `#!/bin/sh\necho "$@" >> ${JSON.stringify(ran)}\n`); + await chmod(bin, 0o755); + return { bin, ran, dir }; +} + +test("the switch reads 1 as on, and unset, empty or 0 as off; loopback is every spelling of it", () => { + assert.equal(nn.noNetwork({ ARCHILYZER_NO_NETWORK: "1" }), true); + for (const v of [undefined, "", "0"]) assert.equal(nn.noNetwork({ ARCHILYZER_NO_NETWORK: v }), false); + for (const h of ["localhost", "127.0.0.1", "127.8.9.10", "::1", "[::1]", "::ffff:127.0.0.1", "app.localhost", ""]) assert.equal(nn.isLoopbackHost(h), true, h); + for (const h of [OUT, "odysee.com", "10.0.0.1", "::ffff:192.0.2.1", "localhost.example"]) assert.equal(nn.isLoopbackHost(h), false, h); +}); + +test("door: what children ask by themselves is said off — npm reads its cache only, CLIs send no telemetry", () => { + assert.equal(process.env.npm_config_offline, "true"); + assert.equal(process.env.DO_NOT_TRACK, "1"); + assert.equal(process.env.HYPERFRAMES_NO_TELEMETRY, "1"); +}); + +test("door: fetch to another host is refused before it connects, naming the door", async () => { + await assert.rejects(fetch(`https://${OUT}/x`), (e) => /a connection .* refused \(192\.0\.2\.1:443\)/.test(refusedBy(e))); +}); + +test("door: an http(s) request to another host fails with the socket's error", async () => { + const err = await new Promise<Error>((resolve) => http.get(`http://${OUT}/`).on("error", resolve)); + assert.match(refusedBy(err), /refused \(192\.0\.2\.1:80\)/); +}); + +test("door: a WebSocket to another host closes with an error, never connected", async () => { + const ws = new WebSocket(`wss://${OUT}/announce`); + const ev = await new Promise<string>((resolve) => { + ws.onopen = () => resolve("open"); + ws.onerror = () => resolve("error"); + }); + assert.equal(ev, "error"); +}); + +test("door: a UDP datagram to another host (a UDP tracker) is refused", async () => { + const s = dgram.createSocket("udp4"); + try { + const err = await new Promise<Error | null>((resolve) => s.send("x", 6969, OUT, (e) => resolve(e))); + assert.match(refusedBy(err), /a UDP datagram .* refused \(192\.0\.2\.1\)/); + } finally { + s.close(); + } +}); + +test("loopback is never refused: a test's own server answers", async () => { + const srv = http.createServer((_q, r) => r.end("ok")); + await new Promise<void>((r) => srv.listen(0, "127.0.0.1", () => r())); + try { + const port = (srv.address() as { port: number }).port; + assert.equal(await (await fetch(`http://127.0.0.1:${port}/`)).text(), "ok"); + assert.equal(await (await fetch(`http://localhost:${port}/`)).text(), "ok"); + } finally { + await new Promise<void>((r) => srv.close(() => r())); + } +}); + +test("door: yt-dlp (or ffmpeg, gallery-dl…) spawned for another host is refused — spawn, spawnSync, execFile, exec, execa", async () => { + const yt = await fakeTool("yt-dlp"); + try { + const url = `https://${OUT}/watch?v=x`; + assert.throws(() => spawn(yt.bin, ["--no-playlist", url]), (e) => /spawning yt-dlp for https:\/\/192\.0\.2\.1/.test(refusedBy(e))); + assert.throws(() => spawnSync(yt.bin, [url]), (e) => refusedBy(e) !== ""); + assert.throws(() => execFileSync(yt.bin, [url]), (e) => refusedBy(e) !== ""); + assert.throws(() => exec(`${yt.bin} ${url}`), (e) => refusedBy(e) !== ""); + assert.throws(() => spawnSync("sh", ["-c", `ffmpeg -i ${url} out.mp4`]), (e) => /spawning ffmpeg/.test(refusedBy(e))); + // The repo's yt-dlp runner spawns through execa: the same door. + const { execa } = await import("execa"); + await assert.rejects(execa(yt.bin, [url]), (e) => refusedBy(e) !== ""); + await assert.rejects(readFile(yt.ran, "utf8"), "it never ran"); + // Loopback, and a test's fake named as one (fake-ytdlp.mjs), run. + assert.equal(spawnSync(yt.bin, ["http://127.0.0.1:4000/v"]).status, 0); + const fake = await fakeTool("fake-ytdlp.mjs"); + assert.equal(spawnSync(fake.bin, [url]).status, 0); + await rm(fake.dir, { recursive: true, force: true }); + assert.match(await readFile(yt.ran, "utf8"), /127\.0\.0\.1/); + } finally { + await rm(yt.dir, { recursive: true, force: true }); + } +}); + +test("door: a browser is given a proxy that does not answer; on another host's URL, or Firefox, it is refused", () => { + const g = nn.guardSpawn("/x/ms-playwright/chromium_headless_shell-1/chrome-linux/headless_shell", ["--headless", "--remote-debugging-pipe", "about:blank"]); + assert.ok("args" in g && g.args.includes("--proxy-server=http://127.0.0.1:9"), JSON.stringify(g)); + const own = nn.guardSpawn("/usr/bin/chromium", ["--proxy-server=http://127.0.0.1:3128", "file:///tmp/card.html"]); + assert.ok("args" in own && !own.args.includes("--proxy-server=http://127.0.0.1:9"), "its own proxy is kept"); + assert.ok("refuse" in nn.guardSpawn("google-chrome", ["--headless", "https://odysee.com/@x"])); + assert.ok("refuse" in nn.guardSpawn("/usr/lib/firefox/firefox", ["-headless"])); + // Not a networking tool: untouched. + assert.deepEqual(nn.guardSpawn("node", ["script.mjs", "https://odysee.com/"]), { args: ["script.mjs", "https://odysee.com/"] }); +}); + +test("a tool or browser is one only where it is the command: an argument value is not", () => { + const url = "https://x.com/someone"; + // A fake gallery-dl told which browser's cookies to read starts no Firefox; one told where ffmpeg is runs no ffmpeg. + assert.ok("args" in nn.guardSpawn("/tmp/t/fake-gallery-dl.mjs", ["--cookies-from-browser", "firefox", url])); + assert.ok("args" in nn.guardSpawn("/tmp/t/fake-ytdlp.mjs", ["--cookies-from-browser", "chrome", "--ffmpeg-location", "ffmpeg", url])); + // What a wrapper or a shell runs is a command. + assert.ok("refuse" in nn.guardSpawn("timeout", ["30", "yt-dlp", url])); + assert.ok("refuse" in nn.guardSpawn("xvfb-run", ["-a", "chromium", url])); + assert.ok("refuse" in nn.guardSpawn("sh", ["-c", `cat list | ffmpeg -i ${url} -f null -`])); + assert.ok("refuse" in nn.guardSpawn("bash", ["-c", `FOO=1 nice -n 10 gallery-dl ${url}`])); + const wrapped = nn.guardSpawn("xvfb-run", ["-a", "/usr/bin/chromium", "--headless"]); + assert.ok("args" in wrapped && wrapped.args.includes("--proxy-server=http://127.0.0.1:9")); +}); + +test("promisify(execFile) and promisify(exec) keep their {stdout, stderr} answer, and are guarded", async () => { + const { promisify } = await import("node:util"); + const cp = await import("node:child_process"); + const run = promisify(cp.execFile); + const r = await run("sh", ["-c", "echo hi"]); + assert.equal(r.stdout, "hi\n"); + assert.equal((await promisify(cp.exec)("echo there")).stdout, "there\n"); + await assert.rejects(run("sh", ["-c", `curl https://${OUT}/`]), (e) => /spawning curl/.test(refusedBy(e))); +}); + +test("door: the Odysee player-page opener refuses by name, before any browser", async () => { + const { openPlayerPage } = await import("../ytdlp/storedUrlPageOpen"); + const lines: string[] = []; + const r = await openPlayerPage({ pageUrl: "https://odysee.com/@demo:1/x:1", cdnHost: "player.odycdn.com", signal: new AbortController().signal, onLog: (l) => lines.push(l) }); + assert.equal(r.ok, false); + assert.match(r.error ?? "", /ARCHILYZER_NO_NETWORK=1: the Odysee player-page opener refused/); + assert.match(lines.join(""), /player-page opener refused/); +}); + +test("named doors: assertNetworkAllowed refuses another host and passes loopback; with the switch off it passes all", () => { + assert.throws(() => nn.assertNetworkAllowed("a door", "https://archive.org/x"), /a door refused/); + nn.assertNetworkAllowed("a door", "http://127.0.0.1:3001/api"); + nn.assertNetworkAllowed("a door", "https://archive.org/x", {}); +}); + +test("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" }); + 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" }); + assert.deepEqual(JSON.parse(on), { spawnGuarded: true, connectGuarded: true, status: 0 }); + assert.match(await readFile(yt.ran, "utf8"), /192\.0\.2\.1/, "the tool ran: nothing refused"); + } finally { + await rm(yt.dir, { recursive: true, force: true }); + } +}); diff --git a/common/lib/paths.ts b/common/lib/paths.ts @@ -1,3 +1,6 @@ +// ARCHILYZER_NO_NETWORK=1 (lib/noNetwork.mjs): imported for its effect — with the switch set, this +// process's outward doors refuse before any request. +import "./noNetwork.mjs"; import fs from "node:fs"; import path from "node:path"; import os from "node:os"; diff --git a/common/package.json b/common/package.json @@ -54,6 +54,7 @@ "./lib/montage/voiceMatch.mjs": "./lib/montage/voiceMatch.mjs", "./lib/montage/speakerCheck.mjs": "./lib/montage/speakerCheck.mjs", "./lib/ports.mjs": "./lib/ports.mjs", + "./lib/noNetwork.mjs": "./lib/noNetwork.mjs", "./lib/renderPriority.mjs": "./lib/renderPriority.mjs", "./lib/heavyQueue.mjs": "./lib/heavyQueue.mjs", "./lib/report/drafted.mjs": "./lib/report/drafted.mjs", @@ -85,7 +86,7 @@ "./testing/*": "./testing/*" }, "scripts": { - "test": "tsx --test \"*.test.ts\" \"{lib,controller,jobs,social,ytdlp,components,views,publish,bin,testing}/*.test.ts\" \"{lib,controller,jobs,social,ytdlp,components,views,publish,bin,testing}/*/*.test.ts\" \"{lib,controller,jobs,publish,testing}/*/*/*.test.ts\" \"lib/*/*/*/*.test.ts\"" + "test": "ARCHILYZER_NO_NETWORK=1 NODE_OPTIONS=\"--import=$PWD/lib/noNetwork.mjs $NODE_OPTIONS\" tsx --test \"*.test.ts\" \"{lib,controller,jobs,social,ytdlp,components,views,publish,bin,testing}/*.test.ts\" \"{lib,controller,jobs,social,ytdlp,components,views,publish,bin,testing}/*/*.test.ts\" \"{lib,controller,jobs,publish,testing}/*/*/*.test.ts\" \"lib/*/*/*/*.test.ts\"" }, "dependencies": { "@aws-sdk/client-s3": "^3.1080.0", diff --git a/common/social/playwrightRuntime.ts b/common/social/playwrightRuntime.ts @@ -16,6 +16,9 @@ // an editor server action), then resolve from the running process's directory, // then from the workspace packages that actually install it. +// ARCHILYZER_NO_NETWORK=1 (lib/noNetwork.mjs): imported for its effect — with the switch set, this +// process's outward doors refuse before any request. +import "../lib/noNetwork.mjs"; import { createRequire } from "node:module"; import path from "node:path"; import { pathToFileURL } from "node:url"; diff --git a/common/testing/README.md b/common/testing/README.md @@ -53,7 +53,19 @@ gets no chapter card. glob, so `[slug]` is a character class: no file matches, 0 tests run, and the run exits 0. The package's own `test` script is unaffected (its `app/**/*.test.ts` walks into the directory). For a few files by path, use `pnpm test:files <package> <file>…` (`scripts/test-files.mjs`): it escapes the path and fails a run of 0 -tests. **Do not run a test file with a bare `tsx <file>` instead.** It runs, but outside the test runner +tests. **No test reaches another host: `ARCHILYZER_NO_NETWORK=1`.** Every test script sets it (each package's +`test`, `pnpm test:scripts`, `pnpm test:files`) and preloads `common/lib/noNetwork.mjs` into every node process +the run starts, through `NODE_OPTIONS=--import=…`. Under it, any connection to a host that is not loopback +fails with `ENONETWORK` naming the door, and so does a yt-dlp, ffmpeg, gallery-dl or curl spawn aimed at one. A +browser gets a dead proxy. Loopback fakes keep working. **A test run by hand must export the same two:** + +```sh +ARCHILYZER_NO_NETWORK=1 NODE_OPTIONS="--import=$PWD/common/lib/noNetwork.mjs" tsx --test <file> # from the repo root +``` + +`ARCHILYZER_NO_NETWORK_LOG=<file>` writes one line per refusal, which finds a test whose code swallowed one. + +**Do not run a test file with a bare `tsx <file>` instead.** It runs, but outside the test runner `NODE_TEST_CONTEXT` is unset, and guards keyed on it are off. Under it the Odysee player-page opener (`ytdlp/storedUrlPageOpen.ts`) launches headless Chromium on odysee.com. The two stored-URL editor tests now name an empty `E2E_ODYSEE_PAGE_FIXTURE`, which keeps it closed whichever way they run. diff --git a/common/ytdlp/runYtdlp.ts b/common/ytdlp/runYtdlp.ts @@ -1,3 +1,6 @@ +// ARCHILYZER_NO_NETWORK=1 (lib/noNetwork.mjs): imported for its effect — with the switch set, this +// process's outward doors refuse before any request. +import "../lib/noNetwork.mjs"; import { tierChannelMedia } from "../lib/mediaTier-server"; import path from "node:path"; import { mkdir, readdir, readFile } from "node:fs/promises"; diff --git a/common/ytdlp/storedUrlPageOpen.ts b/common/ytdlp/storedUrlPageOpen.ts @@ -13,6 +13,7 @@ // PAGE_OPEN_PLATFORMS. No cookies, a fresh context each time. import { importPlaywright } from "../social/playwrightRuntime"; +import { assertNetworkAllowed } from "../lib/noNetwork.mjs"; export const PAGE_OPEN_PLATFORMS: readonly string[] = ["odysee"]; @@ -58,6 +59,14 @@ export function abortableWait(ms: number, signal: AbortSignal): Promise<void> { // regardless (the CDN may serve it anyway). export const openPlayerPage: PageOpener = async ({ pageUrl, cdnHost, signal, onLog }) => { const mediaStatuses: number[] = []; + // ARCHILYZER_NO_NETWORK (lib/noNetwork.mjs), first and by name: set by every + // test harness, it holds however the test file was started. + try { + assertNetworkAllowed("the Odysee player-page opener", pageUrl); + } catch (e) { + onLog(`${(e as Error).message}\n`); + return { ok: false, mediaStatuses, error: (e as Error).message }; + } // NEVER A BROWSER UNDER A TEST RUNNER (release 32 R9). node's runner (and // tsx --test) sets NODE_TEST_CONTEXT in every test file's process: a test // that reaches the real opener — an editor route test running the whole cut — diff --git a/editor/app/api/ops/_read.test.ts b/editor/app/api/ops/_read.test.ts @@ -23,7 +23,8 @@ await corpus.writeSettings({ kind: "remote", enabled: false, priority: 1, - remote: { baseUrl: "http://lan-box.local:3001", token: "never-printed" }, + // Loopback, a port nothing serves: the pool probes even a disabled remote, and a test asks no LAN host. + remote: { baseUrl: "http://127.0.0.1:9", token: "never-printed" }, }, ], }); diff --git a/editor/package.json b/editor/package.json @@ -9,7 +9,7 @@ "start:test": "WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts EXPORT_PUBLIC_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.export-public SETTINGS_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-settings.json EDITOR_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-changelog.md EXPORT_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-export-changelog.md GENERATION_USAGE_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.generation-usage.jsonl YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs next start --port ${PORT:-3011}", "build": "next build", "start": "UV_THREADPOOL_SIZE=${UV_THREADPOOL_SIZE:-16} next start --port ${EDITOR_PORT:-3001}", - "test": "tsx --test \"app/**/*.test.ts\" \"e2e/*.unit.ts\"", + "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 @@ -16,7 +16,7 @@ "build:hub": "tsx ../common/bin/archilyzer.ts build hub", "start": "node scripts/serve-out.mjs out ${EXPORT_DEV_PORT:-3000}", "lint": "eslint", - "test": "tsx --test \"app/**/*.test.ts\"", + "test": "ARCHILYZER_NO_NETWORK=1 NODE_OPTIONS=\"--import=$PWD/../common/lib/noNetwork.mjs $NODE_OPTIONS\" tsx --test \"app/**/*.test.ts\"", "e2e": "node ../scripts/queue-lock.mjs --name e2e-export --estimate 1500 --ports EXPORT_E2E_PORT:3020 -- playwright test", "e2e:hub": "node ../scripts/queue-lock.mjs --name e2e-export --estimate 1500 --ports HUB_PORT:3041 -- playwright test --config playwright.hub.config.ts", "e2e:2origin": "node ../scripts/queue-lock.mjs --name e2e-export --estimate 1500 --ports ORIGIN_B_PORT:4610,HUB_A_PORT:4611 -- playwright test --config playwright.2origin.config.ts", diff --git a/homepage/package.json b/homepage/package.json @@ -14,7 +14,7 @@ "start": "serve out -l ${HOMEPAGE_PORT:-3031}", "start:private": "serve out-private -l ${HOMEPAGE_PRIVATE_PORT:-3032}", "lint": "eslint", - "test": "tsx --test \"app/**/*.test.ts\"", + "test": "ARCHILYZER_NO_NETWORK=1 NODE_OPTIONS=\"--import=$PWD/../common/lib/noNetwork.mjs $NODE_OPTIONS\" tsx --test \"app/**/*.test.ts\"", "e2e": "node ../scripts/queue-lock.mjs --name e2e-homepage --estimate 1500 --ports HOMEPAGE_E2E_PORT:3040 -- playwright test", "e2e:ui": "playwright test --ui", "deploy": "tsx ../common/bin/archilyzer.ts deploy homepage" diff --git a/mcp/package.json b/mcp/package.json @@ -14,7 +14,7 @@ }, "scripts": { "start": "tsx src/index.ts", - "test": "tsx --test src/*.test.ts", + "test": "ARCHILYZER_NO_NETWORK=1 NODE_OPTIONS=\"--import=$PWD/../common/lib/noNetwork.mjs $NODE_OPTIONS\" tsx --test src/*.test.ts", "typecheck": "tsc --noEmit -p tsconfig.json", "bench": "tsx bench/bench.ts", "smoke": "tsx bench/smoke.ts" diff --git a/package.json b/package.json @@ -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": "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/test-files.mjs b/scripts/test-files.mjs @@ -8,7 +8,8 @@ // Next route directory like `[slug]` is a character class: the file matches // nothing, 0 tests run, and it exits 0 — a green run that tested nothing. Here // a path that names a file is escaped to match only itself, and a run whose -// summary says 0 tests is a failure. +// summary says 0 tests is a failure. It runs under ARCHILYZER_NO_NETWORK=1, as +// every test script does. import { spawn } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; @@ -36,7 +37,13 @@ async function main(argv) { const cwd = path.resolve(ROOT, pkg); const args = files.map((f) => (fs.existsSync(path.resolve(cwd, f)) ? literalGlob(f) : f)); const tsx = path.join(ROOT, "node_modules", ".bin", "tsx"); - const child = spawn(tsx, ["--test", ...args], { cwd, stdio: ["ignore", "pipe", "inherit"] }); + // The test harness's switch (common/lib/noNetwork.mjs): nothing the run starts reaches another host. + const env = { + ...process.env, + ARCHILYZER_NO_NETWORK: "1", + NODE_OPTIONS: `--import=${path.join(ROOT, "common", "lib", "noNetwork.mjs")} ${process.env.NODE_OPTIONS ?? ""}`.trim(), + }; + const child = spawn(tsx, ["--test", ...args], { cwd, env, stdio: ["ignore", "pipe", "inherit"] }); let out = ""; child.stdout.on("data", (d) => { out += d; diff --git a/umtool/package.json b/umtool/package.json @@ -8,7 +8,7 @@ "build": "next build", "start": "next start --port ${UMTOOL_PORT:-3050}", "typecheck": "tsc --noEmit", - "test": "tsx --test lib/brandIcon.test.ts lib/privacy.test.ts lib/articles/*.test.ts lib/research/*.test.ts lib/inbox/*.test.ts lib/clips/*.test.ts components/projects/bench/*.test.ts", + "test": "ARCHILYZER_NO_NETWORK=1 NODE_OPTIONS=\"--import=$PWD/../common/lib/noNetwork.mjs $NODE_OPTIONS\" tsx --test lib/brandIcon.test.ts lib/privacy.test.ts lib/articles/*.test.ts lib/research/*.test.ts lib/inbox/*.test.ts lib/clips/*.test.ts components/projects/bench/*.test.ts", "e2e": "node ../scripts/worktree.mjs run -- node ../scripts/queue-lock.mjs --name e2e-umtool --estimate 1500 --prebuild umtool --ports UMTOOL_E2E_PORT:3051,EDITOR_STUB_PORT:3052 -- playwright test" }, "dependencies": {