// WHAT EVERY CHILD PROCESS INHERITS — process-wide (lane network-exits, // review 2, findings 1 and 2). // // 1. NO CHILD EVER GETS A NETWORK EXIT'S CREDENTIAL. At install, every // `NETWORK_EXIT_*` variable is copied into a private in-process map and // DELETED from process.env; lib/networkCredentials-server.ts reads the // map. Every spawn also drops any such name its environment still holds. // 2. ONCE ANY NETWORK POLICY EXISTS (`network.platforms` in settings.json has // a key — or the file cannot be read, which fails safe), NO CHILD INHERITS // A PROXY VARIABLE (any `*_proxy`, either case): every yt-dlp, gallery-dl, // ffmpeg, browser and anything else, in or out of the trial's scope, // cookie-bearing or not, goes out from this machine's own address unless // the network-exit code routes it. The one exception is the routed // listing's dead-proxy backstop (`routedChildEnv`, value DEAD_PROXY). // With NO policy, a child's environment is exactly what it was before // this lane. // // ONE PLACE, AND NO WAY AROUND IT: the hook is on Node's own spawn — // ChildProcess.prototype.spawn, which spawn, execFile, exec, fork, execa, // cross-spawn and Playwright all reach with the final environment // (`envPairs`), however and whenever the caller took its binding. A call site // cannot build its environment another way: whatever it passes is filtered // here. lib/childEnvGuard.gate.test.ts holds the process entries and the // networking modules to importing it. // // THE SYNC API (spawnSync, execSync, execFileSync) IS NOT HOOKED (review 3, // finding 3): it does not pass through the prototype, and wrapping its exports // meant guessing the caller's options argument. Nothing that does networking // spawns synchronously — the repo's sync spawns are git, ffprobe, local ffmpeg, // systemd-run and a version probe — and gate test 5 fails when a networking // tool gains one. A sync child still never sees a credential: it left // process.env at install. // // WHICH SETTINGS FILE (review 3, finding 2): the one the entry names // (setNetworkPolicySettingsFile — the editor, umtool and both CLIs name the // file getPaths() reads), else SETTINGS_FILE, resolved ONCE. No cwd walk: a // module both Next apps bundle must not join cwd-derived paths (finding 1, // scripts/next-build-trace.test.mjs). When no file is named, or it cannot be // read, a policy MAY exist: children get no proxy variable (fail closed), and // the log says so once. // // Plain ESM: umtool's .mjs and the scripts run it under bare node. // Idempotent; per process (the mark is on the prototype and on globalThis, // which Next's two module graphs share). import { ChildProcess } from "node:child_process"; import { readFileSync, statSync } from "node:fs"; const MARK = Symbol.for("archilyzer.childEnvGuard"); const STATE = Symbol.for("archilyzer.childEnvGuard.state"); // A loopback port nothing listens on (1, tcpmux; binding it needs root). export const DEAD_PROXY = "socks5h://127.0.0.1:1"; export const PROXY_ENV_RE = /(?:^|_)proxy$/i; export const CREDENTIAL_ENV_RE = /^NETWORK_EXIT_/; /** @returns {{ creds: Map, settingsFile: string | null, resolved: boolean, said: Set, cache: { mtimeMs: number, size: number, active: boolean } | null }} */ function state() { const g = /** @type {any} */ (globalThis); if (!g[STATE]) g[STATE] = { creds: new Map(), settingsFile: null, resolved: false, said: new Set(), cache: null }; return g[STATE]; } // Move every NETWORK_EXIT_* out of process.env into the private map. export function captureNetworkExitEnv() { const { creds } = state(); for (const k of Object.keys(process.env)) { if (!CREDENTIAL_ENV_RE.test(k)) continue; const v = process.env[k]; if (v !== undefined) creds.set(k, v); delete process.env[k]; } } /** @param {string} name */ export function networkExitEnvValue(name) { captureNetworkExitEnv(); return state().creds.get(name); } // The settings file the policy is read from, named by the entry. /** @param {string} file */ export function setNetworkPolicySettingsFile(file) { const st = state(); st.settingsFile = file; st.resolved = true; st.cache = null; } /** @param {string} line */ function sayOnce(line) { const st = state(); if (st.said.has(line)) return; st.said.add(line); console.error(line); } // Resolved once: the named file, else SETTINGS_FILE (absolute), else null. function resolvedSettingsFile() { const st = state(); if (!st.resolved) { const env = process.env.SETTINGS_FILE; st.settingsFile = env && env.startsWith("/") ? env : null; st.resolved = true; } return st.settingsFile; } // Whether a network policy exists. No file named, unreadable, not JSON: yes // (fail safe). Absent at the named path: no (a fresh install has none). The // CONTENT is re-read when the file's mtime or size changes; the path never is. export function networkPolicyActive() { const file = resolvedSettingsFile(); if (!file) { sayOnce( "childEnvGuard: no settings file was named (setNetworkPolicySettingsFile / SETTINGS_FILE) — a network policy " + "may exist, so no child process gets a proxy variable", ); return true; } let st; try { st = statSync(file); } catch (e) { const code = /** @type {NodeJS.ErrnoException} */ (e).code; if (code === "ENOENT" || code === "ENOTDIR") return false; sayOnce(`childEnvGuard: ${file} could not be read — a network policy may exist, so no child process gets a proxy variable`); return true; } const s = state(); if (s.cache && s.cache.mtimeMs === st.mtimeMs && s.cache.size === st.size) return s.cache.active; let active = true; try { const raw = JSON.parse(readFileSync(file, "utf8")); const platforms = raw && typeof raw === "object" ? raw.network?.platforms : undefined; active = !!platforms && typeof platforms === "object" && Object.keys(platforms).length > 0; } catch { sayOnce(`childEnvGuard: ${file} could not be read — a network policy may exist, so no child process gets a proxy variable`); active = true; } s.cache = { mtimeMs: st.mtimeMs, size: st.size, active }; return active; } /** * Whether a variable may reach a child: never a credential; a proxy variable * only with no policy, or when it is the routed listing's dead backstop. * @param {string} name @param {string} value @param {boolean} active */ function keep(name, value, active) { if (CREDENTIAL_ENV_RE.test(name)) return false; if (active && PROXY_ENV_RE.test(name) && value !== DEAD_PROXY) return false; return true; } /** @param {readonly string[]} pairs */ export function filterEnvPairs(pairs) { const active = networkPolicyActive(); return pairs.filter((p) => { const i = p.indexOf("="); return keep(i < 0 ? p : p.slice(0, i), i < 0 ? "" : p.slice(i + 1), active); }); } /** @param {Record} env */ export function filterEnv(env) { const active = networkPolicyActive(); /** @type {Record} */ const out = {}; for (const [k, v] of Object.entries(env)) if (v !== undefined && keep(k, v, active)) out[k] = v; return out; } // A child's environment with every proxy variable and credential removed, // policy or not (the network-exit code's direct listings). export function envWithoutProxies() { /** @type {Record} */ const out = {}; for (const [k, v] of Object.entries(process.env)) { if (v !== undefined && !PROXY_ENV_RE.test(k) && !CREDENTIAL_ENV_RE.test(k)) out[k] = v; } return out; } // The routed listing's environment: no inherited proxy, no credential, and // every proxy variable (both cases) pointing at DEAD_PROXY — a child that did // not read its stdin config fails instead of listing direct. No credential is // ever in it: the proxy reaches yt-dlp on stdin only. export function routedChildEnv() { const env = envWithoutProxies(); for (const k of ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"]) { env[k] = DEAD_PROXY; env[k.toLowerCase()] = DEAD_PROXY; } return env; } export function installChildEnvGuard() { captureNetworkExitEnv(); const proto = /** @type {any} */ (ChildProcess.prototype); if (proto[MARK]) return; const spawn = proto.spawn; proto.spawn = function guardedSpawn(/** @type {any} */ options) { if (options && Array.isArray(options.envPairs)) options.envPairs = filterEnvPairs(options.envPairs); // A credential put back into process.env since (Next's dev .env reload) // was filtered out above; take it out of process.env again. captureNetworkExitEnv(); return spawn.call(this, options); }; proto[MARK] = true; } installChildEnvGuard();