// 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 spawned for another host is refused // (the spawn throws). The tools are yt-dlp, gallery-dl, curl, wget, // streamlink and git when a URL or `host:path` names one; ffmpeg and // ffprobe by their inputs and output only; ssh, scp and rsync by their // destination; gh always; pip, uv and kin when they install. A tool counts // only where it is the COMMAND (the executable, what a wrapper or a shell // string runs, `shell: true` included), so `--cookies-from-browser firefox` // and a test's `fake-ytdlp.mjs` pass. A browser is given a proxy that does // not answer, so loopback and file:// pages still load; Playwright reaches // its browser this way too. Firefox is refused. A child given an // environment of its own gets the switch and this module's preload put // back in. npm, pnpm and npx run with `npm_config_offline=true`; telemetry // is opted out (DO_NOT_TRACK, HYPERFRAMES_NO_TELEMETRY). // - a worker thread: each one runs this module first. // - 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. A loopback NAME's lookup is checked as well: a custom // `lookup` or a hosts file cannot map it elsewhere. // // It installs itself when this module is imported with the switch set. The // harness preloads it (`NODE_OPTIONS=--import=…`), and the door modules // import it too, so a test run is covered however it is started. Outside a // test run (no NODE_TEST_CONTEXT, no preload), installing says so on stderr, // and the editor's and umtool's boot say it again. // // KNOWN LIMITS — what a JS guard cannot see: // - a unix socket (or a named pipe) is never refused. A local proxy listening // on one could carry a request out. // - native code's own sockets: node-datachannel's WebRTC (STUN/ICE, peer // traffic), and any addon. The seeder names no STUN servers under the // switch, which is the one such path the repo has. // - `dns.resolve*` queries (a lookup before a REFUSED connection never happens). // - a process this one did not start, and what a non-node child starts. // // 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 dns from "node:dns"; import { syncBuiltinESMExports } from "node:module"; import net from "node:net"; import path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { promisify } from "node:util"; import workerThreads from "node:worker_threads"; export const NO_NETWORK_ENV = "ARCHILYZER_NO_NETWORK"; /** @param {Record} [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} [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|curl|wget|streamlink|aria2c|rclone|wrangler|nitter|twitch-dl|git)(\.(exe|py|sh))?$/; // ffmpeg and its kin: only an INPUT (`-i`) or the output names a host; a URL in // a -metadata comment, a drawtext or -headers for a local input asks nothing. const FFMPEG_KIN = /^(ffmpeg|ffprobe|ffplay)$/; // Always another host unless what they are pointed at is loopback. const REMOTE_SHELLS = /^(ssh|scp|sftp|rsync|mosh)$/; // Network by nature, whatever the arguments (but `--version`/`--help`). const ALWAYS_NETWORK = /^(gh|hub|glab)$/; // Installers: refused when the subcommand fetches. // (npm, pnpm, yarn and npx are given npm_config_offline=true instead: they read their cache.) const INSTALLERS = /^(pip|pip3|uv|pipx|bun|cargo|go)$/; const INSTALL_VERBS = new Set(["install", "i", "add", "download", "sync", "lock", "update", "upgrade", "up", "dlx", "exec", "x", "create", "init", "get", "fetch", "publish", "login"]); const PYTHON = /^python(\d(\.\d+)?)?$/; 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 COMMANDS of a command line — the executable, what a wrapper runs, the * first word of a shell string and of each of its pipeline stages — each with * the words that follow it, and 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, args: string[] }>} */ function commandWords(words) { const out = []; const skippable = (t) => /^\w+=/.test(t) || /^-/.test(t) || /^\d+[smhd]?$/.test(t); 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 && (WRAPPERS.test(base(toks[i])) || skippable(toks[i]))) i += 1; if (!toks[i]) continue; if (SHELLS.test(base(toks[i])) && toks[i + 1] === "-c") { shellString(toks.slice(i + 2).join(" ")); continue; } out.push({ word: toks[i], at: -1, args: toks.slice(i + 1) }); } }; let i = 0; while (i < words.length) { const w = words[i]; const b = base(w); if (SHELLS.test(b)) { out.push({ word: w, at: i, args: words.slice(i + 1) }); const c = words.indexOf("-c", i + 1); if (c > 0 && words[c + 1] !== undefined) shellString(words[c + 1]); break; } out.push({ word: w, at: i, args: words.slice(i + 1) }); 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 && skippable(words[i])) i += 1; } return out; } const GIT_NETWORK = new Set(["clone", "fetch", "pull", "push", "ls-remote", "remote", "submodule", "archive"]); /** `user@host:path` / `host:path` (scp, rsync, git): the host, or null. */ function scpHost(w) { if (/^[a-z][\w+.-]*:\/\//i.test(w) || w.startsWith("/") || w.startsWith(".")) return null; const m = /^([^@\s/]+@)?(\[[^\]]+\]|[^:\s/@]+):/.exec(w); if (!m) return null; return m[1] && !/[.@]/.test(m[2]) ? `${m[1]}${m[2]}` : m[2]; } // ssh's options that take a value (so the destination is found past them). const SSH_VALUE_OPTS = new Set(["-b", "-c", "-D", "-E", "-e", "-F", "-I", "-i", "-J", "-L", "-l", "-m", "-O", "-o", "-p", "-Q", "-R", "-S", "-W", "-w", "-P"]); /** Why one command reaches another host, or null. @param {{ word: string, args: string[] }} c */ function outwardReason(c) { const b = base(c.word); const urls = outwardUrls(c.args); if (NETWORK_TOOLS.test(b)) { if (b === "git") { // Only git's network commands, by a URL or `user@host:path` among their // arguments: `git show :` and `HEAD:file` are revisions, and a // URL in a commit message asks nothing. (A named remote — `git fetch // origin` — cannot be judged from the command line.) const sub = c.args.find((w) => !w.startsWith("-")); if (!GIT_NETWORK.has(sub ?? "")) return null; if (urls.length) return `spawning git ${sub} for ${urls[0]}`; const remote = c.args.map(scpHost).find((h) => h && !isLoopbackHost(h.replace(/^[^@]*@/, "")) && /[.@]|^\[/.test(h)); return remote ? `spawning git ${sub} for ${remote}` : null; } if (urls.length) return `spawning ${b} for ${urls[0]}`; return null; } if (FFMPEG_KIN.test(b)) { // The inputs (`-i` values, concat:/protocol inputs included) and the last word (the output, or ffprobe's input). const judged = c.args.filter((w, i) => c.args[i - 1] === "-i"); if (c.args.length) judged.push(c.args[c.args.length - 1]); const u = outwardUrls(judged); return u.length ? `spawning ${b} for ${u[0]}` : null; } if (REMOTE_SHELLS.test(b)) { if (b === "ssh" || b === "mosh" || b === "sftp") { let dest = null; for (let i = 0; i < c.args.length; i += 1) { const w = c.args[i]; if (SSH_VALUE_OPTS.has(w)) i += 1; else if (!w.startsWith("-")) { dest = w; break; } } if (dest === null) return null; const host = dest.replace(/^ssh:\/\//, "").replace(/^[^@]*@/, "").replace(/:\d+$/, ""); return isLoopbackHost(host) ? null : `spawning ${b} to ${host}`; } const remote = c.args.map(scpHost).find((h) => h && !isLoopbackHost(h.replace(/^[^@]*@/, ""))); if (remote) return `spawning ${b} to ${remote}`; return urls.length ? `spawning ${b} for ${urls[0]}` : null; } if (ALWAYS_NETWORK.test(b)) { return c.args.every((w) => /^(--version|-v|--help|-h|help|version)$/.test(w)) ? null : `spawning ${b} (it always asks its service)`; } if (INSTALLERS.test(b) || (PYTHON.test(b) && c.args[0] === "-m" && /^(pip|pip3|uv)$/.test(c.args[1] ?? ""))) { const sub = (PYTHON.test(b) ? c.args.slice(2) : c.args).find((w) => !w.startsWith("-")); if (sub && INSTALL_VERBS.has(sub)) return `spawning ${PYTHON.test(b) ? `${b} -m ${c.args[1]}` : b} ${sub} (it fetches packages)`; return urls.length ? `spawning ${b} for ${urls[0]}` : null; } if (PYTHON.test(b) && urls.length) return `spawning ${b} for ${urls[0]}`; return null; } /** * 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); for (const c of commands) { const why = outwardReason(c); if (why) return { refuse: why }; } 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) { const urls = outwardUrls(browser.args); 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] }; } /** A shell command line (exec, or spawn with `shell: true`): what /bin/sh would run. */ export function guardShell(command) { const g = guardSpawn("sh", ["-c", String(command)]); return "refuse" in g ? g : { 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]]; } /** This module, as NODE_OPTIONS can name it whatever the path holds (a file URL: no spaces to quote). */ // (Never thrown at import: a bundler may hand this module an import.meta.url that is not a file URL.) const SELF_PATH = (() => { try { return fileURLToPath(import.meta.url); } catch { return null; } })(); const SELF_URL = SELF_PATH ? pathToFileURL(SELF_PATH).href : String(import.meta.url); const PRELOAD = `--import=${SELF_URL}`; /** NODE_OPTIONS with this module's preload in it (once). */ export function withPreload(nodeOptions) { const cur = nodeOptions ?? ""; return /noNetwork\.mjs/.test(cur) ? cur : `${PRELOAD} ${cur}`.trim(); } /** * The environment a child runs with when its caller gave it one of its own * (`env: {}`): the switch, the preload and the offline/opt-out settings put * back, so a child cannot step outside the guard by being given less. * @param {Record} env */ export function guardedChildEnv(env) { return { ...env, [NO_NETWORK_ENV]: process.env[NO_NETWORK_ENV] || "1", NODE_OPTIONS: withPreload(env.NODE_OPTIONS), npm_config_offline: env.npm_config_offline ?? "true", DO_NOT_TRACK: env.DO_NOT_TRACK ?? "1", HYPERFRAMES_NO_TELEMETRY: env.HYPERFRAMES_NO_TELEMETRY ?? "1", }; } /** The options object among `rest` (the first plain object), and its index. */ function optionsIn(rest) { const at = rest.findIndex((x) => x !== null && typeof x === "object" && !Array.isArray(x)); return at >= 0 ? { at, opts: rest[at] } : { at: -1, opts: null }; } /** `rest` with options.env (when the caller gave one) carrying the guard. */ function guardOptions(rest) { const { at, opts } = optionsIn(rest); if (!opts || !opts.env || typeof opts.env !== "object") return rest; const next = [...rest]; next[at] = { ...opts, env: guardedChildEnv(opts.env) }; return next; } // 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 { opts } = optionsIn(rest); // `shell: true`: the file and its arguments are one command line for /bin/sh. const g = opts?.shell ? guardShell([file, ...args].join(" ")) : guardSpawn(String(file), args); if ("refuse" in g) throw new NoNetworkError(`child_process.${name} (${caller()})`, g.refuse); return [file, opts?.shell ? args : g.args, ...guardOptions(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 = guardShell(argList[0]); if ("refuse" in g) throw new NoNetworkError(`child_process.${name} (${caller()})`, g.refuse); return [argList[0], ...guardOptions(argList.slice(1))]; }; const guarded = function guarded(...argList) { return orig.apply(this, check(argList)); }; return keepCustomPromisify(guarded, orig, check); } // --- worker threads --------------------------------------------------------------- // A worker is a fresh module graph: neither the preload nor this process's // patches reach it. Each one runs this module first (it installs itself, the // worker seeing the switch), then its own code. function guardWorkers() { const Orig = workerThreads.Worker; class GuardedWorker extends Orig { constructor(filename, options = {}) { const opts = { ...options }; if (opts.env && typeof opts.env === "object") opts.env = guardedChildEnv(opts.env); const guard = SELF_PATH ? `require(${JSON.stringify(SELF_PATH)});\n` : ""; let code; if (opts.eval) { code = guard + String(filename); } else { const href = filename instanceof URL ? filename.href : /^(file|data):/.test(String(filename)) ? String(filename) : pathToFileURL(path.resolve(String(filename))).href; code = `${guard}import(${JSON.stringify(href)}).catch((e) => { setImmediate(() => { throw e; }); });\n`; } super(code, { ...opts, eval: true }); } } workerThreads.Worker = GuardedWorker; } // --- 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"; } /** The address a dgram send names, by argument position — or null (a connected socket's send). */ function sendAddress(args) { const [, a1, a2, a3, a4] = args; // send(msg, offset, length, port, address?, cb?) if (typeof a1 === "number" && typeof a2 === "number" && a3 !== undefined && typeof a3 !== "function") { return typeof a4 === "string" ? a4 : null; } // send(msg, port, address?, cb?) if (typeof a1 === "number" || (typeof a1 === "string" && /^\d+$/.test(a1))) return typeof a2 === "string" ? a2 : null; return null; // send(msg[, offset, length], cb?): the socket's connected peer (its connect was guarded) } /** A lookup whose answers are checked: a name may not resolve to another host. */ function checkedLookup(lookup, host) { return function guardedLookup(name, options, cb) { const done = typeof options === "function" ? options : cb; const opts = typeof options === "function" ? {} : options; return lookup(name, opts, (err, address, family) => { if (err) return done(err); const all = Array.isArray(address) ? address.map((a) => a.address) : [address]; const away = all.find((a) => !isLoopbackHost(a)); if (away) return done(new NoNetworkError(`a connection's lookup (${host})`, `${name} → ${away}`)); return done(null, address, family); }); }; } 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() { if (installed) return; installed = true; // 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) 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 // (PostHog, on every render). And every node child preloads this module. // Children inherit this environment. process.env.npm_config_offline ??= "true"; process.env.DO_NOT_TRACK ??= "1"; process.env.HYPERFRAMES_NO_TELEMETRY ??= "1"; process.env.NODE_OPTIONS = withPreload(process.env.NODE_OPTIONS); 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; } // A loopback NAME is looked up: its answers are checked too (a custom // `lookup`, or a hosts file, mapping it elsewhere). if (host !== null && net.isIP(String(host).replace(/^\[|\]$/g, "")) === 0) { const normalized = Array.isArray(args[0]); const o = normalized ? args[0][0] : args[0]; if (o && typeof o === "object") { const next = { ...o, lookup: checkedLookup(o.lookup ?? dns.lookup, String(host)) }; if (normalized) { const arr = [next, ...args[0].slice(1)]; for (const k of Object.getOwnPropertySymbols(args[0])) arr[k] = args[0][k]; return origConnect.apply(this, [arr, ...args.slice(1)]); } return origConnect.apply(this, [next, ...args.slice(1)]); } } 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 address = sendAddress(args); 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); } guardWorkers(); // ESM named imports of node builtins are live bindings of their CJS // exports: this makes `import { spawn } from "node:child_process"` and // `import { Worker } from "node:worker_threads"`, done anywhere, before or // after, see the guarded ones. syncBuiltinESMExports(); } if (noNetwork()) installNoNetworkGuard();