commit a81051b9a44607e3edf15cd3cdd4406733d9717e
parent de7807f0024a1e0a1bf59c38db5fe29cdadc29c7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 21 Nov 2026 18:21:07 -0500
Merge lane/network-exits: named network exits for logged-out channel listings (trial)
Proxy exits are named in settings; a channel's exit is sticky; a request carrying cookies or a login
never leaves the home address; a proxy that does not answer fails the request, never a silent fallback.
The trial routes only two platforms' channel listings. Credentials live in a key file and reach no log,
argv, record or child environment. With no policy configured nothing changes.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
61 files changed, 5987 insertions(+), 38 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -196,8 +196,10 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `tts` | tts speaks a line with a local text-to-speech engine and a STOCK voice, as a job on the `tts` queue: {"text": "..."} or {"file": "/abs/script.txt"} (UTF-8, at most 20,000 characters), "engine" (kokoro \| orpheus \| espeak-ng), "voice" (one of the engine's stock voices; kokoro: af\_heart, bm\_george, ...; orpheus: leah, zac, ...), "speed" (0.5-2; orpheus has none) — defaults from settings.tts (kokoro, af\_heart, 1) — and "out" (an absolute .wav path the result is copied to, never inside the corpus). Orpheus also takes "tuning" ({"temperature": 0.1-1.5, "top\_p": 0.05-1, "top\_k": 0-200, "min\_p": 0-0.5, "repeat\_penalty": 1-2, "takes": 1-6}, any of them; the rest its defaults) and "reading" (0-99999; 0 = the first): the same words read again differently, a new cached file; kokoro and espeak-ng ignore both and say so in the result's "note". The expressive tags <laugh> <chuckle> <sigh> <cough> <sniffle> <groan> <yawn> <gasp> are performed by orpheus and stripped for the others; any other <...> is refused. Numbers, years, money and times are spoken (2024: "twenty twenty-four"). The result is {wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate, speed, disclosure} (orpheus: also tuning, reading and seedBase, every value it was made with): wav is the 48 kHz mono WAV the editor wrote (out, or its cache), disclosure the line a narrated export carries. The same ask again is answered from the cache (cached: true, no engine run). Kokoro and orpheus need `archilyzer tts setup [--engine orpheus]` first; orpheus runs on the GPU (a local llama-server the editor starts and stops) and waits while a transcription holds it. With --wait the result is printed on stdout. | `pnpm ops tts --json '{"text":"In 2024 the archive spoke."}' --wait`<br>`pnpm ops tts --json '{"file":"/abs/script.txt","voice":"bm_george","out":"/abs/line.wav"}' --wait`<br>`pnpm ops tts --json '{"text":"Read it again.","engine":"orpheus","reading":1,"tuning":{"temperature":0.7}}' --wait` |
| `voice-enhance` | voice-enhance cleans a speech recording up (denoise, soften the room, level it) as a job on the `voice` queue, behind the heavy slot: {"file": "/abs/take.wav", "out": "/abs/clean.wav"} (never inside the corpus; 48 kHz mono, exactly as long as the input), "engine" (deepfilternet \| rnnoise; settings.voice), "params" (the engine's knobs: lufs, highpass, attenLimDb, postFilter, mix), "parts" (\[{file, out}\], a take recorded part by part). deepfilternet needs `archilyzer voice setup --engine deepfilternet`; rnnoise needs nothing. The result is {op, engine, wav, seconds, samples, sampleRate, engineMs, durationMs, waitedMs, gainDb, params, parts?, synthetic}; with --wait it is printed on stdout. | |
| `voice-convert` | voice-convert keeps a recording's performance (timing, pitch contour) and swaps its timbre for a STOCK synthetic voice, as voice-enhance's job: the same body plus "voice" — "<tts engine>:<stock voice>" (orpheus:zac, orpheus:leah, kokoro:am\_michael, ...; settings.voice.convert.target); a file, a path or a recording is REFUSED as a target (no real person's voice) — and "engine" (openvoice \| seed-vc, each installed by `archilyzer voice setup --engine <id>`). "pitch" is where the result's pitch comes from (settings.voice.convert.pitch): "target" — the stock voice's own, the read's intonation flattened to it; "source" — the pitch the take was read at (raise your voice and it rises); "contour" — the read's rises and falls, moved as a whole to the stock voice's register. "semitones" (-12 to 12) then moves a followed pitch; left out, a followed pitch takes settings.voice.convert.semitones (0 unless set). source and contour are seed-vc's, on its optional f0 model (`archilyzer voice setup --engine seed-vc --with f0`; slower, 44.1 kHz); openvoice refuses them. The target's reference is synthesized once through the tts op and kept. The result adds target, voice, pitch (semitones and f0 — the medians heard and the move applied — when followed), synthetic: true and the disclosure line. | |
-| `settings` | settings patches settings.json through the editor's one writer: {"patch": {"<top-level key>": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage — the refusal names it); a value the schema would not keep as sent (clamped, dropped), named with what would be saved. Answers the saved values. | `pnpm ops settings --json '{"patch":{"diarization":{"cleanAfterCapture":true}}}'`<br>`pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}'` |
+| `settings` | settings patches settings.json through the editor's one writer: {"patch": {"<top-level key>": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage, network — the refusal names it); a value the schema would not keep as sent (clamped, dropped), named with what would be saved. Answers the saved values. | `pnpm ops settings --json '{"patch":{"diarization":{"cleanAfterCapture":true}}}'`<br>`pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}'` |
| `clear-platform-hold` | clear-platform-hold clears a platform's rate-limit hold, backoff and raised pace, as the lane strip's Clear hold: {"platform"}. Answers the sentence. | |
+| `network` | network writes the named network exits (settings.network) through their one writer, as /settings → Network exits: {"upsertExit": {"id", "label"?, "proxy"?: "socks5h://host:port", "credentials"?: true\|false, "enabled"?}}, {"removeExit": "<id>"} (also out of every policy), {"exits": \[...\]} (the whole list, stored form {id, label, scheme, host, port, credentials, enabled}), {"platforms": {"<platform>": {"exits": \[ids, "direct" allowed\], "mode": "sticky"} \| null}}, {"jars": {...}}, {"echoUrl": "<url>" \| ""}, {"credentialsFile": "<path>"}, {"startupProbe": true\|false}. CREDENTIALS ARE NEVER A SETTING: a proxy URL with user:password in it is refused; give the exit "credentials": true and put NETWORK\_EXIT\_<ID>=user:password (percent-encoded) in the mode-600 file network.credentialsFile names (default ~/.config/archilyzer/network-exits.env), or in the environment. THE TRIAL routes only rumble and twitch LISTINGS: any other platform or request kind, and any cookie jar given an exit, is refused whole, every problem named. A channel's exit is a stable hash of its slug over the enabled exits, recorded on its first listing; a recorded exit that is disabled or removed FAILS that channel's listings until network-exit moves it, and a policy whose exits are all disabled fails every listing ("direct" only when the policy names it). One job keeps one exit for every page. Once any policy exists no child process inherits a proxy variable, and NETWORK\_EXIT\_\* never reaches a child. A listing that carries a login (cookies, a header, a token, a config file) goes direct; a 429 or bot check rests that exit (its channels wait); a proxy that does not answer, unreadable settings, missing credentials, or a yt-dlp output that does not show the proxy fail the listing — never a fallback to direct. Not a disguise: no fingerprint or user-agent changes, and a login never moves. get network \[--probe\] reports each exit (no secret in it), the rests, the channels per exit and the 1- and 7-day counts; --probe asks each proxy to answer (and fetches network.echoUrl through it only when set). The startup probe only connects to each proxy (startupProbe: false turns it off). | `pnpm ops network --json '{"upsertExit":{"id":"exit-a","proxy":"socks5h://nl-ams-wg-socks5-001.relays.mullvad.net:1080"}}'`<br>`pnpm ops network --json '{"platforms":{"rumble":{"exits":["direct","exit-a","exit-b"],"mode":"sticky"}}}'`<br>`pnpm ops network --json '{"startupProbe":false}'` |
+| `network-exit` | network-exit reassigns one channel's exit: {"slug", "exit"} (an enabled exit of its platform's policy, or "direct"). The only way a channel moves besides its exit being removed or disabled. | `pnpm ops network-exit --json '{"slug":"demo-rumble","exit":"exit-b"}'` |
| `recheck-service` | recheck-service asks a service whose cookie refresh alert is up ONE request through its own path, as the dashboard banner's Recheck: {"service"} ("rumble", "youtube", "odysee", "archive.today", "x", "instagram" or a forum host). Waits for it: {jobId, result: "clean" \| "stale" \| "failed", message}; "clean" clears the alert (and a yt-dlp service's backoff, as any clean request). For "x" it sends X NO request: clean when the login on disk was renewed after the alert (Refresh cookies on /cookies) — for a jar-age alert, when the jar is within social.x.maxCookieAgeMinutes. The For "instagram" it sends Instagram NO request either and is the operator's word that its check is passed: it clears the alert, and the next Instagram job raises it again if it was not. The timer never asks Instagram. The editor also rechecks by itself on a timer (settings.serviceCookies.recheckIntervalMinutes, default 180, 0 = off; `pnpm ops settings --json '{"patch":{"serviceCookies":{"recheckIntervalMinutes":0}}}'`). Asked while a recheck or another press for the service runs (a click, the dashboard's, the timer's): refused, 409 {busy: true}, never queued. dismiss-service clears a service's cookie alert by hand: {"service"}. x-session marks the X account's state by hand: {"accountState": "suspended" \| "ok", "note"?}. While it is suspended, check-post- availability and capture-posts with screenshots on X (the jobs that record a post as deleted or unavailable) are refused, because a suspended account's answers are thinned; every other X job logs it. get x-session and /cookies show it as the account's alert. Nothing is asked of X. Answers {account: {state, note?, at, by}}. {"clearStop": true, "confirm": true, "note"?} is "Clear the X stop": the one way X's 15-minute stop after a rate limit or a bot check ends early (a clean answer or clear-platform-hold never ends it). Without "confirm" it clears nothing and answers 409 with what it risks; each clear is logged in .jobs/x-stop-cleared.jsonl. rerun-service-jobs retries every job a service's cookie alert stopped, once it is OK again: {"service"} -> {jobIds, skipped}. --wait follows them. | `pnpm ops recheck-service --json '{"service":"rumble"}'`<br>`pnpm ops recheck-service --json '{"service":"x"}'` |
| `dismiss-service` | — | |
| `x-session` | — | `pnpm ops x-session --json '{"accountState":"suspended","note":"read-only since the 21st"}'`<br>`pnpm ops x-session --json '{"accountState":"ok"}'`<br>`pnpm ops x-session --json '{"clearStop":true,"confirm":true,"note":"checked by hand"}'` |
@@ -268,6 +270,7 @@ Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait]
pnpm ops job wait <id>... [--wait-timeout <seconds>]
pnpm ops get settings [<key>]
pnpm ops get storage | sites | workers | auto-queue | scheduler
+ pnpm ops get network [--probe]
pnpm ops get saved-alternates [<slug>]
pnpm ops get compaction-review [<slug>]
pnpm ops get kept-originals [<slug>]
diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md
@@ -62,6 +62,8 @@ Tokens, credentials and knobs a running process reads. Most configuration is not
| `ANTHROPIC_API_KEY` | unset (the API key file is read instead) | The Claude API key for report and video generation on the API (release 27): read first, before the mode-600 key file the generation settings name. Sent only to the Messages API in `x-api-key`; never logged, and never in an error, a job record or a transcript. | common/lib/llm/anthropic.ts |
| `ARCHIVE_ORG_S3_ACCESS` | unset (the S3 key file is read instead) | archive.org's S3 access key for Save Page Now (release 37): read first, with `ARCHIVE_ORG_S3_SECRET`, before the mode-600 file `settings.archiveOrg.s3KeyFile` names. Both or neither. Sent only to web.archive.org/save in the `Authorization: LOW <access>:<secret>` header; never logged, and never in an error, a job record or a result. Without keys Save Page Now is off and says why. | common/lib/waybackPages/savePageNow-server.ts |
| `ARCHIVE_ORG_S3_SECRET` | unset (the S3 key file is read instead) | archive.org's S3 secret key for Save Page Now, with `ARCHIVE_ORG_S3_ACCESS` (above). | common/lib/waybackPages/savePageNow-server.ts |
+| `NETWORK_EXIT_*` | unset (the credentials file is read instead) | One per exit, `NETWORK_EXIT_<ID>`: a network exit's proxy credentials (lane network-exits), `user:password`, each part percent-encoded; `<ID>` is the exit id upper-cased with `-` as `_`. Read first, before the mode-600 file `settings.network.credentialsFile` names. Moved out of the environment when the editor, umtool or the CLI boots, so no child process inherits it; never logged, never in an error, a job record or a result. | common/lib/networkCredentials-server.ts (through common/lib/childEnvGuard.mjs) |
+| `ARCHILYZER_CREDENTIALS_DIR` | unset (only the config directory) | An absolute directory a network exit's credentials file (`settings.network.credentialsFile`) may also sit in, besides `~/.config` and `$XDG_CONFIG_HOME`. | common/lib/networkCredentials-server.ts |
| `SYNC_HEARTBEAT_SECONDS` | `settings.syncScheduler.heartbeatSeconds` | Overrides the editor's in-process sync heartbeat. `0` = no internal timer (tick from cron instead). | editor/app/scheduler/heartbeat.ts |
| `ARCHILYZER_OTS_BIN` | `ots` on PATH, then `~/.local/bin/ots` | The OpenTimestamps `ots` binary that `archilyzer evidence stamp\|upgrade\|verify` (and `evidence pack`'s stamp) run. Without one, the stamp fails and the package is left unstamped (`evidence stamp` it later). | common/bin/evidence-pack.ts |
| `SYNC_TICK_URL` | `http://127.0.0.1:3001/api/scheduler/tick` | Where `archilyzer sync tick` (cron's heartbeat) posts. | common/bin/sync-tick.ts |
@@ -76,7 +78,7 @@ Tokens, credentials and knobs a running process reads. Most configuration is not
| `YTDLP_AUTO_UPDATE` | off | Docker: `1` runs `yt-dlp -U` on every editor boot — on the image's yt-dlp only; an override (`YTDLP_BIN` naming another) is left alone, with a warning. | docker/entrypoint.sh, common/bin/doctor.ts |
| `XDG_STATE_HOME` | `~/.local/state` | The state root: `archilyzer housekeeping` keeps its record of runs in `<it>/archilyzer/housekeeping.json`. | common/bin/housekeeping.ts |
| `ARCHILYZER_HOUSEKEEPING_RECORD` | `$XDG_STATE_HOME/archilyzer/housekeeping.json` | Where `archilyzer housekeeping` appends each run (what each part freed and kept, why a run was skipped, the home filesystem's free space before and after; the last 52 runs). | common/bin/housekeeping.ts |
-| `XDG_CONFIG_HOME` | `~/.config` | Where `wrangler login` keeps its config (`<it>/.wrangler/config/default.toml`); the doctor looks for it there, by path, never reading it. Also where a Linux Firefox may keep its profiles (`<it>/mozilla/firefox`), whose `compatibility.ini` gives the derived Firefox user agent. | common/bin/doctor.ts, common/lib/pagesDeploy.ts, common/lib/browserUserAgent-server.ts |
+| `XDG_CONFIG_HOME` | `~/.config` | Where `wrangler login` keeps its config (`<it>/.wrangler/config/default.toml`); the doctor looks for it there, by path, never reading it. Also where a Linux Firefox may keep its profiles (`<it>/mozilla/firefox`), whose `compatibility.ini` gives the derived Firefox user agent. And one directory a network exit's credentials file may sit in. | common/bin/doctor.ts, common/lib/pagesDeploy.ts, common/lib/browserUserAgent-server.ts, common/lib/networkCredentials-server.ts |
| `APPDATA` | `~/AppData/Roaming` | Windows: where Firefox keeps its profiles (`<it>/Mozilla/Firefox`), whose `compatibility.ini` gives the derived Firefox user agent. Set by Windows itself. | common/lib/browserUserAgent-server.ts |
| `YTDLP_SOURCE_DIR` | `/opt/yt-dlp-src` | Docker: where `/usr/local/bin/yt-dlp-from-source` finds the yt-dlp source tree it runs with the image's python. | docker/yt-dlp-from-source.sh |
| `DOCKER_BIN` | `docker` | The container engine for docker-mode builds (e.g. `podman`). | common/publish/build.ts |
diff --git a/OPERATING.md b/OPERATING.md
@@ -235,6 +235,91 @@ pnpm ops dismiss-service --json '{"service":"rumble"}'
Recheck on the dashboard.` `archilyzer doctor` lists it under "service cookies".
- The state is `transcripts/.service-cookies.json` (`common/lib/serviceCookies.ts`); never hand-edit it.
+### Network exits: list through other addresses (trial)
+
+```sh
+# two exits (worked example: Mullvad — while this machine is connected to the VPN, each WireGuard relay
+# offers a SOCKS5 proxy on port 1080 at its own hostname, resolvable only inside the tunnel)
+pnpm ops network --json '{"upsertExit":{"id":"nl-ams-1","proxy":"socks5h://nl-ams-wg-socks5-001.relays.mullvad.net:1080"}}'
+pnpm ops network --json '{"upsertExit":{"id":"relay-2","proxy":"socks5h://<another relay hostname>:1080"}}'
+# spread rumble's listings over them, direct kept in the pool as the comparison
+pnpm ops network --json '{"platforms":{"rumble":{"exits":["direct","nl-ams-1","relay-2"],"mode":"sticky"}}}'
+pnpm ops get network --probe # each proxy answers? (+ the address, with echoUrl set)
+pnpm ops get network # rests, channels per exit, 1/7-day counts
+pnpm ops network-exit --json '{"slug":"demo-rumble","exit":"relay-2"}' # move one channel by hand
+pnpm ops network --json '{"platforms":{"rumble":null}}' # back to direct
+```
+
+- **What it is for**: spreading logged-out listing load over several addresses, and listing a site that
+ does not answer the home address. **Not a disguise**: no fingerprint or user-agent spoofing is added,
+ and a login is never moved between addresses. Sources: https://mullvad.net/en/help/socks5-proxy and
+ https://mullvad.net/en/help/different-entryexit-node-using-wireguard-and-socks5-proxy .
+- **The trial routes only the LISTING (flat-playlist) requests of rumble and twitch.** Downloads,
+ metadata, subtitles, clips, live recordings and every other platform go direct; a policy for anything
+ else, or a cookie jar given an exit, is refused when saved (`TRIAL_SCOPE`, `common/lib/networkExits.ts`).
+- **Rumble channels with the browser clearance cookie stay direct.** A new Rumble channel is made with
+ Firefox's cookies and `cookieMode` "always" (`common/lib/rumbleDefaults.ts`), so its listing carries the
+ Cloudflare clearance — a login, bound to the address it was earned from. On Rumble the trial covers only
+ channels whose listing carries no cookies (`cookieMode` "when-required" or no `cookiesFromBrowser`). In a
+ synthetic example of five Rumble channels (three made with the defaults), two Twitch channels (one with
+ cookies "always") and one YouTube channel, three can be routed: the two cookie-free Rumble channels and
+ the cookie-free Twitch channel (`listingRoutable`, tested in `ytdlp/networkExitListing.test.ts`).
+- **Credentials are never a setting.** An exit is stored as scheme, host, port and `credentials`
+ true/false. A proxy URL with userinfo in it is refused. Put the credentials where the archive keeps its
+ other keys: the environment variable `NETWORK_EXIT_<ID>` (id upper-cased, `-` as `_`; moved out of the
+ environment at boot, so no child process inherits it), else one line `NETWORK_EXIT_<ID>=user:password` in
+ the file `network.credentialsFile` names (default `~/.config/archilyzer/network-exits.env`): under
+ `~/.config`, `$XDG_CONFIG_HOME` or `ARCHILYZER_CREDENTIALS_DIR`, owned by you, mode 600 — anything else is
+ refused. Percent-encode both parts: `my pass#1` is `my%20pass%231`.
+- **Sticky**: a channel's exit is a stable hash of its slug over the platform's enabled exits, chosen on its
+ first listing and recorded in `channels/<slug>/network-exit.json`. Only `network-exit` moves it. A
+ recorded exit that is disabled or removed **fails** that channel's listings, naming the command to
+ reassign it — nothing re-chooses it and nothing sends it direct. `get network` counts the channels on
+ each exit. Removing the platform's policy (`"rumble": null`) sends its channels direct again, on purpose.
+ **A policy whose exits are all disabled fails every listing on that platform** (the exits were turned
+ off but the policy left in place): `direct` is used only when the policy names it.
+- **One job, one exit**: a sync's route is resolved on its first page and kept for every page. If that exit
+ rests mid-walk the sync stops and ends *deferred*; if it is disabled mid-walk, or a later page would carry
+ a login, the sync fails. It never switches exit.
+- **A listing that carries a login goes direct** — cookies by the resolved cookie policy, a cookie file, any
+ `--add-headers`, `--username`/`-u`/`-n`/`--netrc*`, `--extractor-args`, `--config-locations`, `--alias`,
+ `--load-info-json`, an option yt-dlp does not know, or a URL with userinfo in the channel's args. Options
+ are read with yt-dlp's own rules (any unambiguous abbreviation, short clusters, glued values) against its
+ option table (`common/lib/ytdlpOptions.ts`, generated from the installed yt-dlp's parser; a test fails
+ when yt-dlp changes it). A routed listing runs with `--ignore-config`, so no
+ user, system or channel-directory yt-dlp config rides through an exit.
+- **Pacing is unchanged**: the queue gap, the pace, the cooldown and the hold count every exit together —
+ more exits never means more requests per hour.
+- **A 429 or bot check through an exit rests that exit** for the platform, on the platform cooldown's curve;
+ the channels on it wait (their sync ends *deferred* until the rest ends) and never hop. When every exit
+ rests after a 429, the platform cools down as before. A clean listing through the exit ends its rest.
+- **Fail closed**: a proxy that does not answer, refuses, or cannot log in; a settings.json that cannot be
+ read or a network block that does not validate; missing credentials; or a yt-dlp output whose `Proxy map`
+ does not name the exit's proxy — each fails the listing with a sentence naming the exit, and the result
+ is discarded. The routed child gets its proxy on stdin and an environment whose proxy variables all point
+ at a dead loopback port (`NO_PROXY` removed: libcurl applies it even to an explicit proxy), so a child
+ that ignored stdin fails instead of listing direct.
+- **Once any network policy exists, no child process inherits a proxy variable** — every yt-dlp, gallery-dl,
+ ffmpeg, browser, in or out of the trial's scope, cookie-bearing or not (`common/lib/childEnvGuard.mjs`, a
+ hook on Node's own spawn installed by the editor, umtool and the CLI at boot). With no policy, children get
+ the environment they always did. So an inherited `HTTPS_PROXY` no longer carries anything once a policy is
+ saved: one login is never seen from two addresses.
+ **What it costs:** on a machine that needs a proxy to reach the internet at all, saving any policy also
+ takes the proxy from wrangler, git, pnpm, pip, model downloads, docker and the browsers — publishing and
+ installs stop until the policy is removed. The policy is read from the editor's own settings file (every
+ entry names it); if that file cannot be read, a policy is assumed and the log says so once. The sync spawn
+ API is not covered, and nothing networking uses it (a test fails if something starts to). If the guard
+ cannot install, the editor and umtool refuse to start. `socks5h://` has the proxy resolve the hostname; `socks5://` resolves it here.
+ With the VPN down, every preflight asks the home resolver for the relay's name.
+- **Probes**: the startup probe (a minute after boot, when an exit is enabled) only connects to each proxy —
+ no greeting, no destination, no echo; `{"startupProbe": false}` turns it off. The echo URL is fetched only
+ by the operator's `get network --probe`.
+- **Records** store the exit id only (the roster's `lastSweep.exit`, the counts in `transcripts/.network/`).
+ Neither those nor `network-exit.json` are copied into a published site.
+- **Live recordings** (not built): a recording would take its channel's exit once at its start and keep it
+ for every part and reconnect; a dead proxy would end it failed, never continue direct.
+- /settings → **Network exits** has every control above.
+
## Import from archive.org, Odysee, BitChute and the Wayback Machine
```sh
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -24,6 +24,7 @@ A copied example PINS every default it spells — including each lane's `autoQue
| [`livePreclip`](#livepreclip) | object — see below |
| [`liveRecording`](#liverecording) | object — see below |
| [`pacing`](#pacing) | object — see below |
+| [`network`](#network) | object — see below |
| [`downloadFormat`](#downloadformat) | `"auto"` |
| [`sourceVideoQuality`](#sourcevideoquality) | `"original"` |
| [`minFreeDiskGB`](#minfreediskgb) | `5` |
@@ -305,6 +306,58 @@ Default:
}
```
+## `network`
+
+NAMED NETWORK EXITS (lane network-exits): proxies a listing may leave through, a policy per platform queue, and which exit a logged-in request (a cookie jar) is pinned to. Absent or empty = every request goes direct, exactly as before. The trial routes only the listing requests of rumble and twitch, and no cookie jar may leave direct. Written by `pnpm ops network` / `pnpm ops network-exit` and /settings → Network exits, never by `pnpm ops settings`; `pnpm ops get network` reports each exit, its rests and its counts. Proxy credentials are secrets: redacted in every answer, log and record. See common/lib/networkExits.ts and controller/networkExits.ts.
+
+#### `network`
+
+| Key | Default | Description |
+|---|---|---|
+| `exits` | `[]` | NAMED NETWORK EXITS: proxies a fetch may leave through, `[{id, label, scheme, host, port, credentials, enabled}]` (table below). The exit `direct` (no proxy) always exists and is reserved. Written by `pnpm ops network` and /settings → Network exits, never by `pnpm ops settings`. It spreads logged-out listing load over addresses and lets the archive list a site that does not answer the home address; it is not a disguise — no fingerprint or user-agent spoofing is added, and a login never moves between addresses. Worked example, Mullvad: while the machine is connected to the VPN, each WireGuard relay offers a SOCKS5 proxy at its own hostname on port 1080 (`socks5h://nl-ams-wg-socks5-001.relays.mullvad.net:1080`), resolvable only inside the tunnel — https://mullvad.net/en/help/socks5-proxy and https://mullvad.net/en/help/different-entryexit-node-using-wireguard-and-socks5-proxy . |
+| `platforms` | `{}` | Which exits a platform queue's requests may use, keyed by platform: `{exits: [ids], mode: "sticky", kinds: ["listing"]}` (table below). Absent = every request goes direct, exactly as before. THE TRIAL routes only the LISTING (flat-playlist) requests of `rumble` and `twitch`; any other platform or kind is refused when saved; written by hand, it fails every rumble and twitch listing until fixed. Each channel's exit is chosen once, on its first listing, by a stable hash of its slug over the platform's enabled exits and recorded in `channels/<slug>/network-exit.json`; only `pnpm ops network-exit` changes it. A recorded exit that is disabled or removed FAILS that channel's listing (naming the reassignment) — it is never re-chosen and never sent direct; a policy whose exits are all disabled fails every listing on the platform (`direct` is used only when the policy names it). Once any policy exists, no child process inherits a proxy variable (common/lib/childEnvGuard.mjs). One job keeps one exit for all its pages. Pacing stays per platform: the job gap, the pace, the cooldown and the hold count every exit together. A rate limit or bot check through an exit rests that exit for the platform (the platform cooldown's length); its channels' listings wait (the job ends deferred) and never move to another exit; when every exit rests after a rate limit the platform cools down as before. A proxy that does not answer, or a listing whose yt-dlp output does not show the proxy, fails naming the exit — never a fallback to direct. |
+| `jars` | `{}` | A cookie jar's one fixed exit, keyed by jar id (`browser:<spec>`, `file:<path>`, `login:<option>`, `header`, `config`). A request that carries a login is pinned: direct in the trial, never the platform's pool, and a jar's exit is not changed while the jar is fresh. In the trial every assignment is refused: logged-in requests go direct — so a Rumble channel listing with its Firefox clearance cookie (the default for a new Rumble channel) stays direct, and the trial on Rumble covers only cookie-free channels. |
+| `echoUrl` | `""` | An address-echo URL (`http(s)://…`, answering the caller's public address as text) that the operator's `pnpm ops get network --probe` fetches through each exit to show the address it presents. Never fetched by the startup probe. Blank (the default) = no echo request at all. |
+| `credentialsFile` | `"~/.config/archilyzer/network-exits.env"` | The PATH of the mode-600 file holding the exits' credentials, one line per exit with `credentials: true`: `NETWORK_EXIT_<ID>=user:password` (ID upper-cased, `-` as `_`; each part percent-encoded: `my pass#1` is `my%20pass%231`). The environment variable of the same name wins (it is moved out of the environment at boot, so no child process inherits it). An absolute or `~/` path under the user's config directory (`~/.config`, or `$XDG_CONFIG_HOME`) or `ARCHILYZER_CREDENTIALS_DIR`; owned by the user, mode 600. Never the credentials themselves — a value that is not such a path is refused. |
+| `startupProbe` | `true` | A minute after the editor boots, check that each enabled exit's proxy accepts a TCP connection (no SOCKS greeting, no destination, no echo). One line per exit in the server log. false = no connection at boot. |
+
+#### `network.exits[]`
+
+Per entry — each entry spells its own values.
+
+| Key | Description |
+|---|---|
+| `id` | The exit's name in policies, records and `pnpm ops`: lowercase letters, digits and `-`, up to 40, not `direct`. Records store this, never the proxy. |
+| `label` | A display name (defaults to the id). |
+| `scheme` | `socks5h` (the hostname is resolved by the proxy), `socks5` (resolved here), `http` or `https`. `pnpm ops network` also takes the whole as `proxy: "socks5h://host:port"`. |
+| `host` | The proxy's hostname or IP address (letters, digits, `.`, `-`; an IPv6 address in brackets). |
+| `port` | The proxy's port, 1–65535. |
+| `credentials` | Whether the proxy needs a user and password. They are read from `network.credentialsFile` (or its environment variable), never from settings.json; an exit that needs them and has none fails its listings. |
+| `enabled` | Off = the exit is out of every pool; a channel already recorded on it fails its listings until `pnpm ops network-exit` moves it. |
+
+#### `network.platforms.<platform>`
+
+Per entry — each entry spells its own values.
+
+| Key | Description |
+|---|---|
+| `exits` | The exit ids the platform's channels are spread over, `direct` allowed. Disabled exits are skipped. |
+| `mode` | `sticky` (the only mode): a channel keeps its exit; never chosen per request, never moved on a failure. |
+| `kinds` | The request kinds routed (default `["listing"]`). The trial allows `listing` only. |
+
+Default:
+
+```json
+{
+ "exits": [],
+ "platforms": {},
+ "jars": {},
+ "echoUrl": "",
+ "credentialsFile": "~/.config/archilyzer/network-exits.env",
+ "startupProbe": true
+}
+```
+
## `downloadFormat`
Default yt-dlp `-f` download format for every channel that doesn't set its own (ChannelConfig.downloadFormat). "auto" picks per-source: `original` for Odysee (whose HLS rungs are CDN-truncated), `bestaudio/worst` elsewhere. See common/ytdlp/downloadFormat.ts.
diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts
@@ -8,9 +8,16 @@
// loads the AWS SDK and `archilyzer settings example` never opens LMDB. The
// machinery (parser, lookup, usage) is `_cli.ts`; this file is only the table.
+// What every child inherits (lane network-exits): installed before any row
+// can spawn (lib/childEnvGuard.mjs), reading the policy from the same
+// settings file the editor uses.
+import { setNetworkPolicySettingsFile } from "../lib/childEnvGuard.mjs";
+import { getPaths } from "../lib/paths";
import type { Command } from "./_cli";
import { runCli, runIfEntryPoint } from "./_cli";
+setNetworkPolicySettingsFile(getPaths().settingsFile);
+
export const COMMANDS: Command[] = [
{
path: ["index"],
diff --git a/common/controller/checkAvailability.ts b/common/controller/checkAvailability.ts
@@ -35,6 +35,8 @@ import type { Paths } from "../lib/paths";
import { jitterYtdlpSleeps } from "../lib/jitter";
import { jitterMs } from "../lib/jitter";
import "../lib/childKillGuard";
+// What every child inherits (lib/childEnvGuard.mjs; review 2 of lane network-exits).
+import "../lib/childEnvGuard.mjs";
export type CheckAvailabilityMode =
| "resume"
diff --git a/common/controller/networkExits.ts b/common/controller/networkExits.ts
@@ -0,0 +1,742 @@
+// NETWORK EXITS AT RUN TIME (lane network-exits): which exit a channel's
+// listing leaves through, the exits that rest after a rate limit, the counts
+// the trial is judged by, the operator's reassignment and `get network`.
+// The rules and the pure parts are lib/networkExits.ts; the proxy client is
+// lib/networkProxy-server.ts; the one caller that sends requests is the
+// listing in ytdlp/runYtdlp.ts.
+//
+// STATE, all small JSON:
+// channels/<slug>/network-exit.json the channel's sticky exit (who chose it, when)
+// <transcripts>/.network/rests.json per `<platform>/<exit>`: until, fails
+// <transcripts>/.network/usage.json per day per `<platform>/<exit>`: counts
+// <transcripts>/.network/probe.json the last probe's answer per exit
+// None of them ever holds a proxy URL — only exit ids.
+
+import path from "node:path";
+import { readdir } from "node:fs/promises";
+import { readJsonFile, readJsonFileSync, withJsonFileLock, writeJsonAtomic } from "../lib/jsonFile-server";
+import { getPaths, type Paths } from "../lib/paths";
+import type { ChannelConfig } from "../lib/channelConfig";
+import { alwaysCookies, cookieArgs, resolveCookiePolicy, type CookieMode } from "../lib/cookiePolicy";
+import { platformArgs } from "../ytdlp/platformArgs.mjs";
+import { readExitCredentials } from "../lib/networkCredentials-server";
+import { getSettings } from "../lib/settings";
+import { detectPlatform } from "../lib/platform";
+import {
+ DIRECT_EXIT,
+ TRIAL_SCOPE,
+ TRIAL_SCOPE_SENTENCE,
+ exitById,
+ exitPool,
+ NetworkExitError,
+ defaultNetworkSettings,
+ ownProxy,
+ exitDisplay,
+ isRoutable,
+ networkSettingsProblems,
+ proxyUrlOf,
+ requestJar,
+ sanitizeNetwork,
+ secretFragmentsOf,
+ stickyExitFor,
+ type NetworkExit,
+ type NetworkSettings,
+} from "../lib/networkExits";
+import { getThroughProxy, addressInEcho, preflightProxy } from "../lib/networkProxy-server";
+import { nextBackoff, pruneExpired, type PlatformBackoffEntry } from "../jobs/platformBackoff";
+import { platformCooldownRemainingMs } from "../jobs/downloadBackoff";
+import { readChannelConfig } from "./channels";
+
+export const NETWORK_STATE_DIRNAME = ".network";
+export const CHANNEL_EXIT_FILENAME = "network-exit.json";
+
+export const NETWORK_LIMITS_SENTENCE =
+ "Network exits spread logged-out listing load across addresses and let the archive list a site that does " +
+ "not answer the home address. They are not a disguise: no fingerprint or user-agent spoofing is added, and " +
+ "a login is never moved between addresses.";
+
+export function networkStateDir(paths: Paths): string {
+ return path.join(paths.transcriptsDir, NETWORK_STATE_DIRNAME);
+}
+
+function stateFile(paths: Paths, name: string): string {
+ return path.join(networkStateDir(paths), name);
+}
+
+export function channelExitPath(paths: Paths, slug: string): string {
+ return path.join(paths.channelsDir, slug, CHANNEL_EXIT_FILENAME);
+}
+
+function settingsNetwork(): NetworkSettings | undefined {
+ try {
+ return getSettings().network;
+ } catch {
+ return undefined;
+ }
+}
+
+function isObject(v: unknown): v is Record<string, unknown> {
+ return typeof v === "object" && v !== null && !Array.isArray(v);
+}
+
+const key = (platform: string, exit: string) => `${platform}/${exit}`;
+
+// ---------------------------------------------------------------------------
+// THE CHANNEL'S STICKY EXIT
+
+export type ChannelExitRecord = {
+ platform: string;
+ exit: string;
+ // "hash": stickyExitFor chose it; "operator": `pnpm ops network-exit`.
+ by: "hash" | "operator";
+ at: string;
+ previous?: string;
+ reason?: string;
+};
+
+export async function readChannelExitRecord(
+ paths: Paths,
+ slug: string,
+): Promise<ChannelExitRecord | null> {
+ const r = await readJsonFile(channelExitPath(paths, slug));
+ if (!r.ok || !isObject(r.value)) return null;
+ const v = r.value;
+ if (typeof v.platform !== "string" || typeof v.exit !== "string") return null;
+ return {
+ platform: v.platform,
+ exit: v.exit,
+ by: v.by === "operator" ? "operator" : "hash",
+ at: typeof v.at === "string" ? v.at : "",
+ ...(typeof v.previous === "string" ? { previous: v.previous } : {}),
+ ...(typeof v.reason === "string" ? { reason: v.reason } : {}),
+ };
+}
+
+// THE FIRST LISTING CHOOSES; NOTHING ELSE DOES (review 1, finding 5). With
+// no record for this platform the hash chooses over the pool and the choice
+// is written. A record is honoured while its exit is in the pool (or is the
+// operator's `direct`); a recorded exit that is disabled or removed FAILS the
+// listing — it is never re-chosen and never sent direct. Only
+// assignChannelExit (`pnpm ops network-exit`) moves a channel.
+async function stickyChannelExit(
+ paths: Paths,
+ slug: string,
+ platform: string,
+ pool: readonly string[],
+ now: Date,
+): Promise<string> {
+ const file = channelExitPath(paths, slug);
+ return withJsonFileLock(file, async () => {
+ const rec = await readChannelExitRecord(paths, slug);
+ if (rec && rec.platform === platform) {
+ if (pool.includes(rec.exit)) return rec.exit;
+ if (rec.by === "operator" && rec.exit === DIRECT_EXIT) return rec.exit;
+ throw new NetworkExitError(
+ rec.exit,
+ `this channel's recorded network exit "${rec.exit}" is no longer an enabled exit of ${platform} ` +
+ `(enabled: ${pool.join(", ") || "none"}). The ${platform} listing was not sent; a channel is never moved by ` +
+ `itself — reassign it: pnpm ops network-exit --json '{"slug":"${slug}","exit":"<exit or direct>"}'.`,
+ );
+ }
+ const exit = stickyExitFor(slug, pool);
+ const next: ChannelExitRecord = {
+ platform,
+ exit,
+ by: "hash",
+ at: now.toISOString(),
+ ...(rec ? { previous: rec.exit, reason: `the channel moved from ${rec.platform} to ${platform}` } : {}),
+ };
+ await writeJsonAtomic(file, next, { mkdir: true });
+ return exit;
+ });
+}
+
+// ---------------------------------------------------------------------------
+// THE SETTINGS, READ STRICTLY FOR A ROUTE (review 1, finding 5)
+//
+// getSettings() answers defaults for a file it cannot read, which for a route
+// would mean "no policy": direct, silently. The listing reads the file itself:
+// absent = no policy; unreadable, not JSON, or a network block the writers
+// would refuse = the listing FAILS.
+export type StrictNetwork = { ok: true; network: NetworkSettings | undefined } | { ok: false; reason: string };
+
+export function loadNetworkStrict(file: string = getPaths().settingsFile): StrictNetwork {
+ const r = readJsonFileSync(file);
+ if (!r.ok) {
+ return r.reason === "absent"
+ ? { ok: true, network: undefined }
+ : { ok: false, reason: `settings.json could not be read (${r.reason})` };
+ }
+ const raw = isObject(r.value) ? r.value.network : undefined;
+ if (raw === undefined) return { ok: true, network: undefined };
+ const problems = networkSettingsProblems(raw);
+ if (problems.length) return { ok: false, reason: `the network settings do not validate: ${problems.join("; ")}` };
+ return { ok: true, network: sanitizeNetwork(raw) };
+}
+
+// ---------------------------------------------------------------------------
+// THE ROUTE OF ONE LISTING
+
+export type ListingRoute =
+ // No policy for the platform (or the kind is outside the trial, or the
+ // channel's own args carry a --proxy): today's request, untouched.
+ | { kind: "none" }
+ // Under a policy, and direct: a login is pinned, or the channel's exit is
+ // `direct` (the hash chose it from a policy that names it, or the operator).
+ | { kind: "direct"; why: "jar" | "assigned"; jar?: string }
+ // Through an exit: its stored (secret-free) form, and — for the child only —
+ // the proxy URL with its credentials and the exact values to scrub.
+ | { kind: "exit"; exit: NetworkExit; proxyUrl: string; secrets: string[] };
+
+
+// THE JAR'S EXIT. The trial never routes a login: whatever settings.json
+// says (the writers refuse an assignment; a hand edit fails validation), a
+// request carrying one goes direct. Widening this is one deliberate change.
+export const JAR_ROUTING_ALLOWED = false;
+export function jarExit(network: NetworkSettings | undefined, jar: string): string {
+ if (!JAR_ROUTING_ALLOWED) return DIRECT_EXIT;
+ return network?.jars[jar] ?? DIRECT_EXIT;
+}
+
+export async function resolveListingRoute(args: {
+ paths: Paths;
+ slug: string;
+ platform: string;
+ argv: readonly string[];
+ network?: NetworkSettings;
+ now?: Date;
+ env?: Readonly<Record<string, string | undefined>>;
+}): Promise<ListingRoute> {
+ // Only the trial's platforms can be routed; every other listing is today's
+ // without reading anything.
+ if (!isRoutable(args.platform, "listing")) return { kind: "none" };
+ let network = args.network;
+ if (!network) {
+ const strict = loadNetworkStrict(args.paths.settingsFile);
+ if (!strict.ok) {
+ throw new NetworkExitError(
+ DIRECT_EXIT,
+ `${strict.reason}; the ${args.platform} listing was not sent — a listing never goes direct because its ` +
+ `network settings could not be read.`,
+ );
+ }
+ network = strict.network;
+ }
+ const pool = exitPool(network, args.platform, "listing");
+ if (pool === null || ownProxy(args.argv)) return { kind: "none" };
+ const jar = requestJar(args.argv);
+ if (jar && jarExit(network, jar) === DIRECT_EXIT) return { kind: "direct", why: "jar", jar };
+ // A POLICY WITH NO ENABLED EXIT FAILS (review 2, finding 3): `direct` is
+ // used only when the policy NAMES it — never because every exit is off.
+ if (pool.length === 0) {
+ throw new NetworkExitError(
+ DIRECT_EXIT,
+ `network.platforms.${args.platform} has no enabled exit (${network!.platforms[args.platform]!.exits.join(", ")}) — ` +
+ `the exits were turned off but the policy left in place. The ${args.platform} listing was not sent: enable an ` +
+ `exit, list "direct" in the policy, or remove the policy ({"platforms":{"${args.platform}":null}}).`,
+ );
+ }
+ const id = await stickyChannelExit(args.paths, args.slug, args.platform, pool, args.now ?? new Date());
+ if (id === DIRECT_EXIT) return { kind: "direct", why: "assigned" };
+ const exit = exitById(network, id);
+ if (!exit) throw new NetworkExitError(id, `network exit "${id}" is not defined; the ${args.platform} listing was not sent.`);
+ const creds = readExitCredentials(exit, { file: network!.credentialsFile, ...(args.env ? { env: args.env } : {}) });
+ if (!creds.ok) {
+ throw new NetworkExitError(id, `${creds.reason} The ${args.platform} listing was not sent — it never falls back to direct.`);
+ }
+ return { kind: "exit", exit, proxyUrl: proxyUrlOf(exit, creds.creds), secrets: secretFragmentsOf(creds.creds) };
+}
+
+// WHETHER A CHANNEL'S LISTING CAN LEAVE THROUGH AN EXIT AT ALL: on a trial
+// platform and carrying no login (its cookies by the resolved policy, its own
+// args). A Rumble channel made with the defaults carries the Firefox
+// clearance cookie, so it cannot. `global` is settings' cookie pair.
+export function listingRoutable(
+ config: ChannelConfig,
+ global: { cookiesFromBrowser?: string; cookieMode?: CookieMode },
+): boolean {
+ const platform = detectPlatform(config.url) ?? "unknown";
+ if (!isRoutable(platform, "listing")) return false;
+ const argv = [
+ ...cookieArgs(alwaysCookies(resolveCookiePolicy(global, config))),
+ ...platformArgs(detectPlatform(config.url)),
+ ...(config.ytdlpExtraArgs ?? []),
+ ];
+ return requestJar(argv) === null;
+}
+
+// ---------------------------------------------------------------------------
+// RESTS
+
+type RestState = Record<string, PlatformBackoffEntry & { since: number }>;
+
+async function readRests(paths: Paths): Promise<RestState> {
+ const r = await readJsonFile(stateFile(paths, "rests.json"));
+ const out: RestState = {};
+ if (!r.ok || !isObject(r.value)) return out;
+ for (const [k, v] of Object.entries(r.value)) {
+ if (!isObject(v)) continue;
+ const until = Number(v.until);
+ const fails = Number(v.fails);
+ if (!Number.isFinite(until) || !Number.isFinite(fails)) continue;
+ out[k] = { until, fails, since: Number.isFinite(Number(v.since)) ? Number(v.since) : until };
+ }
+ return out;
+}
+
+export async function exitRestUntil(
+ paths: Paths,
+ platform: string,
+ exit: string,
+ now: number = Date.now(),
+): Promise<number | null> {
+ if (exit === DIRECT_EXIT) return null;
+ const e = (await readRests(paths))[key(platform, exit)];
+ return e && e.until > now ? e.until : null;
+}
+
+// A RATE LIMIT OR BOT CHECK THROUGH AN EXIT RESTS THAT EXIT for the
+// platform, on the platform cooldown's own curve (jobs/platformBackoff.ts
+// nextBackoff: 1 min doubling to 30, jittered). `allRest` — every exit of
+// the pool now rests (direct counting as resting while the platform cools
+// down) — is when the caller records the platform's own backoff, as today.
+export async function restExit(
+ paths: Paths,
+ platform: string,
+ exit: string,
+ pool: readonly string[],
+ now: number = Date.now(),
+ rand?: () => number,
+): Promise<{ until: number; allRest: boolean }> {
+ const file = stateFile(paths, "rests.json");
+ const until = await withJsonFileLock(file, async () => {
+ const rests = await readRests(paths);
+ pruneExpired(rests, now);
+ const prev = rests[key(platform, exit)];
+ const next = nextBackoff(prev, now, rand);
+ rests[key(platform, exit)] = { ...next, since: prev && prev.until > now ? prev.since : now };
+ await writeJsonAtomic(file, rests, { mkdir: true });
+ return next.until;
+ });
+ return { until, allRest: await allExitsRest(paths, platform, pool, now) };
+}
+
+export async function allExitsRest(
+ paths: Paths,
+ platform: string,
+ pool: readonly string[],
+ now: number = Date.now(),
+): Promise<boolean> {
+ if (pool.length === 0) return false;
+ const rests = await readRests(paths);
+ for (const exit of pool) {
+ if (exit === DIRECT_EXIT) {
+ const ms = await platformCooldownRemainingMs(platform, paths).catch(() => 0);
+ if (ms <= 0) return false;
+ continue;
+ }
+ const e = rests[key(platform, exit)];
+ if (!e || e.until <= now) return false;
+ }
+ return true;
+}
+
+// A clean listing through the exit forgets its rest (and its escalation).
+export async function clearExitRest(
+ paths: Paths,
+ platform: string,
+ exit: string,
+): Promise<void> {
+ const file = stateFile(paths, "rests.json");
+ await withJsonFileLock(file, async () => {
+ const rests = await readRests(paths);
+ if (!rests[key(platform, exit)]) return;
+ delete rests[key(platform, exit)];
+ await writeJsonAtomic(file, rests, { mkdir: true });
+ });
+}
+
+function clock(ms: number): string {
+ const d = new Date(ms);
+ return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
+}
+
+export function restingSentence(platform: string, exit: string, until: number): string {
+ return (
+ `${platform} exit "${exit}" rests until ${clock(until)} after a rate limit; this channel's listing waits ` +
+ `for it (a channel never moves to another exit on a failure).`
+ );
+}
+
+// The manual Sync gate's notice: the channel's recorded exit rests. Reads
+// only — never chooses or writes an exit.
+export async function listingRestRefusal(
+ paths: Paths,
+ slug: string,
+ url: string | undefined,
+ network: NetworkSettings | undefined = settingsNetwork(),
+ now: number = Date.now(),
+): Promise<{ sentence: string; until: number } | null> {
+ const platform = detectPlatform(url) ?? "unknown";
+ const pool = exitPool(network, platform, "listing");
+ if (!pool) return null;
+ const rec = await readChannelExitRecord(paths, slug);
+ if (!rec || rec.platform !== platform || rec.exit === DIRECT_EXIT || !pool.includes(rec.exit)) return null;
+ const until = await exitRestUntil(paths, platform, rec.exit, now);
+ return until ? { sentence: restingSentence(platform, rec.exit, until), until } : null;
+}
+
+// ---------------------------------------------------------------------------
+// USAGE — the numbers the trial compares against `direct`
+
+export type NetworkUsageCounts = {
+ requests: number;
+ rateLimits: number;
+ botChecks: number;
+ rests: number;
+ proxyFailures: number;
+};
+const COUNT_KEYS: readonly (keyof NetworkUsageCounts)[] = ["requests", "rateLimits", "botChecks", "rests", "proxyFailures"];
+const USAGE_KEEP_DAYS = 8;
+
+function zero(): NetworkUsageCounts {
+ return { requests: 0, rateLimits: 0, botChecks: 0, rests: 0, proxyFailures: 0 };
+}
+
+function dayOf(ms: number): string {
+ return new Date(ms).toISOString().slice(0, 10);
+}
+
+type UsageFile = { days: Record<string, Record<string, NetworkUsageCounts>> };
+
+async function readUsage(paths: Paths): Promise<UsageFile> {
+ const r = await readJsonFile(stateFile(paths, "usage.json"));
+ const out: UsageFile = { days: {} };
+ if (!r.ok || !isObject(r.value) || !isObject(r.value.days)) return out;
+ for (const [day, rows] of Object.entries(r.value.days)) {
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(day) || !isObject(rows)) continue;
+ out.days[day] = {};
+ for (const [k, v] of Object.entries(rows)) {
+ if (!isObject(v)) continue;
+ const c = zero();
+ for (const f of COUNT_KEYS) c[f] = Math.max(0, Math.floor(Number(v[f]) || 0));
+ out.days[day]![k] = c;
+ }
+ }
+ return out;
+}
+
+export async function countNetworkUse(
+ paths: Paths,
+ platform: string,
+ exit: string,
+ delta: Partial<NetworkUsageCounts>,
+ now: number = Date.now(),
+): Promise<void> {
+ const file = stateFile(paths, "usage.json");
+ await withJsonFileLock(file, async () => {
+ const usage = await readUsage(paths);
+ const day = dayOf(now);
+ const row = ((usage.days[day] ??= {})[key(platform, exit)] ??= zero());
+ for (const f of COUNT_KEYS) row[f] += delta[f] ?? 0;
+ const keep = new Set(Array.from({ length: USAGE_KEEP_DAYS }, (_, i) => dayOf(now - i * 86_400_000)));
+ for (const d of Object.keys(usage.days)) if (!keep.has(d)) delete usage.days[d];
+ await writeJsonAtomic(file, usage, { mkdir: true });
+ });
+}
+
+export async function usageOver(
+ paths: Paths,
+ days: number,
+ now: number = Date.now(),
+): Promise<Record<string, NetworkUsageCounts>> {
+ const usage = await readUsage(paths);
+ const out: Record<string, NetworkUsageCounts> = {};
+ for (let i = 0; i < days; i++) {
+ for (const [k, c] of Object.entries(usage.days[dayOf(now - i * 86_400_000)] ?? {})) {
+ const row = (out[k] ??= zero());
+ for (const f of COUNT_KEYS) row[f] += c[f];
+ }
+ }
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// THE OPERATOR'S REASSIGNMENT — `pnpm ops network-exit {slug, exit}`
+
+export class NetworkInputError extends Error {}
+
+export async function assignChannelExit(args: {
+ paths: Paths;
+ slug: string;
+ exit: string;
+ network?: NetworkSettings;
+ now?: Date;
+}): Promise<{ slug: string; platform: string; exit: string; previous: string | null }> {
+ const network = args.network ?? settingsNetwork();
+ const config = await readChannelConfig(args.paths, args.slug);
+ if (!config) throw new NetworkInputError(`Channel "${args.slug}" not found`);
+ const platform = detectPlatform(config.url) ?? config.platform ?? "unknown";
+ const pool = exitPool(network, platform, "listing");
+ if (pool === null) {
+ throw new NetworkInputError(
+ `"${args.slug}" is a ${platform} channel, and ${platform} has no network policy` +
+ (isRoutable(platform, "listing") ? " — set network.platforms." + platform + " first" : ` — ${TRIAL_SCOPE_SENTENCE}`),
+ );
+ }
+ if (args.exit !== DIRECT_EXIT && !pool.includes(args.exit)) {
+ const known = exitById(network, args.exit);
+ throw new NetworkInputError(
+ known
+ ? `exit "${args.exit}" is ${known.enabled ? `not in ${platform}'s policy` : "disabled"} — ${platform}'s enabled exits: ${pool.join(", ") || "none"}`
+ : `no exit "${args.exit}" — ${platform}'s enabled exits: ${pool.join(", ") || "none"} (and "direct")`,
+ );
+ }
+ const file = channelExitPath(args.paths, args.slug);
+ return withJsonFileLock(file, async () => {
+ const rec = await readChannelExitRecord(args.paths, args.slug);
+ const next: ChannelExitRecord = {
+ platform,
+ exit: args.exit,
+ by: "operator",
+ at: (args.now ?? new Date()).toISOString(),
+ ...(rec && rec.exit !== args.exit ? { previous: rec.exit, reason: "reassigned by the operator" } : {}),
+ };
+ await writeJsonAtomic(file, next, { mkdir: true });
+ return { slug: args.slug, platform, exit: args.exit, previous: rec?.exit ?? null };
+ });
+}
+
+// ---------------------------------------------------------------------------
+// THE PROBE AND THE REPORT — `pnpm ops get network [--probe]`
+
+export type ExitProbe = {
+ at: string;
+ reachable: boolean;
+ reason?: string;
+ ms?: number;
+ // The address the echo URL saw through this exit (only with echoUrl set).
+ address?: string | null;
+ echoError?: string;
+};
+
+type ProbeFile = { at: string; exits: Record<string, ExitProbe> };
+
+async function readProbe(paths: Paths): Promise<ProbeFile | null> {
+ const r = await readJsonFile(stateFile(paths, "probe.json"));
+ if (!r.ok || !isObject(r.value) || !isObject(r.value.exits)) return null;
+ return r.value as unknown as ProbeFile;
+}
+
+// EACH ENABLED EXIT'S PROXY is asked to answer. Two depths (review 1,
+// finding 6):
+// - the startup probe (`explicit` false): a TCP (or TLS) connect only — no
+// greeting, no login, no destination, no echo;
+// - the operator's `get network --probe` (`explicit` true): the preflight a
+// listing makes (connect, SOCKS greeting and login) and, only when
+// `echoUrl` is set, that URL fetched through each exit and once direct to
+// name the address each presents.
+export async function probeNetworkExits(
+ paths: Paths,
+ network: NetworkSettings | undefined = settingsNetwork(),
+ now: Date = new Date(),
+ deps: {
+ explicit?: boolean;
+ preflight?: typeof preflightProxy;
+ get?: typeof getThroughProxy;
+ getDirect?: (url: string) => Promise<{ ok: true; body: string } | { ok: false; reason: string }>;
+ env?: Readonly<Record<string, string | undefined>>;
+ } = {},
+): Promise<ProbeFile> {
+ const preflight = deps.preflight ?? preflightProxy;
+ const get = deps.get ?? getThroughProxy;
+ const explicit = deps.explicit === true;
+ const out: ProbeFile = { at: now.toISOString(), exits: {} };
+ for (const e of network?.exits ?? []) {
+ if (!e.enabled) continue;
+ let url = proxyUrlOf(e, null);
+ if (explicit) {
+ const creds = readExitCredentials(e, { file: network!.credentialsFile, ...(deps.env ? { env: deps.env } : {}) });
+ if (!creds.ok) {
+ out.exits[e.id] = { at: now.toISOString(), reachable: false, reason: creds.reason };
+ continue;
+ }
+ url = proxyUrlOf(e, creds.creds);
+ }
+ const pf = await preflight(url, undefined, { connectOnly: !explicit });
+ const probe: ExitProbe = { at: now.toISOString(), reachable: pf.ok };
+ if (pf.ok) probe.ms = pf.ms;
+ else probe.reason = pf.reason;
+ if (explicit && pf.ok && network?.echoUrl) {
+ const r = await get(url, network.echoUrl);
+ if (r.ok) probe.address = addressInEcho(r.body);
+ else probe.echoError = r.reason;
+ }
+ out.exits[e.id] = probe;
+ }
+ if (explicit && network?.echoUrl && deps.getDirect) {
+ const r = await deps.getDirect(network.echoUrl);
+ out.exits[DIRECT_EXIT] = {
+ at: now.toISOString(),
+ reachable: true,
+ ...(r.ok ? { address: addressInEcho(r.body) } : { echoError: r.reason }),
+ };
+ }
+ await writeJsonAtomic(stateFile(paths, "probe.json"), out, { mkdir: true });
+ return out;
+}
+
+export type NetworkReportView = {
+ limits: string;
+ trialScope: { platforms: typeof TRIAL_SCOPE; sentence: string };
+ // Built from the stored form: there is no secret in it to mask.
+ exits: Array<{
+ id: string;
+ label: string;
+ display: string;
+ scheme: string | null;
+ host: string | null;
+ port: number | null;
+ credentials: boolean;
+ enabled: boolean;
+ probe: ExitProbe | null;
+ channels: number;
+ }>;
+ platforms: Record<
+ string,
+ NetworkSettings["platforms"][string] & { pool?: string[]; allRest?: boolean; ignored?: string }
+ >;
+ jars: Record<string, string>;
+ echoUrl: string;
+ credentialsFile: string;
+ startupProbe: boolean;
+ settingsProblem: string | null;
+ rests: Array<{ platform: string; exit: string; until: string; fails: number }>;
+ usage: { "1d": Record<string, NetworkUsageCounts>; "7d": Record<string, NetworkUsageCounts> };
+ lastProbeAt: string | null;
+};
+
+// How many channels are recorded on each exit (a disabled exit's channels
+// fail their listings until reassigned — the report says how many).
+async function channelsByExit(paths: Paths): Promise<Record<string, number>> {
+ const out: Record<string, number> = {};
+ let slugs: string[] = [];
+ try {
+ slugs = await readdir(paths.channelsDir);
+ } catch {
+ return out;
+ }
+ for (const slug of slugs) {
+ const rec = await readChannelExitRecord(paths, slug);
+ if (rec) out[rec.exit] = (out[rec.exit] ?? 0) + 1;
+ }
+ return out;
+}
+
+export async function networkReport(
+ paths: Paths,
+ network?: NetworkSettings,
+ now: number = Date.now(),
+): Promise<NetworkReportView> {
+ let settingsProblem: string | null = null;
+ if (!network) {
+ const strict = loadNetworkStrict(paths.settingsFile);
+ if (strict.ok) network = strict.network;
+ else {
+ settingsProblem = strict.reason;
+ network = settingsNetwork();
+ }
+ }
+ const rests = await readRests(paths);
+ const probe = await readProbe(paths);
+ const counts = await channelsByExit(paths);
+ const platforms: NetworkReportView["platforms"] = {};
+ for (const [platform, policy] of Object.entries(network?.platforms ?? {})) {
+ const pool = exitPool(network, platform, "listing");
+ platforms[platform] = {
+ ...policy,
+ ...(pool === null
+ ? { ignored: TRIAL_SCOPE_SENTENCE }
+ : { pool, allRest: await allExitsRest(paths, platform, pool, now) }),
+ };
+ }
+ const d = defaultNetworkSettings();
+ return {
+ limits: NETWORK_LIMITS_SENTENCE,
+ trialScope: { platforms: TRIAL_SCOPE, sentence: TRIAL_SCOPE_SENTENCE },
+ exits: [
+ {
+ id: DIRECT_EXIT,
+ label: "Direct (no proxy)",
+ display: "no proxy",
+ scheme: null,
+ host: null,
+ port: null,
+ credentials: false,
+ enabled: true,
+ probe: probe?.exits[DIRECT_EXIT] ?? null,
+ channels: counts[DIRECT_EXIT] ?? 0,
+ },
+ ...(network?.exits ?? []).map((e) => ({
+ id: e.id,
+ label: e.label,
+ display: exitDisplay(e),
+ scheme: e.scheme,
+ host: e.host,
+ port: e.port,
+ credentials: e.credentials,
+ enabled: e.enabled,
+ probe: probe?.exits[e.id] ?? null,
+ channels: counts[e.id] ?? 0,
+ })),
+ ],
+ platforms,
+ jars: network?.jars ?? {},
+ echoUrl: network?.echoUrl ?? "",
+ credentialsFile: network?.credentialsFile ?? d.credentialsFile,
+ startupProbe: network?.startupProbe ?? d.startupProbe,
+ settingsProblem,
+ rests: Object.entries(rests)
+ .filter(([, e]) => e.until > now)
+ .map(([k, e]) => {
+ const [platform = "", exit = ""] = k.split("/");
+ return { platform, exit, until: new Date(e.until).toISOString(), fails: e.fails };
+ }),
+ usage: { "1d": await usageOver(paths, 1, now), "7d": await usageOver(paths, 7, now) },
+ lastProbeAt: probe?.at ?? null,
+ };
+}
+
+// THE STARTUP PROBE: once, a minute after the editor boots, when an exit is
+// enabled and `network.startupProbe` is on — a TCP connect to each proxy and
+// nothing else (no greeting, no destination, no echo). One line per exit in
+// the server log; the answers land in probe.json. Never throws; armed below
+// the idle gate (editor/instrumentation.ts).
+export function startupNetworkProbe(opts: { log: (line: string) => void; delayMs?: number; paths?: Paths }): void {
+ const t = setTimeout(() => {
+ void (async () => {
+ try {
+ const paths = opts.paths ?? getPaths();
+ const strict = loadNetworkStrict(paths.settingsFile);
+ if (!strict.ok) return opts.log(`network exits: no startup probe — ${strict.reason}`);
+ const network = strict.network;
+ if (!network?.startupProbe || !network.exits.some((e) => e.enabled)) return;
+ const probe = await probeNetworkExits(paths, network, new Date(), { explicit: false });
+ for (const [id, p] of Object.entries(probe.exits)) {
+ opts.log(`network exit "${id}": ${p.reachable ? "accepts a connection" : `unreachable — ${p.reason ?? "?"}`}`);
+ }
+ } catch (e) {
+ opts.log(`network exits: the startup probe failed — ${(e as Error).message}`);
+ }
+ })();
+ }, opts.delayMs ?? 60_000);
+ t.unref?.();
+}
+
+// What the listing needs to send a request through an exit, read once per
+// listing: the pool (for the all-rest check).
+export function listingPool(network: NetworkSettings | undefined, platform: string): string[] | null {
+ return exitPool(network ?? settingsNetwork(), platform, "listing");
+}
+
+export { TRIAL_SCOPE };
diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts
@@ -123,6 +123,8 @@ import { refuseInstagramYtdlp } from "../lib/instagram/ytdlp";
import { parsePreclipKnob, type PreclipOptions } from "../lib/livePreclip";
import { jitterMs } from "../lib/jitter";
import "../lib/childKillGuard";
+// What every child inherits (lib/childEnvGuard.mjs; review 2 of lane network-exits).
+import "../lib/childEnvGuard.mjs";
export const RECORD_LIVE_JOB_KIND = "record-live";
export const RECORD_LIVE_RESULT_MARKER = "@@record-live ";
diff --git a/common/controller/rosterStore.ts b/common/controller/rosterStore.ts
@@ -47,6 +47,9 @@ export type RosterSweep = {
at: string;
listedCount: number;
verdict: SweepVerdict;
+ // The network exit the listing went through (controller/networkExits.ts),
+ // written only when the platform has a network policy; never a proxy URL.
+ exit?: string;
};
export type RosterEntry = {
@@ -230,6 +233,9 @@ export function normalizeRoster(value: unknown): Roster {
at: rawSweep.at,
listedCount: Math.max(0, Math.floor(rawSweep.listedCount)),
verdict: rawSweep.verdict,
+ ...(typeof rawSweep.exit === "string" && /^[a-z0-9][a-z0-9-]{0,39}$/.test(rawSweep.exit)
+ ? { exit: rawSweep.exit }
+ : {}),
}
: null;
diff --git a/common/controller/verifyBeforeClean.ts b/common/controller/verifyBeforeClean.ts
@@ -570,10 +570,14 @@ export async function verifyBeforeClean({
// A 429 on the listing (runYtdlp's EnumerationIncompleteError) is a rate
// limit: the platform's cooldown is recorded, as Sync records it, so the
// downloads and the retry of this clean both stay away for it.
+ // Through a network exit the exit rests instead, and the platform's
+ // cooldown is due only once every exit rests (platformBackoffDue).
if (err instanceof EnumerationIncompleteError) {
- await (probes?.recordBackoff ?? ((pf: string) => recordDownloadBackoff(pf, paths, "rate_limit")))(
- err.platform,
- ).catch(() => {});
+ if (err.platformBackoffDue) {
+ await (probes?.recordBackoff ?? ((pf: string) => recordDownloadBackoff(pf, paths, "rate_limit")))(
+ err.platform,
+ ).catch(() => {});
+ }
verdicts.stopped = { kind: "rate-limit", platform: err.platform, message: reason };
} else if (!signal?.aborted) {
verdicts.stopped = { kind: "error", platform, message: reason };
diff --git a/common/jobs/jobDeferred.ts b/common/jobs/jobDeferred.ts
@@ -0,0 +1,16 @@
+// A job its queue started that may not run yet — X's job cap, an exit that
+// rests after a rate limit (controller/networkExits.ts): it ends `done`,
+// DEFERRED, not failed (JobRecord.deferred), with the sentence and the time it
+// may run. The sync scheduler re-queues a deferred channel at `until`.
+//
+// Its own module so code below the job funnel (a yt-dlp listing) can throw it
+// without importing streamCommand, which re-exports it.
+export class JobDeferredError extends Error {
+ constructor(
+ message: string,
+ readonly until: number,
+ ) {
+ super(message);
+ this.name = "JobDeferredError";
+ }
+}
diff --git a/common/jobs/streamCommand.ts b/common/jobs/streamCommand.ts
@@ -38,6 +38,7 @@ import { runInJobContext, type JobContext } from "../lib/jobContext";
import { serviceStoppedLine } from "../lib/serviceCookies";
import { configuredCookieBrowser } from "../lib/serviceCookies-server";
import { claimResumeTag } from "./resumeTag";
+import { JobDeferredError } from "./jobDeferred";
// Mark a job's channel report dirty so the debounced scheduler regenerates the
// snapshot — called both on each completed sub-operation and on the job's
@@ -424,17 +425,10 @@ async function refuseForUnreachableMedia(
}
}
-// A job its queue started that may not run yet (X's job cap): it ends
-// deferred, not failed (JobRecord.deferred).
-export class JobDeferredError extends Error {
- constructor(
- message: string,
- readonly until: number,
- ) {
- super(message);
- this.name = "JobDeferredError";
- }
-}
+// A job its queue started that may not run yet (X's job cap, a resting
+// network exit): it ends deferred, not failed (JobRecord.deferred). The class
+// lives in ./jobDeferred so a listing below the funnel can throw it.
+export { JobDeferredError };
export async function runManagedFunction(
opts: RunManagedFunctionOpts,
diff --git a/common/lib/childEnvGuard.d.mts b/common/lib/childEnvGuard.d.mts
@@ -0,0 +1,13 @@
+// Types for ./childEnvGuard.mjs: what every child process inherits.
+export const DEAD_PROXY: "socks5h://127.0.0.1:1";
+export const PROXY_ENV_RE: RegExp;
+export const CREDENTIAL_ENV_RE: RegExp;
+export function captureNetworkExitEnv(): void;
+export function networkExitEnvValue(name: string): string | undefined;
+export function setNetworkPolicySettingsFile(file: string): void;
+export function networkPolicyActive(): boolean;
+export function filterEnvPairs(pairs: readonly string[]): string[];
+export function filterEnv(env: Record<string, string | undefined>): Record<string, string>;
+export function envWithoutProxies(): Record<string, string>;
+export function routedChildEnv(): Record<string, string>;
+export function installChildEnvGuard(): void;
diff --git a/common/lib/childEnvGuard.fixture.mjs b/common/lib/childEnvGuard.fixture.mjs
@@ -0,0 +1,111 @@
+// The fixture of childEnvGuard.test.ts, run as its own node process:
+// `node childEnvGuard.fixture.mjs <mode> <settings file | "-">`. Bindings to
+// child_process are taken BEFORE the guard is installed — an ESM named import
+// here and a CommonJS require below — as code loaded earlier than an entry's
+// import would hold them. Prints JSON.
+import { spawn as eSpawn, exec as eExec, execFile as eExecFile, fork as eFork, spawnSync as eSpawnSync, execFileSync as eExecFileSync } from "node:child_process";
+import { createRequire } from "node:module";
+import { fileURLToPath } from "node:url";
+
+const require = createRequire(import.meta.url);
+const cjs = require("node:child_process");
+const { spawn: rSpawn, execFile: rExecFile } = cjs;
+const SELF = fileURLToPath(import.meta.url);
+const [mode, settingsFile] = process.argv.slice(2);
+
+const ENV_SCRIPT =
+ "const o={};for(const [k,v] of Object.entries(process.env)){if(/proxy$/i.test(k)||/^NETWORK_EXIT_/.test(k))o[k]=v;}process.stdout.write(JSON.stringify(o));";
+const WHOLE_ENV = "process.stdout.write(JSON.stringify(Object.entries(process.env).filter(([k])=>k!=='_')))";
+
+if (mode === "fork-child") {
+ const o = {};
+ for (const [k, v] of Object.entries(process.env)) if (/proxy$/i.test(k) || /^NETWORK_EXIT_/.test(k)) o[k] = v;
+ process.stdout.write(JSON.stringify(o));
+ process.exit(0);
+}
+
+const collect = (child) =>
+ new Promise((resolve) => {
+ let s = "";
+ child.stdout.on("data", (d) => (s += d));
+ child.on("close", () => resolve(JSON.parse(s || "{}")));
+ });
+const node = process.execPath;
+
+Object.assign(process.env, { HTTPS_PROXY: "http://127.0.0.1:2", no_proxy: "*", NETWORK_EXIT_EXIT_A: "fixture-user:fixture-value" });
+if (settingsFile && settingsFile !== "-") process.env.SETTINGS_FILE = settingsFile;
+else delete process.env.SETTINGS_FILE;
+
+const errs = [];
+const origError = console.error;
+console.error = (...a) => errs.push(a.join(" "));
+const guard = await import("./childEnvGuard.mjs");
+
+const out = {};
+if (mode === "apis") {
+ out.parentHasCredential = "NETWORK_EXIT_EXIT_A" in process.env;
+ out.esmSpawn = await collect(eSpawn(node, ["-e", ENV_SCRIPT]));
+ out.esmExec = await collect(eExec(`"${node}" -e '${ENV_SCRIPT}'`));
+ out.esmExecFile = await collect(eExecFile(node, ["-e", ENV_SCRIPT]));
+ out.esmExecFileUndefined = await collect(eExecFile(node, ["-e", ENV_SCRIPT], undefined));
+ out.cjsSpawn = await collect(rSpawn(node, ["-e", ENV_SCRIPT]));
+ out.cjsExecFile = await collect(rExecFile(node, ["-e", ENV_SCRIPT]));
+ out.shellTrue = await collect(eSpawn(`"${node}" -e '${ENV_SCRIPT}'`, { shell: true }));
+ out.fork = await collect(eFork(SELF, ["fork-child"], { silent: true }));
+ const { execa } = await import("execa");
+ out.execa = JSON.parse((await execa(node, ["-e", ENV_SCRIPT])).stdout || "{}");
+ out.execaOwnEnv = JSON.parse((await execa(node, ["-e", ENV_SCRIPT], { env: { ...process.env, ALL_PROXY: "http://127.0.0.1:3" } })).stdout || "{}");
+ out.routed = JSON.parse((await execa(node, ["-e", ENV_SCRIPT], { env: guard.routedChildEnv(), extendEnv: false })).stdout || "{}");
+ // The sync API is NOT hooked (no networking spawn uses it; the gate holds
+ // that): it gets main's environment — minus the credential, which left
+ // process.env at install.
+ out.spawnSync = JSON.parse(eSpawnSync(node, ["-e", ENV_SCRIPT]).stdout.toString() || "{}");
+ out.execFileSync = JSON.parse(eExecFileSync(node, ["-e", ENV_SCRIPT]).toString() || "{}");
+ out.log = errs;
+} else if (mode === "main") {
+ // No policy: the WHOLE environment a child sees is the parent's, in order.
+ const parent = Object.entries(process.env).filter(([k]) => k !== "_");
+ const child = await collect(eSpawn(node, ["-e", WHOLE_ENV]));
+ out.sameWhole = JSON.stringify(child) === JSON.stringify(parent);
+ const base = { PATH: process.env.PATH ?? "", HTTPS_PROXY: "http://127.0.0.1:2", INHERITED_ONLY: "1" };
+ const ownAndInherited = Object.create(base);
+ ownAndInherited.OWN_KEY = "own";
+ const viaSpawn = await collect(eSpawn(node, ["-e", WHOLE_ENV], { env: ownAndInherited }));
+ out.explicitEnv = Object.fromEntries(viaSpawn);
+ // The test harness re-adds its no-network preload to a child given its own
+ // environment (common/lib/noNetwork.mjs guardedChildEnv), which copies own
+ // keys only; the inherited-key case is then the harness's, not the guard's.
+ out.noNetworkHarness = process.env.ARCHILYZER_NO_NETWORK === "1";
+ // Options reach Node unchanged.
+ const { execa } = await import("execa");
+ out.cwd = (await execa(node, ["-e", "process.stdout.write(process.cwd())"], { cwd: "/" })).stdout;
+ out.input = (await execa(node, ["-e", "process.stdin.pipe(process.stdout)"], { input: "piped-in" })).stdout;
+ const t0 = Date.now();
+ const timedOut = await execa(node, ["-e", "setTimeout(()=>{},5000)"], { timeout: 200, reject: false });
+ out.timeout = { timedOut: timedOut.timedOut, fast: Date.now() - t0 < 3000 };
+ const ac = new AbortController();
+ const aborted = execa(node, ["-e", "setTimeout(()=>{},5000)"], { cancelSignal: ac.signal, reject: false });
+ setTimeout(() => ac.abort(), 100);
+ out.signal = (await aborted).isCanceled;
+ const det = eSpawn(node, ["-e", "process.stdout.write(String(process.pid))"], { detached: true, stdio: ["ignore", "pipe", "ignore"] });
+ out.detached = (await new Promise((r) => { let s = ""; det.stdout.on("data", (d) => (s += d)); det.on("close", () => r(s)); })) !== "";
+} else if (mode === "twocopies") {
+ const { ChildProcess } = cjs;
+ const first = ChildProcess.prototype.spawn;
+ const copy = await import("./childEnvGuard.mjs?copy=2");
+ out.onePatch = ChildProcess.prototype.spawn === first;
+ out.bothRead =
+ guard.networkExitEnvValue("NETWORK_EXIT_EXIT_A") === "fixture-user:fixture-value" &&
+ copy.networkExitEnvValue("NETWORK_EXIT_EXIT_A") === "fixture-user:fixture-value";
+ // A credential put back (Next's dev .env reload does this) reaches no child.
+ const PUT_BACK = "NETWORK_EXIT_EXIT_B";
+ process.env[PUT_BACK] = "fixture-user:put-back";
+ out.putBack = await collect(eSpawn(node, ["-e", ENV_SCRIPT]));
+ out.putBackLeftEnv = !(PUT_BACK in process.env);
+} else if (mode === "unresolved") {
+ out.child = await collect(eSpawn(node, ["-e", ENV_SCRIPT]));
+ await collect(eSpawn(node, ["-e", ENV_SCRIPT]));
+ out.log = errs;
+}
+console.error = origError;
+process.stdout.write(JSON.stringify(out));
diff --git a/common/lib/childEnvGuard.gate.test.ts b/common/lib/childEnvGuard.gate.test.ts
@@ -0,0 +1,122 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { readFileSync, readdirSync, statSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/childEnvGuard.gate.test.ts
+//
+// THE SPAWN-SITE GATE (review 2, finding 2). The environment a child gets is
+// decided in ONE place: lib/childEnvGuard.mjs, a hook on Node's own spawn
+// (ChildProcess.prototype.spawn, which spawn/execFile/exec/fork/execa all
+// reach) and on spawnSync/execSync/execFileSync. A site cannot build its
+// environment another way, because whatever it passes is filtered there. So
+// the gate holds what the hook depends on:
+// 1. every process ENTRY that can start network work installs it first
+// (editor, umtool, the archilyzer CLI) — a child of a guarded process
+// inherits the filtered environment, so grandchildren are covered;
+// 2. every common/ module that spawns a networking tool (yt-dlp, gallery-dl,
+// streamlink, curl, wget, a browser) imports it too, so a script that
+// loads one without an entry is still guarded;
+// 3. no source file reaches a spawn the hook does not see (process.binding,
+// internalBinding, a second ChildProcess.prototype.spawn patch);
+// 4. no source file sets a proxy variable for a child except the guard's
+// routedChildEnv.
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
+const read = (rel: string) => readFileSync(path.join(ROOT, rel), "utf8");
+const GUARD_IMPORT = /childEnvGuard(\.mjs)?["']/;
+
+function walk(dir: string, out: string[] = []): string[] {
+ let names: string[];
+ try {
+ names = readdirSync(path.join(ROOT, dir));
+ } catch {
+ return out;
+ }
+ for (const n of names) {
+ if (n === "node_modules" || n === ".next" || n === "e2e" || n.startsWith(".")) continue;
+ const rel = path.join(dir, n);
+ if (statSync(path.join(ROOT, rel)).isDirectory()) walk(rel, out);
+ else if (/\.(ts|tsx|mjs|js)$/.test(n) && !/\.(test|spec|fixture|unit)\./.test(n)) out.push(rel);
+ }
+ return out;
+}
+
+const SOURCES = [...walk("common"), ...walk("editor/app"), ...walk("editor/lib"), "editor/instrumentation.ts", ...walk("umtool"), ...walk("scripts"), ...walk("mcp/src")];
+
+test("1. every process entry installs the guard before anything else can spawn", () => {
+ for (const entry of ["editor/instrumentation.ts", "umtool/instrumentation.ts", "common/bin/archilyzer.ts", "umtool/bin/umtool.mjs"]) {
+ assert.match(read(entry), GUARD_IMPORT, `${entry} does not install lib/childEnvGuard`);
+ }
+});
+
+// X code (and headedDisplay, which builds the X browser's launch) is another
+// lane's: covered by the process entries above, not edited here.
+const X_FILES = new Set([
+ "common/social/xGalleryDlFetcher.ts",
+ "common/social/xTrendingRead.ts",
+ "common/social/xSessionBroker.ts",
+ "common/social/xBrowserLogin.ts",
+ "common/social/headedDisplay.ts",
+]);
+const NETWORK_TOOL = /ytdlpBin|galleryDlBin|["'`]yt-dlp["'`]|["'`]gallery-dl["'`]|streamlink|["'`]curl["'`]|["'`]wget["'`]|chromium\.launch|firefox\.launch|launchPersistentContext/;
+const SPAWNS = /\b(execa|spawn|execFile|fork|spawnSync|execFileSync|execSync)\s*\(/;
+
+test("2. every common/ module that spawns a networking tool imports the guard", () => {
+ const missing = SOURCES.filter(
+ (f) => f.startsWith("common/") && !f.endsWith("childEnvGuard.mjs") && !X_FILES.has(f),
+ ).filter((f) => {
+ const s = read(f);
+ return SPAWNS.test(s) && NETWORK_TOOL.test(s) && !GUARD_IMPORT.test(s);
+ });
+ assert.deepEqual(missing, []);
+});
+
+test("3. nothing reaches a spawn the guard does not see", () => {
+ const raw = SOURCES.filter((f) => !f.endsWith("childEnvGuard.mjs") && !f.endsWith("noNetwork.mjs")).filter((f) =>
+ /process\.binding\(|internalBinding\(|ChildProcess\.prototype\.spawn\s*=/.test(read(f)),
+ );
+ assert.deepEqual(raw, []);
+});
+
+test("4. no source sets a proxy variable for a child but the guard", () => {
+ const setters = SOURCES.filter((f) => !f.endsWith("childEnvGuard.mjs") && !f.endsWith("noNetwork.mjs")).filter((f) =>
+ /\b(HTTPS?_PROXY|ALL_PROXY|https?_proxy|all_proxy|NO_PROXY|no_proxy)\s*:/.test(read(f)),
+ );
+ assert.deepEqual(setters, []);
+});
+
+// REVIEW 3 finding 3: the sync API is not hooked, so no networking spawn may
+// use it. A sync call naming a networking tool (or a URL) fails the gate.
+test("5. no networking tool is spawned through the sync API", () => {
+ const SYNC = /\b(spawnSync|execSync|execFileSync|execaSync)\s*\(([\s\S]{0,240})/g;
+ const NET = /yt-?dlp|ytdlpBin|gallery-?dl|galleryDlBin|streamlink|\bcurl\b|\bwget\b|aria2c|chromium|playwright|https?:\/\//i;
+ const hits: string[] = [];
+ for (const f of SOURCES) {
+ for (const m of read(f).matchAll(SYNC)) if (NET.test(m[2]!)) hits.push(`${f}: ${m[0].slice(0, 80)}`);
+ }
+ assert.deepEqual(hits, []);
+});
+
+// REVIEW 3 finding 2: every entry names the settings file the editor uses.
+test("6. every process entry tells the guard which settings file holds the policy", () => {
+ for (const entry of ["editor/instrumentation.ts", "umtool/instrumentation.ts", "common/bin/archilyzer.ts", "umtool/bin/umtool.mjs"]) {
+ assert.match(read(entry), /setNetworkPolicySettingsFile\(/, entry);
+ }
+ // The umtool CLI names the file getPaths() reads (umtool/lib/paths.mjs editorSettingsFile).
+ assert.match(read("umtool/bin/umtool.mjs"), /setNetworkPolicySettingsFile\(editorSettingsFile\(\)\)/);
+});
+
+// REVIEW 3 nit 4: a guard that does not install stops the server.
+test("7. a server whose guard does not install refuses to start", () => {
+ for (const entry of ["editor/instrumentation.ts", "umtool/instrumentation.ts"]) {
+ const s = read(entry);
+ const at = s.indexOf("setNetworkPolicySettingsFile(");
+ const block = s.slice(at, at + 900);
+ assert.match(block, /catch[\s\S]*refuses to start[\s\S]*process\.exit\(1\)/, entry);
+ // …and does not leave a credential behind for whatever runs before the exit.
+ assert.match(block, /catch[\s\S]*NETWORK_EXIT_[\s\S]*process\.exit\(1\)/, `${entry}: the catch clears NETWORK_EXIT_* first`);
+ }
+});
diff --git a/common/lib/childEnvGuard.mjs b/common/lib/childEnvGuard.mjs
@@ -0,0 +1,213 @@
+// 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<string, string>, settingsFile: string | null, resolved: boolean, said: Set<string>, 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<string, string | undefined>} env */
+export function filterEnv(env) {
+ const active = networkPolicyActive();
+ /** @type {Record<string, string>} */
+ 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<string, string>} */
+ 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();
diff --git a/common/lib/childEnvGuard.test.ts b/common/lib/childEnvGuard.test.ts
@@ -0,0 +1,102 @@
+import { test, after } from "node:test";
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/childEnvGuard.test.ts
+//
+// THE CHILD-ENVIRONMENT HOOK (lane network-exits, reviews 2-3). Each case runs
+// lib/childEnvGuard.fixture.mjs as its own node process, with child_process
+// bindings taken before the guard is installed (ESM named imports and a
+// CommonJS require).
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const DIR = mkdtempSync(path.join(os.tmpdir(), "child-env-guard-"));
+after(() => rmSync(DIR, { recursive: true, force: true }));
+
+function run(mode: string, settings: string | null | "unset") {
+ let file = "-";
+ if (settings !== "unset") {
+ file = path.join(DIR, `settings-${Math.random().toString(36).slice(2)}.json`);
+ if (settings !== null) writeFileSync(file, settings);
+ }
+ const env: Record<string, string> = {};
+ for (const [k, v] of Object.entries(process.env)) {
+ if (v !== undefined && !/proxy$/i.test(k) && !["NODE_OPTIONS", "ARCHILYZER_NO_NETWORK", "SETTINGS_FILE"].includes(k)) env[k] = v;
+ }
+ return JSON.parse(execFileSync(process.execPath, [path.join(HERE, "childEnvGuard.fixture.mjs"), mode, file], { env, cwd: DIR }).toString());
+}
+
+const POLICY = JSON.stringify({ network: { exits: [], platforms: { twitch: { exits: ["direct"], mode: "sticky" } } } });
+const ASYNC = ["esmSpawn", "esmExec", "esmExecFile", "esmExecFileUndefined", "cjsSpawn", "cjsExecFile", "shellTrue", "fork", "execa", "execaOwnEnv"] as const;
+
+test("a credential leaves process.env at load and no child gets it, whatever API spawns it (review 2 finding 1)", () => {
+ const r = run("apis", POLICY);
+ assert.equal(r.parentHasCredential, false);
+ for (const w of [...ASYNC, "routed", "spawnSync", "execFileSync"]) {
+ assert.ok(!Object.keys(r[w]).some((k) => k.startsWith("NETWORK_EXIT_")), w);
+ }
+});
+
+test("any policy: every async spawn, bindings taken before install included, gets no proxy variable (review 3 test 1)", () => {
+ const r = run("apis", POLICY);
+ for (const w of ASYNC) assert.deepEqual(r[w], {}, w);
+ assert.deepEqual(Object.keys(r.routed).sort(), ["ALL_PROXY", "HTTPS_PROXY", "HTTP_PROXY", "all_proxy", "http_proxy", "https_proxy"]);
+ for (const v of Object.values(r.routed)) assert.equal(v, "socks5h://127.0.0.1:1");
+});
+
+test("the sync API is not hooked: it keeps main's environment (no networking spawn uses it — the gate holds that)", () => {
+ const r = run("apis", POLICY);
+ assert.deepEqual(r.spawnSync, { HTTPS_PROXY: "http://127.0.0.1:2", no_proxy: "*" });
+ assert.deepEqual(r.execFileSync, { HTTPS_PROXY: "http://127.0.0.1:2", no_proxy: "*" });
+});
+
+test("no policy is main, byte for byte: the whole environment, explicit env own and inherited keys, and the options (review 3 test 2)", () => {
+ const r = run("main", JSON.stringify({ network: { exits: [], platforms: {} } }));
+ assert.equal(r.sameWhole, true);
+ assert.equal(r.explicitEnv.OWN_KEY, "own");
+ if (!r.noNetworkHarness) {
+ assert.equal(r.explicitEnv.INHERITED_ONLY, "1");
+ assert.equal(r.explicitEnv.HTTPS_PROXY, "http://127.0.0.1:2");
+ }
+ assert.equal(r.cwd, "/");
+ assert.equal(r.input, "piped-in");
+ assert.deepEqual(r.timeout, { timedOut: true, fast: true });
+ assert.equal(r.signal, true);
+ assert.equal(r.detached, true);
+});
+
+test("two copies of the module share one state: one patch, one map, a put-back credential reaches no child (review 3 test 3)", () => {
+ const r = run("twocopies", POLICY);
+ assert.equal(r.onePatch, true);
+ assert.equal(r.bothRead, true);
+ assert.deepEqual(r.putBack, {});
+ assert.equal(r.putBackLeftEnv, true);
+});
+
+test("no settings file named: fail closed (a policy may exist), said once in the log (review 3 finding 2)", () => {
+ const r = run("unresolved", "unset");
+ assert.deepEqual(r.child, {});
+ assert.equal(r.log.filter((l: string) => /childEnvGuard: no settings file was named/.test(l)).length, 1);
+});
+
+test("unreadable settings strip too (fail safe), said once", () => {
+ const r = run("apis", "{ not json");
+ for (const w of ASYNC) assert.deepEqual(r[w], {}, w);
+ assert.equal(r.log.filter((l: string) => /could not be read/.test(l)).length, 1);
+});
+
+test("an absent settings file at the named path is no policy: main's proxies", () => {
+ const r = run("apis", null);
+ assert.deepEqual(r.esmSpawn, { HTTPS_PROXY: "http://127.0.0.1:2", no_proxy: "*" });
+});
+
+test("the policy path is resolved once (review 3 nit 6): SETTINGS_FILE changed later is not re-read", () => {
+ const src = readFileSync(path.join(HERE, "childEnvGuard.mjs"), "utf8");
+ assert.match(src, /resolvedSettingsFile/);
+ assert.doesNotMatch(src, /process\.cwd\(\)/, "no cwd walk (review 3 findings 1-2)");
+});
diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts
@@ -98,6 +98,8 @@ const DECLARED: EnvVarDecl[] = [
{ name: "ANTHROPIC_API_KEY", audience: "runtime", default: "unset (the API key file is read instead)", readBy: "common/lib/llm/anthropic.ts", doc: "The Claude API key for report and video generation on the API (release 27): read first, before the mode-600 key file the generation settings name. Sent only to the Messages API in `x-api-key`; never logged, and never in an error, a job record or a transcript." },
{ name: "ARCHIVE_ORG_S3_ACCESS", audience: "runtime", default: "unset (the S3 key file is read instead)", readBy: "common/lib/waybackPages/savePageNow-server.ts", doc: "archive.org's S3 access key for Save Page Now (release 37): read first, with `ARCHIVE_ORG_S3_SECRET`, before the mode-600 file `settings.archiveOrg.s3KeyFile` names. Both or neither. Sent only to web.archive.org/save in the `Authorization: LOW <access>:<secret>` header; never logged, and never in an error, a job record or a result. Without keys Save Page Now is off and says why." },
{ name: "ARCHIVE_ORG_S3_SECRET", audience: "runtime", default: "unset (the S3 key file is read instead)", readBy: "common/lib/waybackPages/savePageNow-server.ts", doc: "archive.org's S3 secret key for Save Page Now, with `ARCHIVE_ORG_S3_ACCESS` (above)." },
+ { name: "NETWORK_EXIT_*", audience: "runtime", default: "unset (the credentials file is read instead)", readBy: "common/lib/networkCredentials-server.ts (through common/lib/childEnvGuard.mjs)", doc: "One per exit, `NETWORK_EXIT_<ID>`: a network exit's proxy credentials (lane network-exits), `user:password`, each part percent-encoded; `<ID>` is the exit id upper-cased with `-` as `_`. Read first, before the mode-600 file `settings.network.credentialsFile` names. Moved out of the environment when the editor, umtool or the CLI boots, so no child process inherits it; never logged, never in an error, a job record or a result." },
+ { name: "ARCHILYZER_CREDENTIALS_DIR", audience: "runtime", default: "unset (only the config directory)", readBy: "common/lib/networkCredentials-server.ts", doc: "An absolute directory a network exit's credentials file (`settings.network.credentialsFile`) may also sit in, besides `~/.config` and `$XDG_CONFIG_HOME`." },
{ name: "SYNC_HEARTBEAT_SECONDS", audience: "runtime", default: "`settings.syncScheduler.heartbeatSeconds`", readBy: "editor/app/scheduler/heartbeat.ts", doc: "Overrides the editor's in-process sync heartbeat. `0` = no internal timer (tick from cron instead)." },
{ name: "ARCHILYZER_OTS_BIN", audience: "runtime", default: "`ots` on PATH, then `~/.local/bin/ots`", readBy: "common/bin/evidence-pack.ts", doc: "The OpenTimestamps `ots` binary that `archilyzer evidence stamp|upgrade|verify` (and `evidence pack`'s stamp) run. Without one, the stamp fails and the package is left unstamped (`evidence stamp` it later)." },
{ name: "SYNC_TICK_URL", audience: "runtime", default: "`http://127.0.0.1:3001/api/scheduler/tick`", readBy: "common/bin/sync-tick.ts", doc: "Where `archilyzer sync tick` (cron's heartbeat) posts." },
@@ -112,7 +114,7 @@ const DECLARED: EnvVarDecl[] = [
{ name: "YTDLP_AUTO_UPDATE", audience: "runtime", default: "off", readBy: "docker/entrypoint.sh, common/bin/doctor.ts", doc: "Docker: `1` runs `yt-dlp -U` on every editor boot — on the image's yt-dlp only; an override (`YTDLP_BIN` naming another) is left alone, with a warning." },
{ name: "XDG_STATE_HOME", audience: "runtime", default: "`~/.local/state`", readBy: "common/bin/housekeeping.ts", doc: "The state root: `archilyzer housekeeping` keeps its record of runs in `<it>/archilyzer/housekeeping.json`." },
{ name: "ARCHILYZER_HOUSEKEEPING_RECORD", audience: "runtime", default: "`$XDG_STATE_HOME/archilyzer/housekeeping.json`", readBy: "common/bin/housekeeping.ts", doc: "Where `archilyzer housekeeping` appends each run (what each part freed and kept, why a run was skipped, the home filesystem's free space before and after; the last 52 runs)." },
- { name: "XDG_CONFIG_HOME", audience: "runtime", default: "`~/.config`", readBy: "common/bin/doctor.ts, common/lib/pagesDeploy.ts, common/lib/browserUserAgent-server.ts", doc: "Where `wrangler login` keeps its config (`<it>/.wrangler/config/default.toml`); the doctor looks for it there, by path, never reading it. Also where a Linux Firefox may keep its profiles (`<it>/mozilla/firefox`), whose `compatibility.ini` gives the derived Firefox user agent." },
+ { name: "XDG_CONFIG_HOME", audience: "runtime", default: "`~/.config`", readBy: "common/bin/doctor.ts, common/lib/pagesDeploy.ts, common/lib/browserUserAgent-server.ts, common/lib/networkCredentials-server.ts", doc: "Where `wrangler login` keeps its config (`<it>/.wrangler/config/default.toml`); the doctor looks for it there, by path, never reading it. Also where a Linux Firefox may keep its profiles (`<it>/mozilla/firefox`), whose `compatibility.ini` gives the derived Firefox user agent. And one directory a network exit's credentials file may sit in." },
{ name: "APPDATA", audience: "runtime", default: "`~/AppData/Roaming`", readBy: "common/lib/browserUserAgent-server.ts", doc: "Windows: where Firefox keeps its profiles (`<it>/Mozilla/Firefox`), whose `compatibility.ini` gives the derived Firefox user agent. Set by Windows itself." },
{ name: "YTDLP_SOURCE_DIR", audience: "runtime", default: "`/opt/yt-dlp-src`", readBy: "docker/yt-dlp-from-source.sh", doc: "Docker: where `/usr/local/bin/yt-dlp-from-source` finds the yt-dlp source tree it runs with the image's python." },
{ name: "DOCKER_BIN", audience: "runtime", default: "`docker`", readBy: "common/publish/build.ts", doc: "The container engine for docker-mode builds (e.g. `podman`)." },
diff --git a/common/lib/networkCredentials-server.test.ts b/common/lib/networkCredentials-server.test.ts
@@ -0,0 +1,70 @@
+import { test, after } from "node:test";
+import assert from "node:assert/strict";
+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+process.env.NETWORK_EXIT_EXIT_CAPTURED = "captured-user:captured-value";
+const { readExitCredentials, credentialsFileRefusal } = await import("./networkCredentials-server");
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/networkCredentials-server.test.ts
+//
+// THE KEY-FILE CONVENTION (as archive.org's S3 keys, lib/waybackPages/
+// savePageNow-server.ts): the environment first, else a mode-600 file whose
+// PATH is a setting. Temp files only.
+
+const DIR = mkdtempSync(path.join(os.tmpdir(), "net-creds-"));
+process.env.ARCHILYZER_CREDENTIALS_DIR = DIR;
+after(() => rmSync(DIR, { recursive: true, force: true }));
+const exitA = { id: "exit-a", label: "A", scheme: "socks5h" as const, host: "a.example.test", port: 1080, credentials: true, enabled: true };
+
+function keyFile(text: string, mode = 0o600): string {
+ const f = path.join(DIR, `keys-${Math.random().toString(36).slice(2)}.env`);
+ writeFileSync(f, text);
+ chmodSync(f, mode);
+ return f;
+}
+
+test("an exit without credentials reads nothing", () => {
+ assert.deepEqual(readExitCredentials({ ...exitA, credentials: false }, { file: "/nonexistent", env: {} }), { ok: true, creds: null });
+});
+
+test("the environment first, then the mode-600 file", () => {
+ const f = keyFile("NETWORK_EXIT_EXIT_A=from-file:pw%21\n");
+ const env = readExitCredentials(exitA, { file: f, env: { NETWORK_EXIT_EXIT_A: "from-env:pw" } });
+ assert.ok(env.ok && env.creds?.username === "from-env");
+ const file = readExitCredentials(exitA, { file: f, env: {} });
+ assert.ok(file.ok);
+ assert.deepEqual(file.creds, { username: "from-file", password: "pw!", encoded: "from-file:pw%21" });
+});
+
+test("a file others can read, a missing file or line, or a raw password is refused, never echoing it", () => {
+ const open = readExitCredentials(exitA, { file: keyFile("NETWORK_EXIT_EXIT_A=u:fake-one\n", 0o644), env: {} });
+ assert.equal(open.ok, false);
+ assert.match((open as { reason: string }).reason, /readable by others — chmod 600 it/);
+ const none = readExitCredentials(exitA, { file: path.join(DIR, "absent.env"), env: {} });
+ assert.match((none as { reason: string }).reason, /exit "exit-a" needs credentials: put NETWORK_EXIT_EXIT_A=user:password .*absent\.env/);
+ const noLine = readExitCredentials(exitA, { file: keyFile("OTHER=1\n"), env: {} });
+ assert.match((noLine as { reason: string }).reason, /has no NETWORK_EXIT_EXIT_A= line/);
+ const raw = readExitCredentials(exitA, { file: keyFile("NETWORK_EXIT_EXIT_A=u:fake@value-two\n"), env: {} });
+ assert.equal(raw.ok, false);
+ assert.match((raw as { reason: string }).reason, /percent-encode/);
+ assert.ok(!(raw as { reason: string }).reason.includes("value-two"));
+});
+
+test("NETWORK_EXIT_* is moved out of process.env at load into the private map (review 2 finding 1)", () => {
+ assert.equal(process.env.NETWORK_EXIT_EXIT_CAPTURED, undefined);
+ const r = readExitCredentials({ id: "exit-captured", credentials: true }, { file: path.join(DIR, "none.env") });
+ assert.ok(r.ok && r.creds?.username === "captured-user");
+});
+
+test("the key file must sit under the config directory or ARCHILYZER_CREDENTIALS_DIR, be ours and mode 600 (review 2 nit 8)", () => {
+ assert.match(credentialsFileRefusal("/etc/network-exits.env") ?? "", /not under/);
+ assert.match(credentialsFileRefusal("relative.env") ?? "", /absolute/);
+ assert.equal(credentialsFileRefusal(path.join(DIR, "x.env")), null);
+ assert.equal(credentialsFileRefusal("~/.config/archilyzer/network-exits.env"), null);
+ const outside = readExitCredentials(exitA, { file: "/etc/network-exits.env", env: {} });
+ assert.match((outside as { reason: string }).reason, /not under/);
+ const g = readExitCredentials(exitA, { file: keyFile("NETWORK_EXIT_EXIT_A=u:p\n", 0o640), env: {} });
+ assert.match((g as { reason: string }).reason, /readable by others/);
+});
diff --git a/common/lib/networkCredentials-server.ts b/common/lib/networkCredentials-server.ts
@@ -0,0 +1,101 @@
+// A NETWORK EXIT'S CREDENTIALS (lane network-exits, review 1 finding 1;
+// review 2 finding 1 and nit 8), kept the way archive.org's S3 keys are
+// (lib/waybackPages/savePageNow-server.ts): the environment first
+// (`NETWORK_EXIT_<ID>`), else a mode-600 file whose PATH is the setting
+// `network.credentialsFile`, one line per exit:
+// `NETWORK_EXIT_<ID>=user:password`, each part percent-encoded.
+//
+// - The environment form is read from a PRIVATE in-process map:
+// lib/childEnvGuard.mjs moves every NETWORK_EXIT_* out of process.env when
+// it is installed (importing this module installs it), so no child process
+// ever inherits one.
+// - The file must sit under the user's config directory (`~/.config`, or
+// `$XDG_CONFIG_HOME`) or ARCHILYZER_CREDENTIALS_DIR, be a regular file
+// owned by this user, and have no group or other permission bits. It is
+// opened once and checked and read through the same descriptor.
+//
+// The credentials are never a setting, never logged, never in an error, a job
+// record or a result: every sentence here names the exit, the variable and
+// the file — never a value.
+
+import { closeSync, fstatSync, openSync, readFileSync, constants as fsConstants } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { networkExitEnvValue } from "./childEnvGuard.mjs";
+import {
+ DEFAULT_NETWORK_CREDENTIALS_FILE,
+ credentialsEnvKey,
+ parseCredentials,
+ type ExitCredentials,
+ type NetworkExit,
+} from "./networkExits";
+
+export type ExitCredentialsRead = { ok: true; creds: ExitCredentials | null } | { ok: false; reason: string };
+
+const expandHome = (p: string) => (p === "~" || p.startsWith("~/") ? os.homedir() + p.slice(1) : p);
+const unquote = (v: string) => v.trim().replace(/^(["'])(.*)\1$/, "$2").trim();
+
+function allowedDirs(): string[] {
+ const dirs = [path.join(os.homedir(), ".config")];
+ if (process.env.XDG_CONFIG_HOME && path.isAbsolute(process.env.XDG_CONFIG_HOME)) dirs.push(process.env.XDG_CONFIG_HOME);
+ if (process.env.ARCHILYZER_CREDENTIALS_DIR && path.isAbsolute(process.env.ARCHILYZER_CREDENTIALS_DIR)) {
+ dirs.push(process.env.ARCHILYZER_CREDENTIALS_DIR);
+ }
+ return dirs.map((d) => path.resolve(d));
+}
+
+// Why `keyFile` may not hold credentials, or null.
+export function credentialsFileRefusal(keyFile: string): string | null {
+ const expanded = expandHome(keyFile.trim());
+ if (!path.isAbsolute(expanded)) return `${keyFile} is not an absolute path (or ~/…); the credentials file is refused`;
+ const resolved = path.resolve(expanded);
+ const under = allowedDirs().some((d) => resolved === d || resolved.startsWith(d + path.sep));
+ return under
+ ? null
+ : `${keyFile} is not under the config directory (~/.config, $XDG_CONFIG_HOME) or ARCHILYZER_CREDENTIALS_DIR; the credentials file is refused`;
+}
+
+export function readExitCredentials(
+ exit: Pick<NetworkExit, "id" | "credentials">,
+ o: { file?: string; env?: Readonly<Record<string, string | undefined>> } = {},
+): ExitCredentialsRead {
+ if (!exit.credentials) return { ok: true, creds: null };
+ const key = credentialsEnvKey(exit.id);
+ const keyFile = o.file?.trim() || DEFAULT_NETWORK_CREDENTIALS_FILE;
+ const parsed = (value: string, from: string): ExitCredentialsRead => {
+ const c = parseCredentials(value);
+ return "error" in c ? { ok: false, reason: `exit "${exit.id}": ${key} in ${from}: ${c.error}` } : { ok: true, creds: c };
+ };
+ const envValue = (o.env ? o.env[key] : networkExitEnvValue(key))?.trim();
+ if (envValue) return parsed(envValue, "the environment");
+ const refused = credentialsFileRefusal(keyFile);
+ if (refused) return { ok: false, reason: `${refused}; exit "${exit.id}" needs credentials.` };
+ let fd: number;
+ try {
+ fd = openSync(expandHome(keyFile), fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
+ } catch {
+ return {
+ ok: false,
+ reason: `exit "${exit.id}" needs credentials: put ${key}=user:password (percent-encoded) in ${keyFile} (mode 600), or set ${key} in the environment`,
+ };
+ }
+ let text: string;
+ try {
+ const st = fstatSync(fd);
+ if (!st.isFile()) return { ok: false, reason: `${keyFile} is not a regular file; exit "${exit.id}" is off.` };
+ if (typeof process.getuid === "function" && st.uid !== process.getuid()) {
+ return { ok: false, reason: `${keyFile} is not owned by this user; exit "${exit.id}" is off.` };
+ }
+ if (st.mode & 0o077) return { ok: false, reason: `${keyFile} is readable by others — chmod 600 it first; exit "${exit.id}" is off until then.` };
+ text = readFileSync(fd, "utf8");
+ } catch {
+ return { ok: false, reason: `${keyFile} could not be read; exit "${exit.id}" is off.` };
+ } finally {
+ closeSync(fd);
+ }
+ for (const raw of text.split("\n")) {
+ const line = raw.trim().replace(/^export\s+/, "");
+ if (line.startsWith(`${key}=`)) return parsed(unquote(line.slice(key.length + 1)), keyFile);
+ }
+ return { ok: false, reason: `${keyFile} has no ${key}= line; exit "${exit.id}" needs credentials.` };
+}
diff --git a/common/lib/networkExits.test.ts b/common/lib/networkExits.test.ts
@@ -0,0 +1,230 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ DIRECT_EXIT,
+ NetworkRequestError,
+ applyNetworkRequest,
+ credentialsEnvKey,
+ exitDisplay,
+ exitPool,
+ jarExitChangeRefusal,
+ networkSettingsProblems,
+ parseCredentials,
+ parseProxyInput,
+ proxyUrlOf,
+ redactFragments,
+ requestJar,
+ sanitizeNetwork,
+ secretFragmentsOf,
+ stableHash,
+ stickyExitFor,
+ ownProxy,
+ type NetworkSettings,
+} from "./networkExits";
+import { execFileSync } from "node:child_process";
+import { readFileSync, realpathSync } from "node:fs";
+import { YTDLP_OPTIONS, YTDLP_OPTIONS_DUMP } from "./ytdlpOptions";
+import { YTDLP_OPTION_CLASSES } from "./ytdlpOptionClasses";
+
+// The installed yt-dlp's own option table, from its own parser, run with the
+// interpreter its launcher names (a pip/pipx install); null when there is no
+// such yt-dlp (a standalone binary, none on PATH).
+function installedTable(): unknown[] | null {
+ try {
+ const bin = realpathSync(execFileSync("sh", ["-c", "command -v yt-dlp"]).toString().trim());
+ const shebang = /^#!(\S+)/.exec(readFileSync(bin, "utf8").split("\n")[0] ?? "")?.[1];
+ if (!shebang) return null;
+ return JSON.parse(execFileSync(shebang, ["-E", "-c", YTDLP_OPTIONS_DUMP], { timeout: 60_000 }).toString()).rows;
+ } catch {
+ return null;
+ }
+}
+const INSTALLED = installedTable();
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/networkExits.test.ts
+//
+// REVIEW 1 (finding 1): a proxy's credentials are never a setting and never
+// masked by pattern. The settings hold the exit's id, scheme, host, port and
+// whether it has credentials; the secret lives in the key file
+// (lib/networkCredentials-server.ts). Every answer is built from that form.
+
+function exit(id: string, extra: Record<string, unknown> = {}) {
+ return { id, label: id.toUpperCase(), scheme: "socks5h", host: `${id}.example.test`, port: 1080, credentials: false, enabled: true, ...extra };
+}
+
+function net(extra: Partial<NetworkSettings> = {}): NetworkSettings {
+ return sanitizeNetwork({
+ exits: [exit("exit-a", { credentials: true }), exit("exit-b")],
+ platforms: { rumble: { exits: ["exit-a", "exit-b"], mode: "sticky" } },
+ ...extra,
+ });
+}
+
+test("the stored form has no secret: id, scheme, host, port, credentials yes/no", () => {
+ const n = net();
+ assert.deepEqual(n.exits[0], { id: "exit-a", label: "EXIT-A", scheme: "socks5h", host: "exit-a.example.test", port: 1080, credentials: true, enabled: true });
+ assert.equal(exitDisplay(n.exits[0]!), "socks5h://exit-a.example.test:1080 (credentials)");
+ assert.equal(exitDisplay(n.exits[1]!), "socks5h://exit-b.example.test:1080");
+ assert.equal(n.credentialsFile, "~/.config/archilyzer/network-exits.env");
+ assert.equal(n.startupProbe, true);
+ assert.deepEqual(networkSettingsProblems(n), []);
+});
+
+test("a proxy URL with credentials is refused at save; raw special characters get the encoding sentence", () => {
+ for (const pw of ["pa'ss", 'pa"ss', "pa ss", "pa<ss", "p@ss", "pa\\ss", "pa%zz"]) {
+ const r = parseProxyInput(`socks5h://user:${pw}@h.example.test:1080`);
+ assert.ok("error" in r, pw);
+ assert.match(r.error, /percent-encode/, pw);
+ assert.ok(!r.error.includes(pw), `the refusal echoes ${pw}`);
+ }
+ const enc = parseProxyInput("socks5h://user:pa%27ss@h.example.test:1080");
+ assert.ok("error" in enc);
+ assert.match(enc.error, /credentials are not a setting .* NETWORK_EXIT_<ID>=user:password/);
+ assert.ok(!enc.error.includes("pa%27ss"));
+ assert.deepEqual(parseProxyInput("socks5h://h.example.test:1080"), { scheme: "socks5h", host: "h.example.test", port: 1080 });
+ assert.deepEqual(parseProxyInput("HTTP://127.0.0.1:3128"), { scheme: "http", host: "127.0.0.1", port: 3128 });
+ for (const bad of ["socks4://h:1", "socks5h://h:1/path", "socks5h://h", "socks5h://h\t:1", "socks5h://<redacted>@h:1"]) {
+ assert.ok("error" in parseProxyInput(bad), bad);
+ }
+});
+
+test("credentials in the key file: user:password, percent-encoded, unreserved only", () => {
+ assert.deepEqual(parseCredentials("example-user:fake%27value"), { username: "example-user", password: "fake'value", encoded: "example-user:fake%27value" });
+ for (const raw of ["user:pa'ss", "user:p@ss", "user:pa ss", "user:pa\\ss", "nouser", "user:pa%zz"]) {
+ const r = parseCredentials(raw);
+ assert.ok("error" in r, raw);
+ assert.match(r.error, /percent-encode/);
+ assert.ok(!r.error.includes(raw.split(":")[1] ?? raw));
+ }
+ assert.equal(credentialsEnvKey("nl-ams-1"), "NETWORK_EXIT_NL_AMS_1");
+});
+
+test("the proxy URL is built from the parsed parts; the fragments are exact values", () => {
+ const n = net();
+ const creds = parseCredentials("example-user:fake%27value");
+ assert.ok(!("error" in creds));
+ assert.equal(proxyUrlOf(n.exits[0]!, creds), "socks5h://example-user:fake%27value@exit-a.example.test:1080");
+ assert.equal(proxyUrlOf(n.exits[1]!, null), "socks5h://exit-b.example.test:1080");
+ const frags = secretFragmentsOf(creds);
+ for (const f of ["example-user:fake%27value", "fake%27value", "fake'value", "fake\\'value", "example-user"]) assert.ok(frags.includes(f), f);
+ const line = "[debug] | Stdin config: ['--proxy', 'socks5h://example-user:fake%27value@exit-a.example.test:1080'] fake\\'value";
+ const red = redactFragments(line, frags);
+ assert.ok(!red.includes("fake") && !red.includes("example-user"), red);
+ // Exact values, no pattern: text without them is untouched.
+ assert.equal(redactFragments("https://example.org?mail=a@b.example", frags), "https://example.org?mail=a@b.example");
+});
+
+test("a policy for rumble or twitch listings is accepted; another platform, kind or a jar is refused", () => {
+ assert.deepEqual(networkSettingsProblems(net({ platforms: { twitch: { exits: ["direct", "exit-b"], mode: "sticky", kinds: ["listing"] } } })), []);
+ const yt = networkSettingsProblems({ ...net(), platforms: { youtube: { exits: ["exit-a"], mode: "sticky" } } });
+ assert.match(yt[0]!, /^network\.platforms\.youtube: refused — the network-exit trial routes only the listing requests of rumble and twitch/);
+ const kind = networkSettingsProblems({ ...net(), platforms: { rumble: { exits: ["exit-a"], kinds: ["listing", "download"] } } });
+ assert.match(kind[0]!, /kinds: "download" refused/);
+ const jar = networkSettingsProblems({ ...net(), jars: { "browser:firefox": "exit-a" } });
+ assert.match(jar[0]!, /network\.jars\.browser:firefox: refused — a request that carries a login/);
+ const mode = networkSettingsProblems({ ...net(), platforms: { rumble: { exits: ["exit-a"], mode: "random" } } });
+ assert.match(mode[0]!, /mode: "sticky" is the only mode/);
+ const keyFile = networkSettingsProblems({ ...net(), credentialsFile: "a-pasted-value" });
+ assert.match(keyFile[0]!, /credentialsFile: the PATH of the mode-600 file/);
+ assert.ok(!keyFile[0]!.includes("a-pasted-value"));
+ const oldShape = networkSettingsProblems({ exits: [{ id: "x", proxy: "socks5h://u:p@h:1" }] });
+ assert.ok(oldShape.some((p) => /exits\[0\]\.proxy: not an exit key/.test(p)));
+ assert.ok(oldShape.every((p) => !p.includes("u:p")));
+});
+
+test("the sticky choice is a stable hash of the slug over the pool, never random", () => {
+ assert.equal(stableHash(""), 0x811c9dc5);
+ const pool = ["exit-a", "exit-b", "direct"];
+ const first = stickyExitFor("demo-rumble", pool);
+ for (let i = 0; i < 50; i++) assert.equal(stickyExitFor("demo-rumble", pool), first);
+ const seen = new Set(Array.from({ length: 60 }, (_, i) => stickyExitFor(`channel-${i}`, pool)));
+ assert.deepEqual([...seen].sort(), [...pool].sort());
+ assert.equal(stickyExitFor("x", []), DIRECT_EXIT);
+});
+
+test("the pool skips disabled exits; out-of-scope is null", () => {
+ const n = net();
+ assert.deepEqual(exitPool(n, "rumble", "listing"), ["exit-a", "exit-b"]);
+ n.exits[0]!.enabled = false;
+ assert.deepEqual(exitPool(n, "rumble", "listing"), ["exit-b"]);
+ assert.equal(exitPool(n, "rumble", "download"), null);
+ assert.equal(exitPool(sanitizeNetwork({ ...net(), platforms: { youtube: { exits: ["exit-a"] } } }), "youtube", "listing"), null);
+});
+
+test("requestJar resolves options by yt-dlp's own prefix rule over its option table (review 2 nit 6)", () => {
+ const base = ["--flat-playlist", "--skip-download", "--print", "url", "--impersonate", "chrome", "-I", "1:50", "--sleep-requests", "1", "--user-agent", "UA"];
+ assert.equal(requestJar(base), null);
+ const pinned: Array<[string[], string]> = [
+ [["--cookies-from-browser", "firefox"], "browser:firefox"],
+ [["--cookies-from-b", "firefox"], "browser:firefox"],
+ [["--cookies=/tmp/jar.txt"], "file:/tmp/jar.txt"],
+ [["--add-headers", "X-Any: 1"], "header"],
+ [["--add-header=Referer: x"], "header"],
+ [["--username", "u"], "login:--username"],
+ [["--pas", "x"], "login:--password"],
+ [["-u", "u"], "login:--username"],
+ [["-n"], "login:--netrc"],
+ [["-vn"], "login:--netrc"],
+ [["--netrc-cmd", "x"], "login:--netrc-cmd"],
+ [["--config-locations", "/etc/x.conf"], "config"],
+ [["--alias", "get-c,-X", "--cookies-from-browser firefox"], "config"],
+ [["--load-info-json", "/tmp/i.json"], "config"],
+ [["--extractor-args", "twitch:client_id=x"], "login:--extractor-args"],
+ [["--made-up-alias"], "config"],
+ [["https://example-user:fake-value@rumble.com/c/demo"], "login:url"],
+ ];
+ for (const [extra, jar] of pinned) assert.equal(requestJar([...base, ...extra]), jar, extra.join(" "));
+ // A value glued to a short option is a value, not flags: -f22 is a format.
+ assert.equal(requestJar([...base, "-f22", "-o", "-n"]), null);
+ assert.equal(requestJar(["--", "--cookies-from-browser"]), null);
+});
+
+test("ownProxy: --proxy in any unambiguous spelling is the channel's own proxy (review 2 nit 6)", () => {
+ for (const a of [["--proxy", ""], ["--prox", ""], ["--proxy="], ["--geo-verification-proxy", "x"]]) assert.equal(ownProxy(a), true, a.join(" "));
+ assert.equal(ownProxy(["--print", "url"]), false);
+});
+
+test("the option table is the installed yt-dlp's (fails when yt-dlp adds, renames or re-arities an option)", { skip: INSTALLED === null ? "no python yt-dlp on PATH" : false }, () => {
+ assert.deepEqual(INSTALLED, YTDLP_OPTIONS.map(([s, l, v]) => [s, l, v]));
+});
+
+test("credentialsFile: an absolute or ~/ path, no .. — anything else is refused (review 2 nit 8)", () => {
+ for (const bad of ["user:pa/ss", "relative/keys.env", "/a/../b.env", "~/x/../y.env", "~user/keys.env", " /x.env"]) {
+ assert.match(networkSettingsProblems({ ...net(), credentialsFile: bad })[0] ?? "", /credentialsFile/, bad);
+ }
+ for (const ok of ["~/.config/archilyzer/network-exits.env", "/home/example/.config/x.env"]) assert.deepEqual(networkSettingsProblems({ ...net(), credentialsFile: ok }), [], ok);
+});
+
+test("a jar's exit is not changed while it is fresh", () => {
+ assert.equal(jarExitChangeRefusal({ jar: "browser:firefox", from: undefined, to: "direct", jarFresh: true }), null);
+ assert.match(jarExitChangeRefusal({ jar: "browser:firefox", from: "direct", to: "exit-a", jarFresh: true })!, /invites a lock/);
+});
+
+test("applyNetworkRequest: a proxy URL fills the fields; credentials only as yes/no; remove leaves policies", () => {
+ const cur = net();
+ const up = applyNetworkRequest(cur, { upsertExit: { id: "exit-c", proxy: "socks5h://exit-c.example.test:1080", credentials: true } });
+ assert.deepEqual((up.exits as unknown[])[2], { id: "exit-c", label: "exit-c", scheme: "socks5h", host: "exit-c.example.test", port: 1080, credentials: true, enabled: true });
+ assert.throws(() => applyNetworkRequest(cur, { upsertExit: { id: "exit-c", proxy: "socks5h://u:fake%40value@h:1" } }), /credentials are not a setting/);
+ const off = applyNetworkRequest(cur, { upsertExit: { id: "exit-a", enabled: false } });
+ assert.equal((off.exits as Array<{ enabled: boolean; host: string }>)[0]!.enabled, false);
+ assert.equal((off.exits as Array<{ host: string }>)[0]!.host, "exit-a.example.test");
+ const rm = applyNetworkRequest(cur, { removeExit: "exit-a" });
+ assert.deepEqual((rm.platforms as Record<string, { exits: string[] }>).rumble!.exits, ["exit-b"]);
+ assert.throws(() => applyNetworkRequest(cur, { bogus: 1 }), NetworkRequestError);
+ assert.throws(() => applyNetworkRequest(cur, { upsertExit: { id: "new" } }), /needs its proxy/);
+ const probeOff = applyNetworkRequest(cur, { startupProbe: false });
+ assert.equal(probeOff.startupProbe, false);
+});
+
+test("every option of the table is classified by a person (review 3 nit 5): a new one fails until it is", () => {
+ const unclassified = [...new Set(YTDLP_OPTIONS.map(([, l]) => l))].filter((l) => !(l in YTDLP_OPTION_CLASSES));
+ assert.deepEqual(unclassified, []);
+ const stale = Object.keys(YTDLP_OPTION_CLASSES).filter((l) => !YTDLP_OPTIONS.some(([, x]) => x === l));
+ assert.deepEqual(stale, []);
+ // And an option the classes do not know is a login at run time.
+ assert.equal(requestJar(["--flat-playlist", "--plugin-dirs", "/x"]), "config");
+ assert.equal(requestJar(["--flat-playlist", "--xff", "US"]), "header");
+ assert.equal(requestJar(["--flat-playlist", "--mark-watched"]), "login:--mark-watched");
+ assert.equal(requestJar(["--flat-playlist", "--referer", "https://example.test/"]), null);
+});
diff --git a/common/lib/networkExits.ts b/common/lib/networkExits.ts
@@ -0,0 +1,716 @@
+// NAMED NETWORK EXITS (lane network-exits, 21 Nov 2026): proxies a fetch may
+// leave through, chosen per channel and kept, for the platforms and request
+// kinds the operator routes. Pure and client-safe: the types, the sanitizer,
+// the validator the writers refuse with, the sticky choice, the cookie-jar
+// classifier. State and the proxy client live in controller/networkExits.ts
+// and lib/networkProxy-server.ts; the credentials in
+// lib/networkCredentials-server.ts.
+//
+// WHAT IT IS FOR, AND WHAT IT IS NOT. It spreads logged-out listing load over
+// several addresses, and lets the archive list a site that does not answer the
+// home address. It is not a disguise: no fingerprint or user-agent spoofing is
+// added, and a login (a cookie jar, a browser's cookies, a token) never moves
+// between addresses.
+//
+// THE RULES, each enforced where its comment says:
+// - `direct` (no proxy) always exists and is reserved.
+// - A policy per platform queue, `network.platforms.<p>`; absent = direct.
+// THE TRIAL routes only TRIAL_SCOPE (rumble and twitch listings); the
+// writers refuse anything else with TRIAL_SCOPE_SENTENCE; a hand-edited
+// out-of-scope policy fails the trial platforms' listings (strict read).
+// - Sticky, never random: stickyExitFor hashes the channel slug over the
+// platform's enabled exits once; the choice is recorded and kept.
+// - A request that carries a login is pinned direct (requestJar). The trial
+// refuses every jar assignment.
+// - CREDENTIALS ARE NEVER A SETTING (review 1, finding 1). An exit is stored
+// as id, scheme, host, port and `credentials: true|false`; the user and
+// password live where the repo keeps every other secret — the environment,
+// else a mode-600 key file whose PATH is `network.credentialsFile`
+// (lib/networkCredentials-server.ts, the archive.org S3 keys' convention).
+// A proxy URL carrying credentials is refused at save. Every answer, log
+// line and record is built from the stored form, so there is nothing to
+// mask; a child's own output is scrubbed of the exact secret values.
+
+import type { FieldDocs } from "./fieldDocs";
+import { YTDLP_OPTIONS } from "./ytdlpOptions";
+import { YTDLP_OPTION_CLASSES, type YtdlpOptionClass } from "./ytdlpOptionClasses";
+
+export const DIRECT_EXIT = "direct";
+
+// The request kinds a policy may name. Only `listing` is routable in the
+// trial; the others are named so a refusal can say what was asked.
+export const NETWORK_REQUEST_KINDS = [
+ "listing",
+ "download",
+ "metadata",
+ "subtitles",
+ "clip",
+ "live",
+ "posts",
+] as const;
+export type NetworkRequestKind = (typeof NETWORK_REQUEST_KINDS)[number];
+
+export const NETWORK_POLICY_MODES = ["sticky"] as const;
+export type NetworkPolicyMode = (typeof NETWORK_POLICY_MODES)[number];
+
+export const PROXY_SCHEMES = ["socks5h", "socks5", "http", "https"] as const;
+export type ProxyScheme = (typeof PROXY_SCHEMES)[number];
+
+export type NetworkExit = {
+ id: string;
+ label: string;
+ scheme: ProxyScheme;
+ host: string;
+ port: number;
+ // Whether the proxy needs a user and password — kept in the key file.
+ credentials: boolean;
+ enabled: boolean;
+};
+
+export type NetworkPlatformPolicy = {
+ exits: string[];
+ mode: NetworkPolicyMode;
+ kinds: NetworkRequestKind[];
+};
+
+export type NetworkSettings = {
+ exits: NetworkExit[];
+ platforms: Record<string, NetworkPlatformPolicy>;
+ jars: Record<string, string>;
+ echoUrl: string;
+ credentialsFile: string;
+ startupProbe: boolean;
+};
+
+export const DEFAULT_NETWORK_CREDENTIALS_FILE = "~/.config/archilyzer/network-exits.env";
+
+// THE TRIAL'S SCOPE — the one place it is widened, deliberately, later.
+export const TRIAL_SCOPE: Readonly<Record<string, readonly NetworkRequestKind[]>> = Object.freeze({
+ rumble: Object.freeze(["listing"] as NetworkRequestKind[]),
+ twitch: Object.freeze(["listing"] as NetworkRequestKind[]),
+});
+
+export const TRIAL_SCOPE_SENTENCE =
+ "the network-exit trial routes only the listing requests of rumble and twitch; every other " +
+ "platform and request kind goes direct (TRIAL_SCOPE in common/lib/networkExits.ts)";
+
+export const JAR_TRIAL_SENTENCE =
+ "a request that carries a login (a cookie jar, a browser's cookies, a token) goes direct in the " +
+ "network-exit trial — a login is never moved to another address";
+
+export function isRoutable(platform: string, kind: NetworkRequestKind): boolean {
+ return (TRIAL_SCOPE[platform] ?? []).includes(kind);
+}
+
+export const NETWORK_SETTINGS_FIELD_DOCS: FieldDocs<NetworkSettings> = {
+ exits:
+ "NAMED NETWORK EXITS: proxies a fetch may leave through, `[{id, label, scheme, host, port, credentials, " +
+ "enabled}]` (table below). The exit `direct` (no proxy) always exists and is reserved. Written by `pnpm ops " +
+ "network` and /settings → Network exits, never by `pnpm ops settings`. It spreads logged-out listing load over " +
+ "addresses and lets the archive list a site that does not answer the home address; it is not a disguise — no " +
+ "fingerprint or user-agent spoofing is added, and a login never moves between addresses. Worked example, " +
+ "Mullvad: while the machine is connected to the VPN, each WireGuard relay offers a SOCKS5 proxy at its own " +
+ "hostname on port 1080 (`socks5h://nl-ams-wg-socks5-001.relays.mullvad.net:1080`), resolvable only inside the " +
+ "tunnel — https://mullvad.net/en/help/socks5-proxy and " +
+ "https://mullvad.net/en/help/different-entryexit-node-using-wireguard-and-socks5-proxy .",
+ platforms:
+ "Which exits a platform queue's requests may use, keyed by platform: `{exits: [ids], mode: \"sticky\", kinds: " +
+ "[\"listing\"]}` (table below). Absent = every request goes direct, exactly as before. THE TRIAL routes only " +
+ "the LISTING (flat-playlist) requests of `rumble` and `twitch`; any other platform or kind is refused when " +
+ "saved; written by hand, it fails every rumble and twitch listing until fixed. Each channel's exit is chosen once, on its first listing, by a stable " +
+ "hash of its slug over the platform's enabled exits and recorded in `channels/<slug>/network-exit.json`; only " +
+ "`pnpm ops network-exit` changes it. A recorded exit that is disabled or removed FAILS that channel's listing " +
+ "(naming the reassignment) — it is never re-chosen and never sent direct; a policy whose exits are all disabled " +
+ "fails every listing on the platform (`direct` is used only when the policy names it). Once any policy exists, no " +
+ "child process inherits a proxy variable (common/lib/childEnvGuard.mjs). One job keeps one exit for all its " +
+ "pages. Pacing stays per platform: the job gap, the pace, the cooldown and the hold count every exit together. " +
+ "A rate limit or bot check through an exit rests that exit for the platform (the platform cooldown's length); " +
+ "its channels' listings wait (the job ends deferred) and never move to another exit; when every exit rests " +
+ "after a rate limit the platform cools down as before. A proxy that does not answer, or a listing whose yt-dlp " +
+ "output does not show the proxy, fails naming the exit — never a fallback to direct.",
+ jars:
+ "A cookie jar's one fixed exit, keyed by jar id (`browser:<spec>`, `file:<path>`, `login:<option>`, " +
+ "`header`, `config`). A request that carries a login is pinned: direct in the trial, never the platform's " +
+ "pool, and a jar's exit is not changed while the jar is fresh. In the trial every assignment is refused: " +
+ "logged-in requests go direct — so a Rumble channel listing with its Firefox clearance cookie (the default " +
+ "for a new Rumble channel) stays direct, and the trial on Rumble covers only cookie-free channels.",
+ echoUrl:
+ "An address-echo URL (`http(s)://…`, answering the caller's public address as text) that the operator's " +
+ "`pnpm ops get network --probe` fetches through each exit to show the address it presents. Never fetched by " +
+ "the startup probe. Blank (the default) = no echo request at all.",
+ credentialsFile:
+ "The PATH of the mode-600 file holding the exits' credentials, one line per exit with `credentials: true`: " +
+ "`NETWORK_EXIT_<ID>=user:password` (ID upper-cased, `-` as `_`; each part percent-encoded: `my pass#1` is " +
+ "`my%20pass%231`). The environment variable of the same name wins (it is moved out of the environment at boot, so no " +
+ "child process inherits it). An absolute or `~/` path under the user's config directory (`~/.config`, or " +
+ "`$XDG_CONFIG_HOME`) or `ARCHILYZER_CREDENTIALS_DIR`; owned by the user, mode 600. Never the credentials themselves — " +
+ "a value that is not such a path is refused.",
+ startupProbe:
+ "A minute after the editor boots, check that each enabled exit's proxy accepts a TCP connection (no SOCKS " +
+ "greeting, no destination, no echo). One line per exit in the server log. false = no connection at boot.",
+};
+
+export const NETWORK_EXIT_FIELD_DOCS: FieldDocs<NetworkExit> = {
+ id:
+ "The exit's name in policies, records and `pnpm ops`: lowercase letters, digits and `-`, up to 40, not " +
+ "`direct`. Records store this, never the proxy.",
+ label: "A display name (defaults to the id).",
+ scheme:
+ "`socks5h` (the hostname is resolved by the proxy), `socks5` (resolved here), `http` or `https`. `pnpm ops " +
+ "network` also takes the whole as `proxy: \"socks5h://host:port\"`.",
+ host: "The proxy's hostname or IP address (letters, digits, `.`, `-`; an IPv6 address in brackets).",
+ port: "The proxy's port, 1–65535.",
+ credentials:
+ "Whether the proxy needs a user and password. They are read from `network.credentialsFile` (or its " +
+ "environment variable), never from settings.json; an exit that needs them and has none fails its listings.",
+ enabled:
+ "Off = the exit is out of every pool; a channel already recorded on it fails its listings until `pnpm ops " +
+ "network-exit` moves it.",
+};
+
+export const NETWORK_PLATFORM_POLICY_FIELD_DOCS: FieldDocs<NetworkPlatformPolicy> = {
+ exits: "The exit ids the platform's channels are spread over, `direct` allowed. Disabled exits are skipped.",
+ mode: "`sticky` (the only mode): a channel keeps its exit; never chosen per request, never moved on a failure.",
+ kinds: "The request kinds routed (default `[\"listing\"]`). The trial allows `listing` only.",
+};
+
+export function defaultNetworkSettings(): NetworkSettings {
+ return { exits: [], platforms: {}, jars: {}, echoUrl: "", credentialsFile: DEFAULT_NETWORK_CREDENTIALS_FILE, startupProbe: true };
+}
+
+const EXIT_ID_RE = /^[a-z0-9][a-z0-9-]{0,39}$/;
+const PLATFORM_KEY_RE = /^[a-z0-9][a-z0-9.-]{0,99}$/;
+const HOST_RE = /^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,62})(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,62}))*|\[[0-9A-Fa-f:.]+\])$/;
+// Unreserved characters and %XX, nothing else (RFC 3986): what the key file's
+// user and password may hold, so no parser — ours, yt-dlp's, a config line's —
+// can read them differently.
+const ENCODED_PART_RE = /^(?:[A-Za-z0-9\-._~]|%[0-9A-Fa-f]{2})+$/;
+
+export const PERCENT_ENCODE_SENTENCE =
+ "percent-encode the user and the password (every character but letters, digits and - . _ ~ — for example " +
+ "`my pass#1` is `my%20pass%231`; encodeURIComponent does it)";
+
+function isObject(v: unknown): v is Record<string, unknown> {
+ return typeof v === "object" && v !== null && !Array.isArray(v);
+}
+
+function hostOk(h: unknown): h is string {
+ return typeof h === "string" && h.length <= 253 && HOST_RE.test(h);
+}
+
+function portOk(p: unknown): p is number {
+ return typeof p === "number" && Number.isInteger(p) && p >= 1 && p <= 65535;
+}
+
+function schemeOf(s: unknown): ProxyScheme | null {
+ return typeof s === "string" && (PROXY_SCHEMES as readonly string[]).includes(s) ? (s as ProxyScheme) : null;
+}
+
+// A PROXY URL TYPED BY THE OPERATOR, read into its stored parts — never its
+// credentials. Parsed by hand (no WHATWG URL normalising one thing while
+// yt-dlp reads another), and a URL that carries userinfo is refused: with the
+// encoding sentence when it is not percent-encoded, always with where the
+// credentials go instead. Never echoes the input.
+export function parseProxyInput(raw: unknown): { scheme: ProxyScheme; host: string; port: number } | { error: string } {
+ if (typeof raw !== "string" || raw.trim() === "") return { error: "no proxy URL" };
+ const s = raw.trim();
+ const m = /^([A-Za-z0-9+.-]+):\/\/(.*)$/s.exec(s);
+ const scheme = schemeOf(m?.[1]?.toLowerCase());
+ if (!m || !scheme) return { error: "the proxy URL's scheme must be socks5h://, socks5://, http:// or https://" };
+ let rest = m[2]!;
+ if (!rest.includes("@") && /[/?#]/.test(rest.replace(/\/$/, ""))) {
+ return { error: "the proxy URL is scheme://host:port, with no path, query or fragment" };
+ }
+ rest = rest.replace(/\/$/, "");
+ const at = rest.lastIndexOf("@");
+ // eslint-disable-next-line no-control-regex
+ if (at < 0 && /[\s\u0000-\u001f\u007f]/.test(rest)) return { error: "the proxy URL holds whitespace or a control character" };
+ if (at >= 0) {
+ const info = rest.slice(0, at);
+ const encoded = info.split(":").every((p) => p === "" || ENCODED_PART_RE.test(p)) && info.split(":").length <= 2;
+ return {
+ error:
+ (encoded ? "" : `the proxy URL's credentials are not percent-encoded — ${PERCENT_ENCODE_SENTENCE}. `) +
+ "Proxy credentials are not a setting — give the exit `credentials: true` and put " +
+ "NETWORK_EXIT_<ID>=user:password (percent-encoded) in the mode-600 file network.credentialsFile names",
+ };
+ }
+ const hp = /^(\[[^\]]*\]|[^:]*):(\d{1,5})$/.exec(rest);
+ if (!hp) return { error: "the proxy URL must name its host and port (socks5h://host:1080)" };
+ const host = hp[1]!;
+ const port = Number(hp[2]);
+ if (!hostOk(host)) return { error: "the proxy URL's host is not a hostname or an IP address" };
+ if (!portOk(port)) return { error: "the proxy URL's port is not 1–65535" };
+ return { scheme, host, port };
+}
+
+export type ExitCredentials = { username: string; password: string; encoded: string };
+
+// A key-file value, `user:password`, each part percent-encoded. Never echoes it.
+export function parseCredentials(raw: string): ExitCredentials | { error: string } {
+ const v = raw.trim();
+ const i = v.indexOf(":");
+ if (i <= 0 || i === v.length - 1) return { error: `the credentials are not user:password — ${PERCENT_ENCODE_SENTENCE}` };
+ const user = v.slice(0, i);
+ const pass = v.slice(i + 1);
+ if (!ENCODED_PART_RE.test(user) || !ENCODED_PART_RE.test(pass)) {
+ return { error: `the credentials hold characters that are not percent-encoded — ${PERCENT_ENCODE_SENTENCE}` };
+ }
+ try {
+ return { username: decodeURIComponent(user), password: decodeURIComponent(pass), encoded: `${user}:${pass}` };
+ } catch {
+ return { error: `the credentials are not valid percent-encoding — ${PERCENT_ENCODE_SENTENCE}` };
+ }
+}
+
+export function credentialsEnvKey(id: string): string {
+ return `NETWORK_EXIT_${id.toUpperCase().replace(/-/g, "_")}`;
+}
+
+// What to show for an exit anywhere: built from the stored parts, so it has
+// no secret in it to mask.
+export function exitDisplay(e: Pick<NetworkExit, "scheme" | "host" | "port" | "credentials">): string {
+ return `${e.scheme}://${e.host}:${e.port}${e.credentials ? " (credentials)" : ""}`;
+}
+
+// THE PROXY URL A CHILD IS GIVEN (internal only — stdin, the proxy client).
+export function proxyUrlOf(e: Pick<NetworkExit, "scheme" | "host" | "port">, creds: ExitCredentials | null): string {
+ return `${e.scheme}://${creds ? `${creds.encoded}@` : ""}${e.host}:${e.port}`;
+}
+
+// The exact strings a child's output must never carry into a log: the
+// encoded userinfo, the user, the password encoded, decoded and as a Python
+// repr (yt-dlp -v prints the config as one). Values, never a pattern.
+export function secretFragmentsOf(creds: ExitCredentials | null): string[] {
+ if (!creds) return [];
+ const [user, pass] = [creds.encoded.slice(0, creds.encoded.indexOf(":")), creds.encoded.slice(creds.encoded.indexOf(":") + 1)];
+ const repr = (s: string) => s.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
+ const out = new Set([creds.encoded, user, pass, creds.username, creds.password, repr(creds.password), repr(creds.username)]);
+ return [...out].filter((f) => f.length > 0).sort((a, b) => b.length - a.length);
+}
+
+export function redactFragments(text: string, fragments: readonly string[]): string {
+ let out = text;
+ for (const f of fragments) out = out.split(f).join("<redacted>");
+ return out;
+}
+
+function exitFromRaw(e: Record<string, unknown>): NetworkExit | null {
+ const id = typeof e.id === "string" ? e.id.trim() : "";
+ const scheme = schemeOf(e.scheme);
+ if (!EXIT_ID_RE.test(id) || id === DIRECT_EXIT || !scheme || !hostOk(e.host) || !portOk(e.port)) return null;
+ const label = typeof e.label === "string" && e.label.trim() ? e.label.trim().slice(0, 80) : id;
+ return { id, label, scheme, host: e.host, port: e.port, credentials: e.credentials === true, enabled: e.enabled !== false };
+}
+
+// THE TOTAL READER (the settings schema's coercion). Keeps every structurally
+// valid entry and drops what is not. It never decides a route: the listing
+// reads the file strictly (controller/networkExits.ts loadNetworkStrict) and
+// FAILS on anything networkSettingsProblems refuses.
+export function sanitizeNetwork(v: unknown): NetworkSettings {
+ const r = isObject(v) ? v : {};
+ const exits: NetworkExit[] = [];
+ const seen = new Set<string>();
+ for (const e of Array.isArray(r.exits) ? r.exits : []) {
+ if (!isObject(e)) continue;
+ const x = exitFromRaw(e);
+ if (!x || seen.has(x.id)) continue;
+ seen.add(x.id);
+ exits.push(x);
+ }
+ const platforms: Record<string, NetworkPlatformPolicy> = {};
+ if (isObject(r.platforms)) {
+ for (const [p, raw] of Object.entries(r.platforms)) {
+ if (!PLATFORM_KEY_RE.test(p) || !isObject(raw)) continue;
+ const ids = (Array.isArray(raw.exits) ? raw.exits : []).filter(
+ (x): x is string => typeof x === "string" && (x === DIRECT_EXIT || EXIT_ID_RE.test(x)),
+ );
+ const kinds = (Array.isArray(raw.kinds) ? raw.kinds : ["listing"]).filter(
+ (k): k is NetworkRequestKind => (NETWORK_REQUEST_KINDS as readonly unknown[]).includes(k),
+ );
+ if (ids.length === 0) continue;
+ platforms[p] = { exits: [...new Set(ids)], mode: "sticky", kinds: kinds.length ? [...new Set(kinds)] : ["listing"] };
+ }
+ }
+ const jars: Record<string, string> = {};
+ if (isObject(r.jars)) {
+ for (const [jar, exit] of Object.entries(r.jars)) {
+ if (jar.length === 0 || jar.length > 300 || typeof exit !== "string") continue;
+ if (exit !== DIRECT_EXIT && !EXIT_ID_RE.test(exit)) continue;
+ jars[jar] = exit;
+ }
+ }
+ const echoUrl = typeof r.echoUrl === "string" && validEchoUrl(r.echoUrl.trim()) ? r.echoUrl.trim() : "";
+ const credentialsFile =
+ typeof r.credentialsFile === "string" && looksLikePath(r.credentialsFile) ? r.credentialsFile.trim() : DEFAULT_NETWORK_CREDENTIALS_FILE;
+ return { exits, platforms, jars, echoUrl, credentialsFile, startupProbe: r.startupProbe !== false };
+}
+
+// An absolute path or one under the home directory (`~/`), no `..`, no
+// whitespace (review 2 nit 8). Where it may live (the config directory, or
+// ARCHILYZER_CREDENTIALS_DIR) and its owner and mode are checked when it is
+// read (lib/networkCredentials-server.ts).
+function looksLikePath(v: string): boolean {
+ if (v !== v.trim() || /\s/.test(v)) return false;
+ if (!v.startsWith("/") && !v.startsWith("~/")) return false;
+ return !v.split("/").includes("..");
+}
+
+function validEchoUrl(s: string): boolean {
+ if (s === "") return true;
+ try {
+ const u = new URL(s);
+ return (u.protocol === "http:" || u.protocol === "https:") && !u.username && !u.password;
+ } catch {
+ return false;
+ }
+}
+
+const NETWORK_KEYS = ["exits", "platforms", "jars", "echoUrl", "credentialsFile", "startupProbe"];
+const EXIT_KEYS = ["id", "label", "scheme", "host", "port", "credentials", "enabled"];
+
+// THE STRICT CHECK every writer refuses with — and the listing fails on: one
+// sentence per problem, each naming its path. Never echoes a value that could
+// be a secret.
+export function networkSettingsProblems(v: unknown): string[] {
+ const problems: string[] = [];
+ if (!isObject(v)) return ["network: must be an object {exits, platforms, jars, echoUrl, credentialsFile, startupProbe}"];
+ for (const k of Object.keys(v)) {
+ if (!NETWORK_KEYS.includes(k)) problems.push(`network.${k}: not a network key (${NETWORK_KEYS.join(", ")})`);
+ }
+ const ids = new Set<string>();
+ if (v.exits !== undefined && !Array.isArray(v.exits)) problems.push("network.exits: must be a list");
+ (Array.isArray(v.exits) ? v.exits : []).forEach((e, i) => {
+ const at = `network.exits[${i}]`;
+ if (!isObject(e)) return problems.push(`${at}: must be {${EXIT_KEYS.join(", ")}}`);
+ for (const k of Object.keys(e)) {
+ if (!EXIT_KEYS.includes(k)) {
+ problems.push(
+ `${at}.${k}: not an exit key (${EXIT_KEYS.join(", ")})` +
+ (k === "proxy" ? " — an exit is stored as scheme, host and port; its credentials live in network.credentialsFile" : ""),
+ );
+ }
+ }
+ const id = typeof e.id === "string" ? e.id : "";
+ if (id === DIRECT_EXIT) problems.push(`${at}.id: "direct" is the built-in exit with no proxy and cannot be redefined`);
+ else if (!EXIT_ID_RE.test(id)) problems.push(`${at}.id: lowercase letters, digits and "-", up to 40 characters`);
+ else if (ids.has(id)) problems.push(`${at}.id: "${id}" is defined twice`);
+ else ids.add(id);
+ if (!schemeOf(e.scheme)) problems.push(`${at}.scheme: socks5h, socks5, http or https`);
+ if (!hostOk(e.host)) problems.push(`${at}.host: a hostname or an IP address (no credentials, no spaces)`);
+ if (!portOk(e.port)) problems.push(`${at}.port: a whole number 1–65535`);
+ if (e.label !== undefined && typeof e.label !== "string") problems.push(`${at}.label: must be a string`);
+ if (e.enabled !== undefined && typeof e.enabled !== "boolean") problems.push(`${at}.enabled: must be true or false`);
+ if (e.credentials !== undefined && typeof e.credentials !== "boolean") problems.push(`${at}.credentials: must be true or false`);
+ });
+ if (v.platforms !== undefined && !isObject(v.platforms)) problems.push("network.platforms: must be an object keyed by platform");
+ for (const [platform, raw] of Object.entries(isObject(v.platforms) ? v.platforms : {})) {
+ const at = `network.platforms.${platform}`;
+ if (!isObject(raw)) {
+ problems.push(`${at}: must be {exits, mode: "sticky", kinds}`);
+ continue;
+ }
+ for (const k of Object.keys(raw)) {
+ if (!["exits", "mode", "kinds"].includes(k)) problems.push(`${at}.${k}: not a policy key (exits, mode, kinds)`);
+ }
+ const exits = Array.isArray(raw.exits) ? raw.exits : null;
+ const nonDirect = (exits ?? []).some((x) => x !== DIRECT_EXIT);
+ if (!(platform in TRIAL_SCOPE)) {
+ if (nonDirect || exits === null) problems.push(`${at}: refused — ${TRIAL_SCOPE_SENTENCE}`);
+ continue;
+ }
+ const kinds = raw.kinds === undefined ? ["listing"] : raw.kinds;
+ if (!Array.isArray(kinds) || kinds.length === 0) problems.push(`${at}.kinds: a non-empty list of request kinds`);
+ else {
+ for (const k of kinds) {
+ if (!(NETWORK_REQUEST_KINDS as readonly unknown[]).includes(k)) {
+ problems.push(`${at}.kinds: "${String(k)}" is not a request kind (${NETWORK_REQUEST_KINDS.join(", ")})`);
+ } else if (!isRoutable(platform, k as NetworkRequestKind) && nonDirect) {
+ problems.push(`${at}.kinds: "${String(k)}" refused — ${TRIAL_SCOPE_SENTENCE}`);
+ }
+ }
+ }
+ if (raw.mode !== undefined && raw.mode !== "sticky") {
+ problems.push(`${at}.mode: "sticky" is the only mode — a channel keeps its exit; exits are never chosen per request or at random`);
+ }
+ if (exits === null || exits.length === 0) {
+ problems.push(`${at}.exits: a non-empty list of exit ids ("direct" allowed)`);
+ continue;
+ }
+ const seen = new Set<unknown>();
+ for (const x of exits) {
+ if (seen.has(x)) problems.push(`${at}.exits: "${String(x)}" is listed twice`);
+ seen.add(x);
+ if (x === DIRECT_EXIT) continue;
+ if (typeof x !== "string" || !ids.has(x)) problems.push(`${at}.exits: "${String(x)}" is not a defined exit`);
+ }
+ }
+ if (v.jars !== undefined && !isObject(v.jars)) problems.push("network.jars: must be an object keyed by jar id");
+ for (const [jar, exit] of Object.entries(isObject(v.jars) ? v.jars : {})) {
+ if (exit === DIRECT_EXIT) continue;
+ problems.push(`network.jars.${jar}: refused — ${JAR_TRIAL_SENTENCE}`);
+ }
+ if (v.echoUrl !== undefined && (typeof v.echoUrl !== "string" || !validEchoUrl(v.echoUrl.trim()))) {
+ problems.push("network.echoUrl: blank, or an http(s) URL with no credentials");
+ }
+ if (v.credentialsFile !== undefined && (typeof v.credentialsFile !== "string" || !looksLikePath(v.credentialsFile))) {
+ problems.push(
+ "network.credentialsFile: the PATH of the mode-600 file that holds the exits' credentials — the value sent is " +
+ "not a path; refused, not stored",
+ );
+ }
+ if (v.startupProbe !== undefined && typeof v.startupProbe !== "boolean") problems.push("network.startupProbe: true or false");
+ return problems;
+}
+
+// FNV-1a, 32 bits, over the UTF-8 bytes: stable across processes, releases
+// and machines (never Math.random, never a per-process seed).
+export function stableHash(s: string): number {
+ let h = 0x811c9dc5;
+ for (const b of new TextEncoder().encode(s)) {
+ h ^= b;
+ h = Math.imul(h, 0x01000193) >>> 0;
+ }
+ return h >>> 0;
+}
+
+export function stickyExitFor(slug: string, pool: readonly string[]): string {
+ if (pool.length === 0) return DIRECT_EXIT;
+ return pool[stableHash(slug) % pool.length]!;
+}
+
+// The platform's pool for `kind`: its policy's exits that are enabled (direct
+// always is), in policy order; null = no policy (direct), and for a platform
+// or kind outside the trial's scope.
+export function exitPool(
+ network: NetworkSettings | undefined,
+ platform: string,
+ kind: NetworkRequestKind,
+): string[] | null {
+ const policy = network?.platforms?.[platform];
+ if (!policy || !isRoutable(platform, kind) || !policy.kinds.includes(kind)) return null;
+ const enabled = new Set(network!.exits.filter((e) => e.enabled).map((e) => e.id));
+ return policy.exits.filter((id) => id === DIRECT_EXIT || enabled.has(id));
+}
+
+export function exitById(network: NetworkSettings | undefined, id: string): NetworkExit | undefined {
+ return network?.exits.find((e) => e.id === id);
+}
+
+// WHAT EACH OPTION MEANS is a person's classification (lib/ytdlpOptionClasses.ts);
+// an option it does not list counts as `config` — a login, pinned direct.
+function optionClass(long: string): YtdlpOptionClass {
+ return YTDLP_OPTION_CLASSES[long] ?? "config";
+}
+
+const LONG = new Map(YTDLP_OPTIONS.map(([, l, v]) => [l, v] as const));
+const SHORT = new Map(YTDLP_OPTIONS.filter(([s]) => s !== null).map(([s, l, v]) => [s!, { long: l, value: v }] as const));
+
+// yt-dlp's (optparse's) rule for a long option: the exact name, else the one
+// name the argument is a prefix of. null: unknown or ambiguous — yt-dlp would
+// refuse it, or it is a user alias; either way the request is not logged-out.
+export function resolveLongOption(name: string): string | null {
+ if (LONG.has(name)) return name;
+ const hits = [...LONG.keys()].filter((l) => l.startsWith(name));
+ return hits.length === 1 ? hits[0]! : null;
+}
+
+type ArgvOption = { long: string | null; raw: string; value?: string };
+
+// The options of an argv as yt-dlp reads them (`--` ends options; a value-
+// taking option swallows its value; a short cluster is flags until a
+// value-taking one, which takes the rest). Positional arguments come back as
+// `{long: null}` with `raw` set... only when they hold a URL with userinfo.
+function argvOptions(argv: readonly string[]): { options: ArgvOption[]; userinfoUrl: boolean } {
+ const options: ArgvOption[] = [];
+ let userinfoUrl = false;
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i]!;
+ if (a === "--") {
+ for (const p of argv.slice(i + 1)) if (/^[a-z][a-z0-9+.-]*:\/\/[^/?#]*@/i.test(p)) userinfoUrl = true;
+ break;
+ }
+ if (a.startsWith("--")) {
+ const eq = a.indexOf("=");
+ const name = eq < 0 ? a : a.slice(0, eq);
+ const long = resolveLongOption(name);
+ let value: string | undefined = eq < 0 ? undefined : a.slice(eq + 1);
+ if (long && LONG.get(long) && value === undefined) value = argv[++i];
+ options.push({ long, raw: name, ...(value !== undefined ? { value } : {}) });
+ continue;
+ }
+ if (a.startsWith("-") && a.length > 1) {
+ for (let j = 1; j < a.length; j++) {
+ const opt = SHORT.get(a[j]!);
+ if (!opt) {
+ options.push({ long: null, raw: `-${a[j]}` });
+ break;
+ }
+ if (opt.value) {
+ const rest = a.slice(j + 1);
+ options.push({ long: opt.long, raw: `-${a[j]}`, value: rest !== "" ? rest : argv[++i] });
+ break;
+ }
+ options.push({ long: opt.long, raw: `-${a[j]}` });
+ }
+ continue;
+ }
+ if (/^[a-z][a-z0-9+.-]*:\/\/[^/?#]*@/i.test(a)) userinfoUrl = true;
+ }
+ return { options, userinfoUrl };
+}
+
+// THE LOGIN A REQUEST CARRIES, read off its final argv with yt-dlp's own
+// option rules: the jar id, or null for a logged-out request. Conservative by
+// design (review 1 finding 4, review 2 nit 6): a cookie, a credential, a
+// token-bearing extractor argument, any extra header, another config, an
+// alias, an info file, an unknown or ambiguous option, or a URL with
+// userinfo pins the request. The routed listing also passes --ignore-config.
+export function requestJar(argv: readonly string[]): string | null {
+ const { options, userinfoUrl } = argvOptions(argv);
+ for (const o of options) {
+ if (o.long === null) return "config";
+ if (o.long === "--cookies-from-browser") return `browser:${o.value ?? ""}`;
+ if (o.long === "--cookies") return `file:${o.value ?? ""}`;
+ const c = optionClass(o.long);
+ if (c === "cookie" || c === "login") return `login:${o.long}`;
+ if (c === "header") return "header";
+ if (c === "config") return "config";
+ }
+ return userinfoUrl ? "login:url" : null;
+}
+
+// The channel's own proxy in its args (`--proxy`, `--prox`, `--geo-verification-
+// proxy`, …): today's request, which the channel's explicit proxy carries.
+export function ownProxy(argv: readonly string[]): boolean {
+ return argvOptions(argv).options.some((o) => o.long !== null && YTDLP_OPTION_CLASSES[o.long] === "proxy");
+}
+
+// A JAR NEVER USES TWO EXITS: changing a jar's exit while the jar is fresh
+// is refused (an account seen from two addresses invites a lock). Unused in
+// the trial, where every assignment is refused earlier; built so a later
+// widening cannot rotate a login by accident.
+export function jarExitChangeRefusal(args: {
+ jar: string;
+ from: string | undefined;
+ to: string;
+ jarFresh: boolean;
+}): string | null {
+ const from = args.from ?? DIRECT_EXIT;
+ if (from === args.to || !args.jarFresh) return null;
+ return (
+ `network.jars.${args.jar}: refused — the jar is fresh and has been used from "${from}"; an account seen ` +
+ `from two addresses invites a lock. Let the login expire (or log out) before giving it "${args.to}".`
+ );
+}
+
+// A listing that could not be sent through its network exit — the proxy did
+// not answer, the settings could not be read, the recorded exit is gone, the
+// credentials are missing, or yt-dlp's output did not show the proxy. Never
+// retried direct.
+export class NetworkExitError extends Error {
+ readonly exit: string;
+ constructor(exit: string, message: string) {
+ super(message);
+ this.name = "NetworkExitError";
+ this.exit = exit;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// ONE WRITE OF THE BLOCK — what `pnpm ops network` and the /settings section
+// both send, applied to the stored block. Pure; the writers then refuse the
+// result with networkSettingsProblems and save it through saveSettings.
+//
+// exits: [...] the whole list (stored form)
+// upsertExit: {id, label?, proxy? | scheme?/host?/port?, credentials?, enabled?}
+// removeExit: "<id>" one exit gone — and out of every policy
+// platforms: {<p>: policy | null} merged per platform; null removes
+// jars: {...} the whole map (refused in the trial unless every value is direct)
+// echoUrl, credentialsFile, startupProbe
+export const NETWORK_REQUEST_KEYS = [
+ "exits",
+ "upsertExit",
+ "removeExit",
+ "platforms",
+ "jars",
+ "echoUrl",
+ "credentialsFile",
+ "startupProbe",
+] as const;
+
+export class NetworkRequestError extends Error {}
+
+export function applyNetworkRequest(current: NetworkSettings, body: Record<string, unknown>): Record<string, unknown> {
+ const unknown = Object.keys(body).filter((k) => !(NETWORK_REQUEST_KEYS as readonly string[]).includes(k));
+ if (unknown.length) {
+ throw new NetworkRequestError(`unknown key(s): ${unknown.join(", ")} — accepted: ${NETWORK_REQUEST_KEYS.join(", ")}`);
+ }
+ if (Object.keys(body).length === 0) throw new NetworkRequestError("nothing to change");
+ let exits: unknown[] = current.exits.map((e) => ({ ...e }));
+ let platforms: Record<string, unknown> = Object.fromEntries(
+ Object.entries(current.platforms).map(([p, v]) => [p, { ...v, exits: [...v.exits], kinds: [...v.kinds] }]),
+ );
+ if (body.exits !== undefined) {
+ if (!Array.isArray(body.exits)) throw new NetworkRequestError("exits: must be a list");
+ exits = body.exits;
+ }
+ if (body.upsertExit !== undefined) {
+ const u = body.upsertExit;
+ if (!isObject(u) || typeof u.id !== "string") {
+ throw new NetworkRequestError("upsertExit: must be {id, label?, proxy?, credentials?, enabled?}");
+ }
+ const i = exits.findIndex((e) => isObject(e) && e.id === u.id);
+ const prev = i >= 0 ? (exits[i] as Record<string, unknown>) : undefined;
+ let parts: Record<string, unknown> = {};
+ if (u.proxy !== undefined) {
+ const p = parseProxyInput(u.proxy);
+ if ("error" in p) throw new NetworkRequestError(`upsertExit.proxy: ${p.error}`);
+ parts = p;
+ } else {
+ for (const k of ["scheme", "host", "port"]) if (u[k] !== undefined) parts[k] = u[k];
+ }
+ if (!prev && parts.host === undefined) throw new NetworkRequestError(`upsertExit: a new exit "${u.id}" needs its proxy (scheme://host:port)`);
+ const merged: Record<string, unknown> = {
+ id: u.id,
+ label: u.label ?? prev?.label ?? u.id,
+ scheme: parts.scheme ?? prev?.scheme,
+ host: parts.host ?? prev?.host,
+ port: parts.port ?? prev?.port,
+ credentials: u.credentials ?? prev?.credentials ?? false,
+ enabled: u.enabled ?? prev?.enabled ?? true,
+ };
+ for (const k of Object.keys(u)) if (![...EXIT_KEYS, "proxy"].includes(k)) merged[k] = u[k];
+ if (i >= 0) exits[i] = merged;
+ else exits.push(merged);
+ }
+ if (body.removeExit !== undefined) {
+ const id = body.removeExit;
+ if (typeof id !== "string" || !exits.some((e) => isObject(e) && e.id === id)) {
+ throw new NetworkRequestError(`removeExit: no exit "${String(id)}"`);
+ }
+ exits = exits.filter((e) => !(isObject(e) && e.id === id));
+ for (const [p, v] of Object.entries(platforms)) {
+ if (!isObject(v) || !Array.isArray(v.exits)) continue;
+ const left = v.exits.filter((x) => x !== id);
+ if (left.length) platforms[p] = { ...v, exits: left };
+ else delete platforms[p];
+ }
+ }
+ if (body.platforms !== undefined) {
+ if (!isObject(body.platforms)) throw new NetworkRequestError("platforms: must be an object keyed by platform");
+ platforms = { ...platforms };
+ for (const [p, v] of Object.entries(body.platforms)) {
+ if (v === null) delete platforms[p];
+ else platforms[p] = v;
+ }
+ }
+ return {
+ exits,
+ platforms,
+ jars: body.jars !== undefined ? body.jars : { ...current.jars },
+ echoUrl: body.echoUrl !== undefined ? body.echoUrl : current.echoUrl,
+ credentialsFile: body.credentialsFile !== undefined ? body.credentialsFile : current.credentialsFile,
+ startupProbe: body.startupProbe !== undefined ? body.startupProbe : current.startupProbe,
+ };
+}
diff --git a/common/lib/networkProxy-server.test.ts b/common/lib/networkProxy-server.test.ts
@@ -0,0 +1,92 @@
+import { test, after } from "node:test";
+import assert from "node:assert/strict";
+import {
+ addressInEcho,
+ getThroughProxy,
+ openTunnel,
+ preflightProxy,
+} from "./networkProxy-server";
+import {
+ closedPort,
+ startCountingServer,
+ startEchoServer,
+ startFakeHttpProxy,
+ startFakeSocks5,
+} from "../testing/fakeProxy";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/networkProxy-server.test.ts
+//
+// Every server is in this process, on 127.0.0.1. The destination names
+// (`echo.exit.test`) are never resolved here: a socks5h proxy is handed the
+// name, and the fake maps it to the loopback echo server.
+
+const echo = await startEchoServer("203.0.113.7\n");
+const direct = await startCountingServer();
+// The fakes tunnel to the echo server only; anything else is refused.
+const routeEcho = (host: string, port: number) =>
+ ["echo.exit.test", "127.0.0.1", "::1"].includes(host) && port === echo.port ? { host: "127.0.0.1", port } : null;
+const socksAuth = await startFakeSocks5({ username: "example-user", password: "fake:value#1", route: routeEcho });
+const socksOpen = await startFakeSocks5({ route: routeEcho });
+const httpProxy = await startFakeHttpProxy({ auth: "example-user:fake-value", route: routeEcho });
+
+after(async () => {
+ await Promise.all([echo.close(), direct.close(), socksAuth.close(), socksOpen.close(), httpProxy.close()]);
+});
+
+const authUrl = `socks5h://example-user:${encodeURIComponent("fake:value#1")}@127.0.0.1:${socksAuth.port}`;
+
+test("preflight: a SOCKS5 proxy that accepts the exit's login answers", async () => {
+ const r = await preflightProxy(authUrl);
+ assert.equal(r.ok, true);
+ assert.equal(socksAuth.connects.length, 0, "a preflight asks no destination");
+});
+
+test("preflight: wrong credentials and a dead proxy fail, never naming the password", async () => {
+ const bad = await preflightProxy(`socks5h://example-user:fake-wrong-value@127.0.0.1:${socksAuth.port}`);
+ assert.equal(bad.ok, false);
+ assert.match((bad as { reason: string }).reason, /refused the exit's username and password/);
+ assert.ok(!(bad as { reason: string }).reason.includes("fake-wrong-value"));
+ const dead = await preflightProxy(`socks5h://u:fake-dead-value@127.0.0.1:${await closedPort()}`);
+ assert.equal(dead.ok, false);
+ assert.equal((dead as { reason: string }).reason, "connection refused");
+ const noCreds = await preflightProxy(`socks5h://127.0.0.1:${socksAuth.port}`);
+ assert.equal(noCreds.ok, false);
+});
+
+test("socks5h hands the NAME to the proxy (DNS through the proxy)", async () => {
+ const before = socksAuth.connects.length;
+ const r = await getThroughProxy(authUrl, `http://echo.exit.test:${echo.port}/`);
+ assert.deepEqual(r, { ok: true, status: 200, body: "203.0.113.7\n" });
+ assert.deepEqual(socksAuth.connects[before], { atyp: "domain", host: "echo.exit.test", port: echo.port });
+});
+
+test("socks5 resolves here and sends an address", async () => {
+ const r = await getThroughProxy(`socks5://127.0.0.1:${socksOpen.port}`, `http://localhost:${echo.port}/`);
+ assert.equal(r.ok, true);
+ assert.notEqual(socksOpen.connects.at(-1)!.atyp, "domain");
+ assert.ok(["127.0.0.1", "::1"].includes(socksOpen.connects.at(-1)!.host));
+});
+
+test("an HTTP CONNECT proxy with Basic auth tunnels; a 407 is a refusal", async () => {
+ const ok = await getThroughProxy(`http://example-user:fake-value@127.0.0.1:${httpProxy.port}`, `http://echo.exit.test:${echo.port}/`);
+ assert.equal(ok.ok, true);
+ assert.equal(addressInEcho((ok as { body: string }).body), "203.0.113.7");
+ const no = await openTunnel(`http://example-user:fake-wrong@127.0.0.1:${httpProxy.port}`, "echo.exit.test", echo.port);
+ assert.equal(no.ok, false);
+ assert.match((no as { reason: string }).reason, /HTTP 407/);
+});
+
+test("a destination the proxy will not reach fails through the proxy — never direct", async () => {
+ const r = await openTunnel(authUrl, "127.0.0.1", direct.port);
+ assert.equal(r.ok, false);
+ assert.match((r as { reason: string }).reason, /could not reach the destination/);
+ assert.equal(direct.connections(), 0);
+});
+
+test("addressInEcho reads plain and JSON echo bodies", () => {
+ assert.equal(addressInEcho("198.51.100.4"), "198.51.100.4");
+ assert.equal(addressInEcho('{"ip":"198.51.100.4"}'), "198.51.100.4");
+ assert.equal(addressInEcho("2001:db8::1\n"), "2001:db8::1");
+ assert.equal(addressInEcho("nothing"), null);
+});
diff --git a/common/lib/networkProxy-server.ts b/common/lib/networkProxy-server.ts
@@ -0,0 +1,383 @@
+// THE PROXY CLIENT behind network exits (lib/networkExits.ts): a preflight
+// that proves an exit's proxy answers before anything is sent through it, and
+// a tunnelled GET for the operator's address-echo probe. SOCKS5 (with and
+// without username/password, `socks5h` handing the hostname to the proxy,
+// `socks5` resolving it here) and HTTP CONNECT over a plain or TLS connection
+// to the proxy. No dependency: the handshakes are a few bytes each.
+//
+// FAIL CLOSED. Every function here either succeeds through the proxy or
+// answers why not; none of them ever opens a connection to the target itself.
+// No error text carries the proxy's credentials.
+
+import net from "node:net";
+import tls from "node:tls";
+import dns from "node:dns/promises";
+import { PROXY_SCHEMES, type ProxyScheme } from "./networkExits";
+
+// The URL here is one this repo built (lib/networkExits.ts proxyUrlOf) from a
+// validated exit and its key-file credentials — never one taken from input.
+type ParsedProxy = { scheme: ProxyScheme; host: string; port: number; username: string; password: string };
+
+function parseProxyUrl(raw: string): ParsedProxy | { error: string } {
+ const m = /^([a-z0-9]+):\/\/(?:([^:@/]*):([^@/]*)@)?(\[[^\]]+\]|[^:/@]+):(\d+)$/.exec(raw);
+ if (!m || !(PROXY_SCHEMES as readonly string[]).includes(m[1]!)) return { error: "the exit's proxy is not scheme://host:port" };
+ try {
+ return {
+ scheme: m[1] as ProxyScheme,
+ username: m[2] ? decodeURIComponent(m[2]) : "",
+ password: m[3] ? decodeURIComponent(m[3]) : "",
+ host: m[4]!.replace(/^\[|\]$/g, ""),
+ port: Number(m[5]),
+ };
+ } catch {
+ return { error: "the exit's credentials are not valid percent-encoding" };
+ }
+}
+
+export const PROXY_TIMEOUT_MS = 8_000;
+
+export type ProxyFailure = { ok: false; reason: string };
+
+class ProxyError extends Error {}
+
+function errText(err: unknown): string {
+ const e = err as NodeJS.ErrnoException;
+ if (e?.code === "ECONNREFUSED") return "connection refused";
+ if (e?.code === "ENOTFOUND" || e?.code === "EAI_AGAIN") return "its host does not resolve";
+ if (e?.code === "ETIMEDOUT") return "timed out";
+ if (e?.code === "ECONNRESET") return "the connection was reset";
+ return e instanceof ProxyError ? e.message : (e?.code ?? (e?.message || String(err)));
+}
+
+// A buffered reader over a socket: `read(n)` resolves with exactly n bytes,
+// `readUntil(sep)` with everything through the separator.
+function reader(sock: net.Socket) {
+ let buf = Buffer.alloc(0);
+ let waiter: (() => void) | null = null;
+ let failed: Error | null = null;
+ const wake = () => {
+ const w = waiter;
+ waiter = null;
+ w?.();
+ };
+ const onData = (c: Buffer) => {
+ buf = Buffer.concat([buf, c]);
+ wake();
+ };
+ const onEnd = () => {
+ failed = failed ?? new ProxyError("the proxy closed the connection");
+ wake();
+ };
+ const onError = (e: Error) => {
+ failed = e;
+ wake();
+ };
+ sock.on("data", onData);
+ sock.on("end", onEnd);
+ sock.on("close", onEnd);
+ sock.on("error", onError);
+ const wait = () => new Promise<void>((r) => (waiter = r));
+ return {
+ async read(n: number): Promise<Buffer> {
+ while (buf.length < n) {
+ if (failed) throw failed;
+ await wait();
+ }
+ const out = buf.subarray(0, n);
+ buf = buf.subarray(n);
+ return out;
+ },
+ async readUntil(sep: string, max = 64 * 1024): Promise<Buffer> {
+ for (;;) {
+ const i = buf.indexOf(sep);
+ if (i >= 0) {
+ const out = buf.subarray(0, i + sep.length);
+ buf = buf.subarray(i + sep.length);
+ return out;
+ }
+ if (buf.length > max) throw new ProxyError("the proxy's answer is too long");
+ if (failed) throw failed;
+ await wait();
+ }
+ },
+ async readAll(max = 64 * 1024): Promise<Buffer> {
+ while (!failed && buf.length <= max) await wait();
+ return buf.subarray(0, max);
+ },
+ // Hand the socket over: stop listening, give back what was read ahead.
+ release(): Buffer {
+ sock.off("data", onData);
+ sock.off("end", onEnd);
+ sock.off("close", onEnd);
+ sock.off("error", onError);
+ return buf;
+ },
+ };
+}
+
+function withTimeout<T>(p: Promise<T>, ms: number, sock: () => net.Socket | null, what: string): Promise<T> {
+ let t: NodeJS.Timeout;
+ return Promise.race([
+ p,
+ new Promise<T>((_, reject) => {
+ t = setTimeout(() => {
+ sock()?.destroy();
+ reject(new ProxyError(`${what} timed out after ${Math.round(ms / 1000)} s`));
+ }, ms);
+ }),
+ ]).finally(() => clearTimeout(t));
+}
+
+// The TCP (or, for an https:// proxy, TLS) connection to the proxy itself.
+function connectToProxy(p: ParsedProxy): Promise<net.Socket> {
+ return new Promise((resolve, reject) => {
+ const onErr = (e: Error) => reject(e);
+ if (p.scheme === "https") {
+ const s = tls.connect({ host: p.host, port: p.port, servername: net.isIP(p.host) ? undefined : p.host }, () => {
+ s.off("error", onErr);
+ resolve(s);
+ });
+ s.once("error", onErr);
+ } else {
+ const s = net.connect({ host: p.host, port: p.port }, () => {
+ s.off("error", onErr);
+ resolve(s);
+ });
+ s.once("error", onErr);
+ }
+ });
+}
+
+const SOCKS_REPLIES: Record<number, string> = {
+ 1: "general failure",
+ 2: "connection not allowed by its rules",
+ 3: "network unreachable",
+ 4: "host unreachable",
+ 5: "connection refused by the destination",
+ 6: "TTL expired",
+ 7: "command not supported",
+ 8: "address type not supported",
+};
+
+async function socksGreeting(sock: net.Socket, r: ReturnType<typeof reader>, p: ParsedProxy): Promise<void> {
+ const creds = p.username !== "" || p.password !== "";
+ sock.write(Buffer.from(creds ? [5, 2, 0, 2] : [5, 1, 0]));
+ const [ver, method] = await r.read(2);
+ if (ver !== 5) throw new ProxyError("it does not speak SOCKS5");
+ if (method === 0xff) throw new ProxyError("it accepts none of the offered login methods");
+ if (method === 2) {
+ if (!creds) throw new ProxyError("it wants a username and password, and the exit has none");
+ const u = Buffer.from(p.username, "utf8");
+ const pw = Buffer.from(p.password, "utf8");
+ if (u.length > 255 || pw.length > 255) throw new ProxyError("the exit's username or password is too long for SOCKS5");
+ sock.write(Buffer.concat([Buffer.from([1, u.length]), u, Buffer.from([pw.length]), pw]));
+ const [, status] = await r.read(2);
+ if (status !== 0) throw new ProxyError("it refused the exit's username and password");
+ } else if (method !== 0) {
+ throw new ProxyError("it chose a login method this client does not speak");
+ }
+}
+
+async function socksConnect(
+ sock: net.Socket,
+ r: ReturnType<typeof reader>,
+ p: ParsedProxy,
+ host: string,
+ port: number,
+): Promise<void> {
+ let addr: Buffer;
+ let target = host;
+ // socks5: the name is resolved HERE; socks5h: the proxy resolves it.
+ if (p.scheme === "socks5" && net.isIP(host) === 0) target = (await dns.lookup(host)).address;
+ const v = net.isIP(target);
+ if (v === 4) addr = Buffer.from([1, ...target.split(".").map(Number)]);
+ else if (v === 6) {
+ const full = expandIpv6(target);
+ addr = Buffer.concat([Buffer.from([4]), full]);
+ } else {
+ const name = Buffer.from(target, "utf8");
+ if (name.length > 255) throw new ProxyError("the destination's name is too long for SOCKS5");
+ addr = Buffer.concat([Buffer.from([3, name.length]), name]);
+ }
+ const portBuf = Buffer.from([(port >> 8) & 0xff, port & 0xff]);
+ sock.write(Buffer.concat([Buffer.from([5, 1, 0]), addr, portBuf]));
+ const [ver, rep, , atyp] = await r.read(4);
+ if (ver !== 5) throw new ProxyError("it answered the connect in something other than SOCKS5");
+ if (rep !== 0) throw new ProxyError(`it could not reach the destination (${SOCKS_REPLIES[rep!] ?? `reply ${rep}`})`);
+ const len = atyp === 1 ? 4 : atyp === 4 ? 16 : (await r.read(1))[0]!;
+ await r.read(len + 2);
+}
+
+function expandIpv6(ip: string): Buffer {
+ const [head, tail] = ip.split("::");
+ const h = head ? head.split(":") : [];
+ const t = tail !== undefined && tail !== "" ? tail.split(":") : [];
+ const groups = [...h, ...Array(8 - h.length - t.length).fill("0"), ...t];
+ const out = Buffer.alloc(16);
+ groups.forEach((g, i) => out.writeUInt16BE(parseInt(g || "0", 16), i * 2));
+ return out;
+}
+
+function basicAuth(p: ParsedProxy): string {
+ if (p.username === "" && p.password === "") return "";
+ return `Proxy-Authorization: Basic ${Buffer.from(`${p.username}:${p.password}`).toString("base64")}\r\n`;
+}
+
+async function httpConnect(sock: net.Socket, r: ReturnType<typeof reader>, p: ParsedProxy, host: string, port: number): Promise<void> {
+ const authority = net.isIP(host) === 6 ? `[${host}]:${port}` : `${host}:${port}`;
+ sock.write(`CONNECT ${authority} HTTP/1.1\r\nHost: ${authority}\r\n${basicAuth(p)}\r\n`);
+ const head = (await r.readUntil("\r\n\r\n")).toString("latin1");
+ const status = Number(/^HTTP\/1\.[01] (\d{3})/.exec(head)?.[1] ?? 0);
+ if (status === 407) throw new ProxyError("it refused the exit's credentials (HTTP 407)");
+ if (status !== 200) throw new ProxyError(`it refused the tunnel (HTTP ${status || "?"})`);
+}
+
+// A TUNNEL through the exit's proxy to host:port, or why not.
+export async function openTunnel(
+ proxyUrl: string,
+ host: string,
+ port: number,
+ timeoutMs = PROXY_TIMEOUT_MS,
+): Promise<{ ok: true; socket: net.Socket; head: Buffer } | ProxyFailure> {
+ const p = parseProxyUrl(proxyUrl);
+ if ("error" in p) return { ok: false, reason: p.error };
+ let sock: net.Socket | null = null;
+ try {
+ return await withTimeout(
+ (async () => {
+ sock = await connectToProxy(p);
+ const r = reader(sock);
+ if (p.scheme === "socks5" || p.scheme === "socks5h") {
+ await socksGreeting(sock, r, p);
+ await socksConnect(sock, r, p, host, port);
+ } else {
+ await httpConnect(sock, r, p, host, port);
+ }
+ const head = r.release();
+ return { ok: true as const, socket: sock, head };
+ })(),
+ timeoutMs,
+ () => sock,
+ "the proxy",
+ );
+ } catch (err) {
+ (sock as net.Socket | null)?.destroy();
+ return { ok: false, reason: errText(err) };
+ }
+}
+
+// THE PREFLIGHT: the proxy answers (TCP, or TLS for https://) and, for a
+// SOCKS proxy, accepts the greeting and the exit's login. Nothing is asked of
+// any destination.
+// `connectOnly` (the startup probe): the TCP or TLS connect alone — no
+// greeting, no login.
+export async function preflightProxy(
+ proxyUrl: string,
+ timeoutMs = PROXY_TIMEOUT_MS,
+ opts: { connectOnly?: boolean } = {},
+): Promise<{ ok: true; ms: number } | ProxyFailure> {
+ const p = parseProxyUrl(proxyUrl);
+ if ("error" in p) return { ok: false, reason: p.error };
+ const t0 = Date.now();
+ let sock: net.Socket | null = null;
+ try {
+ await withTimeout(
+ (async () => {
+ sock = await connectToProxy(p);
+ if (!opts.connectOnly && (p.scheme === "socks5" || p.scheme === "socks5h")) {
+ const r = reader(sock);
+ await socksGreeting(sock, r, p);
+ r.release();
+ }
+ })(),
+ timeoutMs,
+ () => sock,
+ "the proxy",
+ );
+ return { ok: true, ms: Date.now() - t0 };
+ } catch (err) {
+ return { ok: false, reason: errText(err) };
+ } finally {
+ (sock as net.Socket | null)?.destroy();
+ }
+}
+
+// ONE GET THROUGH THE EXIT (the address-echo probe): status and the first
+// 4 KB of the body. http and https destinations; the TLS to an https
+// destination runs inside the tunnel.
+export async function getThroughProxy(
+ proxyUrl: string,
+ url: string,
+ timeoutMs = PROXY_TIMEOUT_MS,
+): Promise<{ ok: true; status: number; body: string } | ProxyFailure> {
+ let u: URL;
+ try {
+ u = new URL(url);
+ } catch {
+ return { ok: false, reason: "the echo URL does not parse" };
+ }
+ const secure = u.protocol === "https:";
+ const port = Number(u.port || (secure ? 443 : 80));
+ const host = u.hostname.replace(/^\[|\]$/g, "");
+ const t = await openTunnel(proxyUrl, host, port, timeoutMs);
+ if (!t.ok) return t;
+ let sock: net.Socket = t.socket;
+ try {
+ return await withTimeout(
+ (async () => {
+ if (secure) {
+ sock = await new Promise<net.Socket>((resolve, reject) => {
+ const s = tls.connect({ socket: t.socket, servername: net.isIP(host) ? undefined : host }, () => resolve(s));
+ s.once("error", reject);
+ });
+ } else if (t.head.length) {
+ sock.unshift(t.head);
+ }
+ const r = reader(sock);
+ sock.write(
+ `GET ${u.pathname || "/"}${u.search} HTTP/1.1\r\nHost: ${u.host}\r\nUser-Agent: archilyzer-network-probe\r\n` +
+ `Accept: text/plain, */*\r\nConnection: close\r\n\r\n`,
+ );
+ const head = (await r.readUntil("\r\n\r\n")).toString("latin1");
+ const status = Number(/^HTTP\/1\.[01] (\d{3})/.exec(head)?.[1] ?? 0);
+ const body = (await r.readAll(4096)).toString("utf8");
+ const chunked = /\r\ntransfer-encoding:\s*chunked/i.test(head);
+ return { ok: true as const, status, body: chunked ? dechunk(body) : body };
+ })(),
+ timeoutMs,
+ () => sock,
+ "the echo request",
+ );
+ } catch (err) {
+ return { ok: false, reason: errText(err) };
+ } finally {
+ sock.destroy();
+ }
+}
+
+function dechunk(s: string): string {
+ let out = "";
+ let rest = s;
+ for (;;) {
+ const m = /^([0-9a-f]+)[^\r\n]*\r\n/i.exec(rest);
+ if (!m) break;
+ const n = parseInt(m[1]!, 16);
+ if (n === 0) break;
+ out += rest.slice(m[0].length, m[0].length + n);
+ rest = rest.slice(m[0].length + n + 2);
+ }
+ return out;
+}
+
+// The public address an echo body names (the first IPv4/IPv6 literal in it),
+// or null.
+export function addressInEcho(body: string): string | null {
+ const t = body.trim();
+ if (net.isIP(t)) return t;
+ for (const m of t.matchAll(/[0-9a-fA-F:.]{3,}/g)) {
+ if (net.isIP(m[0])) return m[0];
+ const c = m[0].replace(/^[.]+|[:.]+$/g, "");
+ if (net.isIP(c)) return c;
+ }
+ return null;
+}
diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts
@@ -83,6 +83,11 @@ import {
import { APP_INSTANCE_CONFIG_FIELD_DOCS } from "./transcriptionApps";
import { DIGEST_APP_CONFIG_FIELD_DOCS } from "./digest";
import {
+ NETWORK_EXIT_FIELD_DOCS,
+ NETWORK_PLATFORM_POLICY_FIELD_DOCS,
+ NETWORK_SETTINGS_FIELD_DOCS,
+} from "./networkExits";
+import {
STORAGE_LOCATION_FIELD_DOCS,
STORAGE_SETTINGS_FIELD_DOCS,
STORAGE_VOLUME_FIELD_DOCS,
@@ -184,6 +189,15 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings,
defaults: fromObject(d.pacing),
},
],
+ network: [
+ {
+ path: "network",
+ docs: NETWORK_SETTINGS_FIELD_DOCS,
+ defaults: fromObject(d.network),
+ },
+ { path: "network.exits[]", docs: NETWORK_EXIT_FIELD_DOCS },
+ { path: "network.platforms.<platform>", docs: NETWORK_PLATFORM_POLICY_FIELD_DOCS },
+ ],
archiveStorage: [
{
path: "archiveStorage",
diff --git a/common/lib/settingsSchema.test.ts b/common/lib/settingsSchema.test.ts
@@ -43,6 +43,7 @@ import type { SourceGroup } from "./copies/settings";
import type { PrivacySettings } from "./privacySettings";
import type { VoiceSettings } from "./voiceSettings";
import type { GenerationSettings } from "./generationSettings";
+import type { NetworkSettings } from "./networkExits";
import type {
AttributionSettings,
BackfillSettings,
@@ -94,6 +95,8 @@ type PreSchemaSiteSettings = {
liveRecording: LiveRecordingSettingsBlock;
// Release 17 slice RL — the adaptive pace and the hold.
pacing: PacingSettingsBlock;
+ // Named network exits (lane network-exits).
+ network: NetworkSettings;
downloadFormat: DownloadFormatPreset;
// The source-video quality a full persist keeps.
sourceVideoQuality: SourceVideoQuality;
@@ -157,7 +160,7 @@ type PreSchemaSiteSettings = {
type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
const shapeUnchanged: Same<SiteSettings, PreSchemaSiteSettings> = true;
-test("SiteSettings keeps its 50 fields, in file order", () => {
+test("SiteSettings keeps its 51 fields, in file order", () => {
assert.equal(shapeUnchanged, true);
assert.deepEqual(Object.keys(siteSettingsSchema.shape), [
"adminTitle",
@@ -172,6 +175,7 @@ test("SiteSettings keeps its 50 fields, in file order", () => {
"livePreclip",
"liveRecording",
"pacing",
+ "network",
"downloadFormat",
"sourceVideoQuality",
"minFreeDiskGB",
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -155,6 +155,8 @@ import {
export type { Worker } from "./workers";
export type { SocialSettings, XSocialSettings, XenforoSocialSettings, InstagramSocialSettings } from "../social/xCookieSource";
import { sanitizeJobGapSeconds } from "./jobGap";
+import { sanitizeNetwork, type NetworkSettings } from "./networkExits";
+export type { NetworkSettings, NetworkExit, NetworkPlatformPolicy } from "./networkExits";
export { JOB_GAP_DEFAULT_SECONDS, JOB_GAP_MAX_SECONDS, jobGapSecondsFor } from "./jobGap";
// The `social` block (release 16 slice XL). The types and the coercion live
@@ -2043,6 +2045,9 @@ export const siteSettingsSchema = z.object({
pacing: settingsField((v): PacingSettingsBlock => sanitizePacing(v)).describe(
"How the download pace adapts to rate limits, per platform (release 17). Every yt-dlp spawn against a platform paces its requests (`--sleep-requests`) at the platform's adaptive pace, and the download lane waits sleepBetweenDownloadsSeconds plus the pace above its fixed value between units. A rate limit doubles the pace; clean units ease it back; a rate limit that outlasts the cooldown cap holds the platform to one probe at a time. The live pace, cooldowns and holds are in `.auto-queue/state.json`, shown on /operations/download. See common/jobs/platformBackoff.ts.",
),
+ network: settingsField((v): NetworkSettings => sanitizeNetwork(v)).describe(
+ "NAMED NETWORK EXITS (lane network-exits): proxies a listing may leave through, a policy per platform queue, and which exit a logged-in request (a cookie jar) is pinned to. Absent or empty = every request goes direct, exactly as before. The trial routes only the listing requests of rumble and twitch, and no cookie jar may leave direct. Written by `pnpm ops network` / `pnpm ops network-exit` and /settings → Network exits, never by `pnpm ops settings`; `pnpm ops get network` reports each exit, its rests and its counts. Proxy credentials are secrets: redacted in every answer, log and record. See common/lib/networkExits.ts and controller/networkExits.ts.",
+ ),
downloadFormat: settingsField((v): DownloadFormatPreset =>
isDownloadFormatPreset(v) ? v : "auto").describe(
"Default yt-dlp `-f` download format for every channel that doesn't set its own (ChannelConfig.downloadFormat). \"auto\" picks per-source: `original` for Odysee (whose HLS rungs are CDN-truncated), `bestaudio/worst` elsewhere. See common/ytdlp/downloadFormat.ts.",
diff --git a/common/lib/ytdlpOptionClasses.ts b/common/lib/ytdlpOptionClasses.ts
@@ -0,0 +1,379 @@
+// WHAT EACH yt-dlp OPTION MEANS FOR A NETWORK EXIT (lane network-exits,
+// review 3 nit 5), classified BY A PERSON, one entry per long name of
+// lib/ytdlpOptions.ts:
+// cookie carries a cookie jar -> the listing goes direct
+// login carries an account, a token or acts as one (--mark-watched)
+// header sets a request header or spoofs where the request comes from
+// config loads other options, code or another program (anything could be in it)
+// proxy the channel's own proxy (the listing is today's, untouched)
+// none reviewed: changes nothing about who is asking or from where
+// An option the table has and this map does not is treated as `config` at run
+// time (pinned direct), and lib/networkExits.test.ts FAILS until it is
+// classified here: regenerating the table never silently admits a new option.
+// Classified for yt-dlp 2026.10.26, 21 Nov 2026.
+
+export type YtdlpOptionClass = "cookie" | "login" | "header" | "config" | "proxy" | "none";
+
+export const YTDLP_OPTION_CLASSES: Readonly<Record<string, YtdlpOptionClass>> = {
+ "--S-force": "none",
+ "--abort-on-error": "none",
+ "--abort-on-unavailable-fragments": "none",
+ "--add-chapters": "none",
+ "--add-headers": "header",
+ "--add-metadata": "none",
+ "--age-limit": "none",
+ "--alias": "config",
+ "--all-formats": "none",
+ "--all-subs": "none",
+ "--allow-dynamic-mpd": "none",
+ "--allow-unplayable-formats": "none",
+ "--ap-list-mso": "none",
+ "--ap-mso": "login",
+ "--ap-password": "login",
+ "--ap-username": "login",
+ "--audio-format": "none",
+ "--audio-multistreams": "none",
+ "--audio-quality": "none",
+ "--autonumber-size": "none",
+ "--autonumber-start": "none",
+ "--batch-file": "config",
+ "--bidi-workaround": "none",
+ "--break-match-filters": "none",
+ "--break-on-existing": "none",
+ "--break-on-reject": "none",
+ "--break-per-input": "none",
+ "--buffer-size": "none",
+ "--cache-dir": "none",
+ "--call-home": "none",
+ "--check-all-formats": "none",
+ "--check-formats": "none",
+ "--clean-info-json": "none",
+ "--clean-infojson": "none",
+ "--client-certificate": "login",
+ "--client-certificate-key": "login",
+ "--client-certificate-password": "login",
+ "--cn-verification-proxy": "proxy",
+ "--color": "none",
+ "--compat-options": "config",
+ "--concat-playlist": "none",
+ "--concurrent-fragments": "none",
+ "--config-locations": "config",
+ "--console-title": "none",
+ "--continue": "none",
+ "--convert-sub": "none",
+ "--convert-subs": "none",
+ "--convert-subtitles": "none",
+ "--convert-thumbnails": "none",
+ "--cookies": "cookie",
+ "--cookies-from-browser": "cookie",
+ "--date": "none",
+ "--dateafter": "none",
+ "--datebefore": "none",
+ "--default-search": "none",
+ "--download-archive": "none",
+ "--download-sections": "none",
+ "--downloader": "config",
+ "--downloader-args": "config",
+ "--dump-json": "none",
+ "--dump-pages": "none",
+ "--dump-single-json": "none",
+ "--dump-user-agent": "none",
+ "--embed-chapters": "none",
+ "--embed-info-json": "none",
+ "--embed-metadata": "none",
+ "--embed-subs": "none",
+ "--embed-thumbnail": "none",
+ "--enable-file-urls": "none",
+ "--encoding": "none",
+ "--exec": "config",
+ "--exec-before-download": "config",
+ "--external-downloader": "config",
+ "--external-downloader-args": "config",
+ "--extract-audio": "none",
+ "--extractor-args": "login",
+ "--extractor-descriptions": "none",
+ "--extractor-retries": "none",
+ "--ffmpeg-location": "config",
+ "--file-access-retries": "none",
+ "--fixup": "none",
+ "--flat-playlist": "none",
+ "--force-download-archive": "none",
+ "--force-generic-extractor": "none",
+ "--force-ipv4": "none",
+ "--force-ipv6": "none",
+ "--force-keyframes-at-cuts": "none",
+ "--force-overwrites": "none",
+ "--force-write-archive": "none",
+ "--force-write-download-archive": "none",
+ "--format": "none",
+ "--format-sort": "none",
+ "--format-sort-force": "none",
+ "--format-sort-reset": "none",
+ "--fragment-retries": "none",
+ "--geo-bypass": "none",
+ "--geo-bypass-country": "header",
+ "--geo-bypass-ip-block": "header",
+ "--geo-verification-proxy": "proxy",
+ "--get-comments": "none",
+ "--get-description": "none",
+ "--get-duration": "none",
+ "--get-filename": "none",
+ "--get-format": "none",
+ "--get-id": "none",
+ "--get-thumbnail": "none",
+ "--get-title": "none",
+ "--get-url": "none",
+ "--help": "none",
+ "--hls-prefer-ffmpeg": "none",
+ "--hls-prefer-native": "none",
+ "--hls-split-discontinuity": "none",
+ "--hls-use-mpegts": "none",
+ "--http-chunk-size": "none",
+ "--id": "none",
+ "--ies": "config",
+ "--ignore-config": "none",
+ "--ignore-dynamic-mpd": "none",
+ "--ignore-errors": "none",
+ "--ignore-no-formats-error": "none",
+ "--impersonate": "none",
+ "--include-ads": "none",
+ "--js-runtimes": "config",
+ "--keep-fragments": "none",
+ "--keep-video": "none",
+ "--lazy-playlist": "none",
+ "--legacy-server-connect": "none",
+ "--limit-rate": "none",
+ "--list-extractors": "none",
+ "--list-formats": "none",
+ "--list-formats-as-table": "none",
+ "--list-formats-old": "none",
+ "--list-impersonate-targets": "none",
+ "--list-subs": "none",
+ "--list-thumbnails": "none",
+ "--live-from-start": "none",
+ "--load-info-json": "config",
+ "--load-pages": "config",
+ "--mark-watched": "login",
+ "--match-filters": "none",
+ "--match-title": "none",
+ "--max-downloads": "none",
+ "--max-filesize": "none",
+ "--max-sleep-interval": "none",
+ "--max-views": "none",
+ "--merge-output-format": "none",
+ "--metadata-from-title": "none",
+ "--min-filesize": "none",
+ "--min-sleep-interval": "none",
+ "--min-views": "none",
+ "--mtime": "none",
+ "--netrc": "login",
+ "--netrc-cmd": "login",
+ "--netrc-location": "login",
+ "--newline": "none",
+ "--no-abort-on-error": "none",
+ "--no-abort-on-unavailable-fragments": "none",
+ "--no-add-chapters": "none",
+ "--no-add-metadata": "none",
+ "--no-allow-dynamic-mpd": "none",
+ "--no-allow-unplayable-formats": "none",
+ "--no-audio-multistreams": "none",
+ "--no-batch-file": "none",
+ "--no-break-match-filters": "none",
+ "--no-break-on-existing": "none",
+ "--no-break-per-input": "none",
+ "--no-cache-dir": "none",
+ "--no-call-home": "none",
+ "--no-check-certificates": "none",
+ "--no-check-formats": "none",
+ "--no-clean-info-json": "none",
+ "--no-clean-infojson": "none",
+ "--no-colors": "none",
+ "--no-colours": "none",
+ "--no-config": "none",
+ "--no-config-locations": "none",
+ "--no-continue": "none",
+ "--no-cookies": "none",
+ "--no-cookies-from-browser": "none",
+ "--no-download": "none",
+ "--no-download-archive": "none",
+ "--no-embed-chapters": "none",
+ "--no-embed-info-json": "none",
+ "--no-embed-metadata": "none",
+ "--no-embed-subs": "none",
+ "--no-embed-thumbnail": "none",
+ "--no-exec": "none",
+ "--no-exec-before-download": "none",
+ "--no-flat-playlist": "none",
+ "--no-force-keyframes-at-cuts": "none",
+ "--no-force-overwrites": "none",
+ "--no-format-sort-force": "none",
+ "--no-geo-bypass": "none",
+ "--no-get-comments": "none",
+ "--no-hls-split-discontinuity": "none",
+ "--no-hls-use-mpegts": "none",
+ "--no-ignore-dynamic-mpd": "none",
+ "--no-ignore-errors": "none",
+ "--no-ignore-no-formats-error": "none",
+ "--no-include-ads": "none",
+ "--no-js-runtimes": "none",
+ "--no-keep-fragments": "none",
+ "--no-keep-video": "none",
+ "--no-lazy-playlist": "none",
+ "--no-list-formats-as-table": "none",
+ "--no-live-from-start": "none",
+ "--no-mark-watched": "none",
+ "--no-match-filters": "none",
+ "--no-mtime": "none",
+ "--no-overwrites": "none",
+ "--no-part": "none",
+ "--no-playlist": "none",
+ "--no-playlist-reverse": "none",
+ "--no-plugin-dirs": "none",
+ "--no-post-overwrites": "none",
+ "--no-prefer-avconv": "none",
+ "--no-prefer-ffmpeg": "none",
+ "--no-prefer-free-formats": "none",
+ "--no-progress": "none",
+ "--no-quiet": "none",
+ "--no-remote-components": "none",
+ "--no-remove-chapters": "none",
+ "--no-resize-buffer": "none",
+ "--no-restrict-filenames": "none",
+ "--no-simulate": "none",
+ "--no-skip-unavailable-fragments": "none",
+ "--no-split-chapters": "none",
+ "--no-split-tracks": "none",
+ "--no-sponskrub": "none",
+ "--no-sponskrub-cut": "none",
+ "--no-sponskrub-force": "none",
+ "--no-sponsorblock": "none",
+ "--no-update": "none",
+ "--no-video-multistreams": "none",
+ "--no-wait-for-video": "none",
+ "--no-warnings": "none",
+ "--no-windows-filenames": "none",
+ "--no-write-annotations": "none",
+ "--no-write-auto-subs": "none",
+ "--no-write-automatic-subs": "none",
+ "--no-write-comments": "none",
+ "--no-write-description": "none",
+ "--no-write-info-json": "none",
+ "--no-write-playlist-metafiles": "none",
+ "--no-write-srt": "none",
+ "--no-write-subs": "none",
+ "--no-write-thumbnail": "none",
+ "--no-youtube-include-dash-manifest": "none",
+ "--no-youtube-include-hls-manifest": "none",
+ "--no-youtube-skip-dash-manifest": "none",
+ "--no-youtube-skip-hls-manifest": "none",
+ "--output": "none",
+ "--output-na-placeholder": "none",
+ "--parse-metadata": "none",
+ "--part": "none",
+ "--password": "login",
+ "--paths": "none",
+ "--playlist-end": "none",
+ "--playlist-items": "none",
+ "--playlist-random": "none",
+ "--playlist-reverse": "none",
+ "--playlist-start": "none",
+ "--plugin-dirs": "config",
+ "--post-overwrites": "none",
+ "--postprocessor-args": "config",
+ "--ppa": "config",
+ "--prefer-avconv": "none",
+ "--prefer-ffmpeg": "none",
+ "--prefer-free-formats": "none",
+ "--prefer-insecure": "none",
+ "--prefer-unsecure": "none",
+ "--preset-alias": "none",
+ "--print": "none",
+ "--print-json": "none",
+ "--print-to-file": "none",
+ "--print-traffic": "config",
+ "--progress": "none",
+ "--progress-delta": "none",
+ "--progress-template": "none",
+ "--proxy": "proxy",
+ "--quiet": "none",
+ "--rate-limit": "none",
+ "--recode-video": "none",
+ "--referer": "none",
+ "--reject-title": "none",
+ "--remote-components": "config",
+ "--remove-chapters": "none",
+ "--remux-video": "none",
+ "--replace-in-metadata": "none",
+ "--resize-buffer": "none",
+ "--restrict-filenames": "none",
+ "--retries": "none",
+ "--retry-sleep": "none",
+ "--rm-cache-dir": "none",
+ "--simulate": "none",
+ "--skip-download": "none",
+ "--skip-playlist-after-errors": "none",
+ "--skip-unavailable-fragments": "none",
+ "--sleep-interval": "none",
+ "--sleep-requests": "none",
+ "--sleep-subtitles": "none",
+ "--socket-timeout": "none",
+ "--source-address": "none",
+ "--split-chapters": "none",
+ "--split-tracks": "none",
+ "--sponskrub": "none",
+ "--sponskrub-args": "none",
+ "--sponskrub-cut": "none",
+ "--sponskrub-force": "none",
+ "--sponskrub-location": "config",
+ "--sponsorblock-api": "none",
+ "--sponsorblock-chapter-title": "none",
+ "--sponsorblock-mark": "none",
+ "--sponsorblock-remove": "none",
+ "--srt-langs": "none",
+ "--sub-format": "none",
+ "--sub-langs": "none",
+ "--test": "none",
+ "--throttled-rate": "none",
+ "--trim-file-names": "none",
+ "--trim-filenames": "none",
+ "--twofactor": "login",
+ "--update": "config",
+ "--update-to": "config",
+ "--use-extractors": "config",
+ "--use-postprocessor": "config",
+ "--user-agent": "none",
+ "--username": "login",
+ "--verbose": "none",
+ "--version": "none",
+ "--video-multistreams": "none",
+ "--video-password": "login",
+ "--wait-for-video": "none",
+ "--windows-filenames": "none",
+ "--write-all-thumbnails": "none",
+ "--write-annotations": "none",
+ "--write-auto-subs": "none",
+ "--write-automatic-subs": "none",
+ "--write-comments": "none",
+ "--write-description": "none",
+ "--write-desktop-link": "none",
+ "--write-info-json": "none",
+ "--write-link": "none",
+ "--write-pages": "none",
+ "--write-playlist-metafiles": "none",
+ "--write-srt": "none",
+ "--write-subs": "none",
+ "--write-thumbnail": "none",
+ "--write-url-link": "none",
+ "--write-webloc-link": "none",
+ "--xattr": "none",
+ "--xattr-set-filesize": "none",
+ "--xattrs": "none",
+ "--xff": "header",
+ "--yes-overwrites": "none",
+ "--yes-playlist": "none",
+ "--youtube-include-dash-manifest": "none",
+ "--youtube-include-hls-manifest": "none",
+ "--youtube-print-sig-code": "none",
+ "--youtube-skip-dash-manifest": "none",
+ "--youtube-skip-hls-manifest": "none",
+};
diff --git a/common/lib/ytdlpOptions.ts b/common/lib/ytdlpOptions.ts
@@ -0,0 +1,383 @@
+// THE INSTALLED yt-dlp'S OPTION TABLE (yt-dlp 2026.10.26), every option its
+// parser accepts — the ones `--help` hides included (`--user-agent`,
+// `--referer`, …): [short, long, takes a value]. lib/networkExits.ts resolves
+// a listing's argv against it with yt-dlp's own rule — an exact long name,
+// else the one long name the argument is a prefix of; short options
+// clustered, a value-taking one swallowing the rest of its cluster — so an
+// abbreviation (`--pas`, `--cookies-from-b`, `--prox`) or a glued value
+// (`-f22`) is read as yt-dlp reads it.
+//
+// GENERATED from yt-dlp's own parser (`yt_dlp.options.create_parser()`) by
+// YTDLP_OPTIONS_DUMP below, run with the interpreter of the yt-dlp on PATH.
+// lib/networkExits.test.ts runs it again and FAILS when the installed yt-dlp
+// adds, renames or re-arities an option: regenerate this table then.
+//
+// Pure data; client-safe.
+
+export const YTDLP_OPTIONS_VERSION = "2026.10.26";
+
+export const YTDLP_OPTIONS_DUMP = "import json, yt_dlp\nfrom yt_dlp.options import create_parser\np = create_parser()\nrows = []\nfor o in p._get_all_options():\n for i, l in enumerate(o._long_opts):\n rows.append([o._short_opts[0][1] if (o._short_opts and i == 0) else None, l, bool(o.takes_value())])\n for s in o._short_opts[1:]:\n rows.append([s[1], o._long_opts[0], bool(o.takes_value())])\nprint(json.dumps({\"version\": yt_dlp.version.__version__, \"rows\": rows}))\n";
+
+export const YTDLP_OPTIONS: ReadonlyArray<readonly [string | null, string, boolean]> = [
+ [null, "--xattr-set-filesize", false],
+ [null, "--dump-user-agent", false],
+ [null, "--youtube-include-dash-manifest", false],
+ [null, "--no-youtube-skip-dash-manifest", false],
+ [null, "--youtube-skip-dash-manifest", false],
+ [null, "--no-youtube-include-dash-manifest", false],
+ [null, "--youtube-include-hls-manifest", false],
+ [null, "--no-youtube-skip-hls-manifest", false],
+ [null, "--youtube-skip-hls-manifest", false],
+ [null, "--no-youtube-include-hls-manifest", false],
+ [null, "--youtube-print-sig-code", false],
+ [null, "--sponskrub", false],
+ [null, "--no-sponskrub", false],
+ [null, "--sponskrub-cut", false],
+ [null, "--no-sponskrub-cut", false],
+ [null, "--sponskrub-force", false],
+ [null, "--no-sponskrub-force", false],
+ [null, "--prefer-avconv", false],
+ [null, "--no-prefer-ffmpeg", false],
+ [null, "--prefer-ffmpeg", false],
+ [null, "--no-prefer-avconv", false],
+ [null, "--call-home", false],
+ [null, "--no-call-home", false],
+ [null, "--include-ads", false],
+ [null, "--no-include-ads", false],
+ [null, "--write-annotations", false],
+ [null, "--no-write-annotations", false],
+ [null, "--sponskrub-location", true],
+ [null, "--sponskrub-args", true],
+ [null, "--cn-verification-proxy", true],
+ ["h", "--help", false],
+ [null, "--version", false],
+ ["U", "--update", false],
+ [null, "--no-update", false],
+ [null, "--update-to", true],
+ ["i", "--ignore-errors", false],
+ [null, "--no-abort-on-error", false],
+ [null, "--abort-on-error", false],
+ [null, "--no-ignore-errors", false],
+ [null, "--list-extractors", false],
+ [null, "--extractor-descriptions", false],
+ [null, "--use-extractors", true],
+ [null, "--ies", true],
+ [null, "--force-generic-extractor", false],
+ [null, "--default-search", true],
+ [null, "--ignore-config", false],
+ [null, "--no-config", false],
+ [null, "--no-config-locations", false],
+ [null, "--config-locations", true],
+ [null, "--plugin-dirs", true],
+ [null, "--no-plugin-dirs", false],
+ [null, "--js-runtimes", true],
+ [null, "--no-js-runtimes", false],
+ [null, "--remote-components", true],
+ [null, "--no-remote-components", false],
+ [null, "--flat-playlist", false],
+ [null, "--no-flat-playlist", false],
+ [null, "--live-from-start", false],
+ [null, "--no-live-from-start", false],
+ [null, "--wait-for-video", true],
+ [null, "--no-wait-for-video", false],
+ [null, "--mark-watched", false],
+ [null, "--no-mark-watched", false],
+ [null, "--no-colors", false],
+ [null, "--no-colours", false],
+ [null, "--color", true],
+ [null, "--compat-options", true],
+ [null, "--alias", true],
+ ["t", "--preset-alias", true],
+ [null, "--proxy", true],
+ [null, "--socket-timeout", true],
+ [null, "--source-address", true],
+ [null, "--impersonate", true],
+ [null, "--list-impersonate-targets", false],
+ ["4", "--force-ipv4", false],
+ ["6", "--force-ipv6", false],
+ [null, "--enable-file-urls", false],
+ [null, "--geo-verification-proxy", true],
+ [null, "--xff", true],
+ [null, "--geo-bypass", false],
+ [null, "--no-geo-bypass", false],
+ [null, "--geo-bypass-country", true],
+ [null, "--geo-bypass-ip-block", true],
+ [null, "--playlist-start", true],
+ [null, "--playlist-end", true],
+ ["I", "--playlist-items", true],
+ [null, "--match-title", true],
+ [null, "--reject-title", true],
+ [null, "--min-filesize", true],
+ [null, "--max-filesize", true],
+ [null, "--date", true],
+ [null, "--datebefore", true],
+ [null, "--dateafter", true],
+ [null, "--min-views", true],
+ [null, "--max-views", true],
+ [null, "--match-filters", true],
+ [null, "--no-match-filters", false],
+ [null, "--break-match-filters", true],
+ [null, "--no-break-match-filters", false],
+ [null, "--no-playlist", false],
+ [null, "--yes-playlist", false],
+ [null, "--age-limit", true],
+ [null, "--download-archive", true],
+ [null, "--no-download-archive", false],
+ [null, "--max-downloads", true],
+ [null, "--break-on-existing", false],
+ [null, "--no-break-on-existing", false],
+ [null, "--break-on-reject", false],
+ [null, "--break-per-input", false],
+ [null, "--no-break-per-input", false],
+ [null, "--skip-playlist-after-errors", true],
+ ["N", "--concurrent-fragments", true],
+ ["r", "--limit-rate", true],
+ [null, "--rate-limit", true],
+ [null, "--throttled-rate", true],
+ ["R", "--retries", true],
+ [null, "--file-access-retries", true],
+ [null, "--fragment-retries", true],
+ [null, "--retry-sleep", true],
+ [null, "--skip-unavailable-fragments", false],
+ [null, "--no-abort-on-unavailable-fragments", false],
+ [null, "--abort-on-unavailable-fragments", false],
+ [null, "--no-skip-unavailable-fragments", false],
+ [null, "--keep-fragments", false],
+ [null, "--no-keep-fragments", false],
+ [null, "--buffer-size", true],
+ [null, "--resize-buffer", false],
+ [null, "--no-resize-buffer", false],
+ [null, "--http-chunk-size", true],
+ [null, "--test", false],
+ [null, "--playlist-reverse", false],
+ [null, "--no-playlist-reverse", false],
+ [null, "--playlist-random", false],
+ [null, "--lazy-playlist", false],
+ [null, "--no-lazy-playlist", false],
+ [null, "--hls-prefer-native", false],
+ [null, "--hls-prefer-ffmpeg", false],
+ [null, "--hls-use-mpegts", false],
+ [null, "--no-hls-use-mpegts", false],
+ [null, "--download-sections", true],
+ [null, "--downloader", true],
+ [null, "--external-downloader", true],
+ [null, "--downloader-args", true],
+ [null, "--external-downloader-args", true],
+ ["a", "--batch-file", true],
+ [null, "--no-batch-file", false],
+ [null, "--id", false],
+ ["P", "--paths", true],
+ ["o", "--output", true],
+ [null, "--output-na-placeholder", true],
+ [null, "--autonumber-size", true],
+ [null, "--autonumber-start", true],
+ [null, "--restrict-filenames", false],
+ [null, "--no-restrict-filenames", false],
+ [null, "--windows-filenames", false],
+ [null, "--no-windows-filenames", false],
+ [null, "--trim-filenames", true],
+ [null, "--trim-file-names", true],
+ ["w", "--no-overwrites", false],
+ [null, "--force-overwrites", false],
+ [null, "--yes-overwrites", false],
+ [null, "--no-force-overwrites", false],
+ ["c", "--continue", false],
+ [null, "--no-continue", false],
+ [null, "--part", false],
+ [null, "--no-part", false],
+ [null, "--mtime", false],
+ [null, "--no-mtime", false],
+ [null, "--write-description", false],
+ [null, "--no-write-description", false],
+ [null, "--write-info-json", false],
+ [null, "--no-write-info-json", false],
+ [null, "--write-playlist-metafiles", false],
+ [null, "--no-write-playlist-metafiles", false],
+ [null, "--clean-info-json", false],
+ [null, "--clean-infojson", false],
+ [null, "--no-clean-info-json", false],
+ [null, "--no-clean-infojson", false],
+ [null, "--write-comments", false],
+ [null, "--get-comments", false],
+ [null, "--no-write-comments", false],
+ [null, "--no-get-comments", false],
+ [null, "--load-info-json", true],
+ [null, "--cookies", true],
+ [null, "--no-cookies", false],
+ [null, "--cookies-from-browser", true],
+ [null, "--no-cookies-from-browser", false],
+ [null, "--cache-dir", true],
+ [null, "--no-cache-dir", false],
+ [null, "--rm-cache-dir", false],
+ [null, "--write-thumbnail", false],
+ [null, "--no-write-thumbnail", false],
+ [null, "--write-all-thumbnails", false],
+ [null, "--list-thumbnails", false],
+ [null, "--write-link", false],
+ [null, "--write-url-link", false],
+ [null, "--write-webloc-link", false],
+ [null, "--write-desktop-link", false],
+ ["q", "--quiet", false],
+ [null, "--no-quiet", false],
+ [null, "--no-warnings", false],
+ ["s", "--simulate", false],
+ [null, "--no-simulate", false],
+ [null, "--ignore-no-formats-error", false],
+ [null, "--no-ignore-no-formats-error", false],
+ [null, "--skip-download", false],
+ [null, "--no-download", false],
+ ["O", "--print", true],
+ [null, "--print-to-file", true],
+ ["g", "--get-url", false],
+ ["e", "--get-title", false],
+ [null, "--get-id", false],
+ [null, "--get-thumbnail", false],
+ [null, "--get-description", false],
+ [null, "--get-duration", false],
+ [null, "--get-filename", false],
+ [null, "--get-format", false],
+ ["j", "--dump-json", false],
+ ["J", "--dump-single-json", false],
+ [null, "--print-json", false],
+ [null, "--force-write-archive", false],
+ [null, "--force-write-download-archive", false],
+ [null, "--force-download-archive", false],
+ [null, "--newline", false],
+ [null, "--no-progress", false],
+ [null, "--progress", false],
+ [null, "--console-title", false],
+ [null, "--progress-template", true],
+ [null, "--progress-delta", true],
+ ["v", "--verbose", false],
+ [null, "--dump-pages", false],
+ [null, "--write-pages", false],
+ [null, "--load-pages", false],
+ [null, "--print-traffic", false],
+ [null, "--encoding", true],
+ [null, "--legacy-server-connect", false],
+ [null, "--no-check-certificates", false],
+ [null, "--prefer-insecure", false],
+ [null, "--prefer-unsecure", false],
+ [null, "--user-agent", true],
+ [null, "--referer", true],
+ [null, "--add-headers", true],
+ [null, "--bidi-workaround", false],
+ [null, "--sleep-requests", true],
+ [null, "--sleep-interval", true],
+ [null, "--min-sleep-interval", true],
+ [null, "--max-sleep-interval", true],
+ [null, "--sleep-subtitles", true],
+ ["f", "--format", true],
+ ["S", "--format-sort", true],
+ [null, "--format-sort-reset", false],
+ [null, "--format-sort-force", false],
+ [null, "--S-force", false],
+ [null, "--no-format-sort-force", false],
+ [null, "--video-multistreams", false],
+ [null, "--no-video-multistreams", false],
+ [null, "--audio-multistreams", false],
+ [null, "--no-audio-multistreams", false],
+ [null, "--all-formats", false],
+ [null, "--prefer-free-formats", false],
+ [null, "--no-prefer-free-formats", false],
+ [null, "--check-formats", false],
+ [null, "--check-all-formats", false],
+ [null, "--no-check-formats", false],
+ ["F", "--list-formats", false],
+ [null, "--list-formats-as-table", false],
+ [null, "--list-formats-old", false],
+ [null, "--no-list-formats-as-table", false],
+ [null, "--merge-output-format", true],
+ [null, "--allow-unplayable-formats", false],
+ [null, "--no-allow-unplayable-formats", false],
+ [null, "--write-subs", false],
+ [null, "--write-srt", false],
+ [null, "--no-write-subs", false],
+ [null, "--no-write-srt", false],
+ [null, "--write-auto-subs", false],
+ [null, "--write-automatic-subs", false],
+ [null, "--no-write-auto-subs", false],
+ [null, "--no-write-automatic-subs", false],
+ [null, "--all-subs", false],
+ [null, "--list-subs", false],
+ [null, "--sub-format", true],
+ [null, "--sub-langs", true],
+ [null, "--srt-langs", true],
+ ["u", "--username", true],
+ ["p", "--password", true],
+ ["2", "--twofactor", true],
+ ["n", "--netrc", false],
+ [null, "--netrc-location", true],
+ [null, "--netrc-cmd", true],
+ [null, "--video-password", true],
+ [null, "--ap-mso", true],
+ [null, "--ap-username", true],
+ [null, "--ap-password", true],
+ [null, "--ap-list-mso", false],
+ [null, "--client-certificate", true],
+ [null, "--client-certificate-key", true],
+ [null, "--client-certificate-password", true],
+ ["x", "--extract-audio", false],
+ [null, "--audio-format", true],
+ [null, "--audio-quality", true],
+ [null, "--remux-video", true],
+ [null, "--recode-video", true],
+ [null, "--postprocessor-args", true],
+ [null, "--ppa", true],
+ ["k", "--keep-video", false],
+ [null, "--no-keep-video", false],
+ [null, "--post-overwrites", false],
+ [null, "--no-post-overwrites", false],
+ [null, "--embed-subs", false],
+ [null, "--no-embed-subs", false],
+ [null, "--embed-thumbnail", false],
+ [null, "--no-embed-thumbnail", false],
+ [null, "--embed-metadata", false],
+ [null, "--add-metadata", false],
+ [null, "--no-embed-metadata", false],
+ [null, "--no-add-metadata", false],
+ [null, "--embed-chapters", false],
+ [null, "--add-chapters", false],
+ [null, "--no-embed-chapters", false],
+ [null, "--no-add-chapters", false],
+ [null, "--embed-info-json", false],
+ [null, "--no-embed-info-json", false],
+ [null, "--metadata-from-title", true],
+ [null, "--parse-metadata", true],
+ [null, "--replace-in-metadata", true],
+ [null, "--xattrs", false],
+ [null, "--xattr", false],
+ [null, "--concat-playlist", true],
+ [null, "--fixup", true],
+ [null, "--ffmpeg-location", true],
+ [null, "--exec", true],
+ [null, "--no-exec", false],
+ [null, "--exec-before-download", true],
+ [null, "--no-exec-before-download", false],
+ [null, "--convert-subs", true],
+ [null, "--convert-sub", true],
+ [null, "--convert-subtitles", true],
+ [null, "--convert-thumbnails", true],
+ [null, "--split-chapters", false],
+ [null, "--split-tracks", false],
+ [null, "--no-split-chapters", false],
+ [null, "--no-split-tracks", false],
+ [null, "--remove-chapters", true],
+ [null, "--no-remove-chapters", false],
+ [null, "--force-keyframes-at-cuts", false],
+ [null, "--no-force-keyframes-at-cuts", false],
+ [null, "--use-postprocessor", true],
+ [null, "--sponsorblock-mark", true],
+ [null, "--sponsorblock-remove", true],
+ [null, "--sponsorblock-chapter-title", true],
+ [null, "--no-sponsorblock", false],
+ [null, "--sponsorblock-api", true],
+ [null, "--extractor-retries", true],
+ [null, "--allow-dynamic-mpd", false],
+ [null, "--no-ignore-dynamic-mpd", false],
+ [null, "--ignore-dynamic-mpd", false],
+ [null, "--no-allow-dynamic-mpd", false],
+ [null, "--hls-split-discontinuity", false],
+ [null, "--no-hls-split-discontinuity", false],
+ [null, "--extractor-args", true],
+];
diff --git a/common/package.json b/common/package.json
@@ -59,6 +59,7 @@
"./lib/montage/speakerCheck.mjs": "./lib/montage/speakerCheck.mjs",
"./lib/ports.mjs": "./lib/ports.mjs",
"./lib/noNetwork.mjs": "./lib/noNetwork.mjs",
+ "./lib/childEnvGuard.mjs": "./lib/childEnvGuard.mjs",
"./lib/renderPriority.mjs": "./lib/renderPriority.mjs",
"./lib/heavyQueue.mjs": "./lib/heavyQueue.mjs",
"./lib/report/drafted.mjs": "./lib/report/drafted.mjs",
diff --git a/common/publish/reportExports.ts b/common/publish/reportExports.ts
@@ -115,6 +115,8 @@ import {
revisionExports,
} from "./reportHistory";
import "../lib/childKillGuard";
+// What every child inherits (lib/childEnvGuard.mjs; review 2 of lane network-exits).
+import "../lib/childEnvGuard.mjs";
// A still or a screenshot in report.html: at most this wide, recompressed.
export const EXPORT_IMAGE_MAX_WIDTH = 1200;
diff --git a/common/social/forumSession.ts b/common/social/forumSession.ts
@@ -46,6 +46,8 @@ import {
} from "./xBrowser";
import { classifyForumPage, type ForumBlock } from "./xenforoParse";
import { launchHeadedContext, type HeadedDisplayLaunchDeps } from "./headedDisplay";
+// What every child inherits (lib/childEnvGuard.mjs; review 2 of lane network-exits).
+import "../lib/childEnvGuard.mjs";
// A host as a directory name: lowercased, nothing but [a-z0-9.-].
export function forumHostKey(host: string): string {
diff --git a/common/social/instagramGalleryDlFetcher.ts b/common/social/instagramGalleryDlFetcher.ts
@@ -82,6 +82,8 @@ import {
parseInstagramRequestLine,
type InstagramRequestLine,
} from "./instagramSignals";
+// What every child inherits (lib/childEnvGuard.mjs; review 2 of lane network-exits).
+import "../lib/childEnvGuard.mjs";
export const INSTAGRAM_FETCHER_ID = "instagram-gallery-dl";
diff --git a/common/testing/fakeProxy.ts b/common/testing/fakeProxy.ts
@@ -0,0 +1,218 @@
+// IN-PROCESS FAKE PROXIES for the network-exit tests: a SOCKS5 server (with
+// an optional username/password) and an HTTP CONNECT proxy, both on loopback,
+// that tunnel only to the loopback servers a test names — and an echo server
+// and a plain target server that count every connection they get. Nothing
+// here reaches beyond 127.0.0.1.
+
+import net from "node:net";
+import http from "node:http";
+
+export type Routed = { host: string; port: number };
+export type ConnectSeen = { atyp: "ipv4" | "domain" | "ipv6" | "http"; host: string; port: number };
+
+function listen(server: net.Server): Promise<number> {
+ return new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve((server.address() as net.AddressInfo).port)));
+}
+
+function closeServer(server: net.Server, sockets: Set<net.Socket>): Promise<void> {
+ for (const s of sockets) s.destroy();
+ return new Promise((resolve) => server.close(() => resolve()));
+}
+
+function track(server: net.Server): Set<net.Socket> {
+ const sockets = new Set<net.Socket>();
+ server.on("connection", (s) => {
+ sockets.add(s);
+ s.on("close", () => sockets.delete(s));
+ });
+ return sockets;
+}
+
+export async function startFakeSocks5(opts: {
+ username?: string;
+ password?: string;
+ // Where a CONNECT to host:port really goes; null refuses it (reply 2).
+ route: (host: string, port: number) => Routed | null;
+}): Promise<{
+ port: number;
+ connects: ConnectSeen[];
+ greetings: number;
+ authFailures: number;
+ // TCP connections accepted, greeting or not (a connect-only probe).
+ connections: number;
+ close: () => Promise<void>;
+}> {
+ const state = { connects: [] as ConnectSeen[], greetings: 0, authFailures: 0, connections: 0 };
+ const server = net.createServer((sock) => {
+ state.connections++;
+ let buf = Buffer.alloc(0);
+ let stage: "greet" | "auth" | "connect" | "piped" = "greet";
+ sock.on("error", () => {});
+ sock.on("data", (c) => {
+ if (stage === "piped") return;
+ buf = Buffer.concat([buf, c]);
+ for (;;) {
+ if (stage === "greet") {
+ if (buf.length < 2 || buf.length < 2 + buf[1]!) return;
+ const methods = [...buf.subarray(2, 2 + buf[1]!)];
+ buf = buf.subarray(2 + buf[1]!);
+ state.greetings++;
+ const wantAuth = opts.username !== undefined;
+ if (wantAuth && !methods.includes(2)) return void sock.end(Buffer.from([5, 0xff]));
+ sock.write(Buffer.from([5, wantAuth ? 2 : 0]));
+ stage = wantAuth ? "auth" : "connect";
+ continue;
+ }
+ if (stage === "auth") {
+ if (buf.length < 2) return;
+ const ul = buf[1]!;
+ if (buf.length < 3 + ul) return;
+ const pl = buf[2 + ul]!;
+ if (buf.length < 3 + ul + pl) return;
+ const u = buf.subarray(2, 2 + ul).toString();
+ const p = buf.subarray(3 + ul, 3 + ul + pl).toString();
+ buf = buf.subarray(3 + ul + pl);
+ if (u !== opts.username || p !== opts.password) {
+ state.authFailures++;
+ return void sock.end(Buffer.from([1, 1]));
+ }
+ sock.write(Buffer.from([1, 0]));
+ stage = "connect";
+ continue;
+ }
+ if (stage === "connect") {
+ if (buf.length < 5) return;
+ const atyp = buf[3]!;
+ let host: string;
+ let off: number;
+ if (atyp === 1) {
+ if (buf.length < 10) return;
+ host = [...buf.subarray(4, 8)].join(".");
+ off = 8;
+ } else if (atyp === 3) {
+ const n = buf[4]!;
+ if (buf.length < 5 + n + 2) return;
+ host = buf.subarray(5, 5 + n).toString();
+ off = 5 + n;
+ } else {
+ if (buf.length < 22) return;
+ const g: string[] = [];
+ for (let i = 0; i < 8; i++) g.push(buf.readUInt16BE(4 + i * 2).toString(16));
+ host = g.join(":").replace(/^(0:)+/, "::").replace(/^::(0:)*/, "::");
+ if (host === "::1" || /^(0:){7}1$/.test(g.join(":"))) host = "::1";
+ off = 20;
+ }
+ const port = buf.readUInt16BE(off);
+ buf = buf.subarray(off + 2);
+ state.connects.push({ atyp: atyp === 1 ? "ipv4" : atyp === 3 ? "domain" : "ipv6", host, port });
+ const to = opts.route(host, port);
+ if (!to) return void sock.end(Buffer.from([5, 2, 0, 1, 0, 0, 0, 0, 0, 0]));
+ const up = net.connect(to.port, to.host, () => {
+ sock.write(Buffer.from([5, 0, 0, 1, 127, 0, 0, 1, 0, 0]));
+ stage = "piped";
+ if (buf.length) up.write(buf);
+ sock.pipe(up).pipe(sock);
+ });
+ up.on("error", () => sock.destroy());
+ return;
+ }
+ return;
+ }
+ });
+ });
+ const sockets = track(server);
+ const port = await listen(server);
+ return {
+ port,
+ get connects() {
+ return state.connects;
+ },
+ get greetings() {
+ return state.greetings;
+ },
+ get authFailures() {
+ return state.authFailures;
+ },
+ get connections() {
+ return state.connections;
+ },
+ close: () => closeServer(server, sockets),
+ };
+}
+
+export async function startFakeHttpProxy(opts: {
+ // The expected `Proxy-Authorization: Basic …` value's user:pass; absent = none needed.
+ auth?: string;
+ route: (host: string, port: number) => Routed | null;
+}): Promise<{ port: number; connects: ConnectSeen[]; close: () => Promise<void> }> {
+ const connects: ConnectSeen[] = [];
+ const server = net.createServer((sock) => {
+ let buf = Buffer.alloc(0);
+ sock.on("error", () => {});
+ const onData = (c: Buffer) => {
+ buf = Buffer.concat([buf, c]);
+ const i = buf.indexOf("\r\n\r\n");
+ if (i < 0) return;
+ sock.off("data", onData);
+ const head = buf.subarray(0, i).toString("latin1");
+ const rest = buf.subarray(i + 4);
+ const m = /^CONNECT ([^\s:]+|\[[^\]]+\]):(\d+) HTTP/.exec(head);
+ if (!m) return void sock.end("HTTP/1.1 400 Bad Request\r\n\r\n");
+ const host = m[1]!;
+ const port = Number(m[2]);
+ connects.push({ atyp: "http", host, port });
+ if (opts.auth !== undefined) {
+ const want = `Basic ${Buffer.from(opts.auth).toString("base64")}`;
+ if (!head.split("\r\n").some((l) => l.toLowerCase() === `proxy-authorization: ${want}`.toLowerCase())) {
+ return void sock.end("HTTP/1.1 407 Proxy Authentication Required\r\n\r\n");
+ }
+ }
+ const to = opts.route(host, port);
+ if (!to) return void sock.end("HTTP/1.1 403 Forbidden\r\n\r\n");
+ const up = net.connect(to.port, to.host, () => {
+ sock.write("HTTP/1.1 200 Connection established\r\n\r\n");
+ if (rest.length) up.write(rest);
+ sock.pipe(up).pipe(sock);
+ });
+ up.on("error", () => sock.destroy());
+ };
+ sock.on("data", onData);
+ });
+ const sockets = track(server);
+ const port = await listen(server);
+ return { port, connects, close: () => closeServer(server, sockets) };
+}
+
+// An address-echo server: answers every GET with `body`.
+export async function startEchoServer(body: string): Promise<{ port: number; hits: () => number; close: () => Promise<void> }> {
+ let hits = 0;
+ const server = http.createServer((_req, res) => {
+ hits++;
+ res.writeHead(200, { "content-type": "text/plain" });
+ res.end(body);
+ });
+ const sockets = track(server);
+ const port = await listen(server);
+ return { port, hits: () => hits, close: () => closeServer(server, sockets) };
+}
+
+// A server that only counts the connections it gets (the "direct" target a
+// fail-closed test proves was never contacted).
+export async function startCountingServer(): Promise<{ port: number; connections: () => number; close: () => Promise<void> }> {
+ let n = 0;
+ const server = net.createServer((s) => {
+ n++;
+ s.destroy();
+ });
+ const sockets = track(server);
+ const port = await listen(server);
+ return { port, connections: () => n, close: () => closeServer(server, sockets) };
+}
+
+// A loopback port with nothing listening on it.
+export async function closedPort(): Promise<number> {
+ const s = net.createServer();
+ const port = await listen(s);
+ await new Promise<void>((r) => s.close(() => r()));
+ return port;
+}
diff --git a/common/ytdlp/audioCheckedDownload.ts b/common/ytdlp/audioCheckedDownload.ts
@@ -54,6 +54,8 @@ import { probeAudioStream } from "./ffmpegStreamProbe";
import { DLOM_PROBE_MARKER } from "../jobs/progressParsers";
import { jitterYtdlpSleeps } from "../lib/jitter";
import "../lib/childKillGuard";
+// What every child inherits (lib/childEnvGuard.mjs; review 2 of lane network-exits).
+import "../lib/childEnvGuard.mjs";
const STDERR_TAIL_BYTES = 64 * 1024;
const DEFAULT_SIZE_GATE_BYTES = 1024 * 1024; // 1 MiB minimum growth between checks
diff --git a/common/ytdlp/metadataScan.ts b/common/ytdlp/metadataScan.ts
@@ -51,6 +51,8 @@ import {
} from "../controller/metadataScanStore";
import { jitterYtdlpSleeps } from "../lib/jitter";
import "../lib/childKillGuard";
+// What every child inherits (lib/childEnvGuard.mjs; review 2 of lane network-exits).
+import "../lib/childEnvGuard.mjs";
// yt-dlp's JSON-subset print template: one JSON object per entry, so the scan
// parses lines instead of whole info jsons — and so nothing is ever written to
diff --git a/common/ytdlp/networkExitListing.test.ts b/common/ytdlp/networkExitListing.test.ts
@@ -0,0 +1,538 @@
+import { test, after, beforeEach } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, writeFileSync, chmodSync, mkdirSync, readFileSync, readdirSync, statSync, existsSync, rmSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/networkExitListing.test.ts
+//
+// THE LISTING THROUGH NAMED NETWORK EXITS (lane network-exits), end to end
+// below yt-dlp: a stand-in yt-dlp records its argv, stdin and proxy
+// environment and behaves like yt-dlp about proxies (the stdin `--proxy`,
+// else the environment's ALL_PROXY, else DIRECT — to a listening trap socket,
+// so a fall-back to direct is SEEN). The exits are in-process fake SOCKS5
+// proxies on loopback. ytdlp/networkExitRealYtdlp.test.ts runs the real
+// binary. getPaths() memoizes, so the env is set before anything imports it.
+const ROOT = mkdtempSync(path.join(os.tmpdir(), "network-exits-"));
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+process.env.ARCHILYZER_CREDENTIALS_DIR = ROOT;
+writeFileSync(process.env.SETTINGS_FILE, "{}\n");
+
+const { fetchFlatPlaylistUrls, runYtdlp, EnumerationIncompleteError, NetworkExitError } = await import("./runYtdlp");
+const { readListingEvidence } = await import("../controller/listingEvidence");
+const { getPaths } = await import("../lib/paths");
+const { JobDeferredError } = await import("../jobs/jobDeferred");
+const { platformCooldownRemainingMs } = await import("../jobs/downloadBackoff");
+const { stickyExitFor } = await import("../lib/networkExits");
+const NE = await import("../controller/networkExits");
+const { downloadQueueKey } = await import("../lib/queueKeys");
+const { waitForQueueGap, noteQueueJobEnd, clearQueueGaps } = await import("../jobs/queueGap");
+const { withRumbleDefaults } = await import("../lib/rumbleDefaults");
+const { closedPort, startCountingServer, startEchoServer, startFakeSocks5 } = await import("../testing/fakeProxy");
+
+const FAKE_CRED = "fake-not-a-credential";
+const trap = await startCountingServer();
+const proxyA = await startFakeSocks5({ username: "example-user-a", password: FAKE_CRED, route: () => null });
+const proxyB = await startFakeSocks5({ route: () => null });
+after(async () => {
+ await Promise.all([trap.close(), proxyA.close(), proxyB.close()]);
+ rmSync(ROOT, { recursive: true, force: true });
+});
+
+// The key file (the repo's convention): mode 600, its PATH a setting.
+const KEYS = path.join(ROOT, "network-exits.env");
+writeFileSync(KEYS, `NETWORK_EXIT_EXIT_A=example-user-a:${FAKE_CRED}\n`);
+chmodSync(KEYS, 0o600);
+
+const PROXY_A_URL = `socks5h://example-user-a:${FAKE_CRED}@127.0.0.1:${proxyA.port}`;
+
+const RECORD = path.join(ROOT, "spawns.jsonl");
+const BIN = path.join(ROOT, "fake-listing.mjs");
+writeFileSync(
+ BIN,
+ `#!/usr/bin/env node
+import { appendFileSync, readFileSync } from "node:fs";
+import net from "node:net";
+const argv = process.argv.slice(2);
+const mode = process.env.FAKE_MODE ?? "ok";
+const ci = argv.indexOf("--config-locations");
+const stdin = ci >= 0 && argv[ci + 1] === "-" && mode !== "ignore-stdin" ? readFileSync(0, "utf8") : null;
+const envProxy = {};
+for (const k of ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "all_proxy", "no_proxy"]) if (process.env[k] !== undefined) envProxy[k] = process.env[k];
+appendFileSync(process.env.FAKE_RECORD, JSON.stringify({ argv, stdin, envProxy }) + "\\n");
+const stdinProxy = stdin ? /--proxy '([^']*)'/.exec(stdin)?.[1] : undefined;
+const proxy = stdinProxy ?? process.env.ALL_PROXY ?? process.env.all_proxy;
+if (argv.includes("-v")) process.stderr.write("[debug] | Stdin config: " + JSON.stringify(stdin) + "\\n");
+if (argv.includes("-v") && proxy && mode !== "no-map" && mode !== "no-map-429") process.stderr.write("[debug] Proxy map: {'all': '" + proxy + "'}\\n");
+if (mode === "slow") {
+ process.stdout.write("https://rumble.com/v1-a.html\\n");
+ await new Promise((r) => setTimeout(r, 3000));
+}
+const finish = () => {
+ if (mode === "429" || mode === "no-map-429") {
+ process.stdout.write("https://rumble.com/v1-a.html\\n");
+ process.stderr.write("[RumbleChannel] x: Downloading page 2\\nERROR: [RumbleChannel] x: Unable to download webpage: HTTP Error 429: Too Many Requests\\n");
+ process.exit(1);
+ }
+ process.stdout.write("https://rumble.com/v1-a.html\\nhttps://rumble.com/v2-b.html\\n");
+};
+if (stdinProxy) finish();
+else {
+ // No stdin proxy: like yt-dlp, the environment's proxy, else DIRECT.
+ const port = proxy ? Number(new URL(proxy).port) : Number(process.env.FAKE_TRAP_PORT);
+ const s = net.connect(port, "127.0.0.1", () => { s.destroy(); finish(); });
+ s.on("error", () => { process.stderr.write("ERROR: Unable to connect\\n"); process.exit(1); });
+}
+`,
+);
+chmodSync(BIN, 0o755);
+process.env.FAKE_RECORD = RECORD;
+process.env.FAKE_TRAP_PORT = String(trap.port);
+
+function exitRow(id: string, port: number, extra: Record<string, unknown> = {}) {
+ return { id, label: id.toUpperCase(), scheme: "socks5h", host: "127.0.0.1", port, credentials: false, enabled: true, ...extra };
+}
+const EXITS = [exitRow("exit-a", proxyA.port, { credentials: true }), exitRow("exit-b", proxyB.port)];
+const RUMBLE_POLICY = { exits: EXITS, platforms: { rumble: { exits: ["exit-a", "exit-b"], mode: "sticky" } }, credentialsFile: KEYS };
+
+function settings(network?: unknown, extra: Record<string, unknown> = {}) {
+ writeFileSync(
+ process.env.SETTINGS_FILE!,
+ JSON.stringify({ pacing: { jitter: 0 }, ...extra, ...(network ? { network } : {}) }) + "\n",
+ );
+}
+
+const SLUGS = Array.from({ length: 40 }, (_, i) => `demo-rumble-${i}`);
+const ON_A = SLUGS.find((s) => stickyExitFor(s, ["exit-a", "exit-b"]) === "exit-a")!;
+const ON_B = SLUGS.find((s) => stickyExitFor(s, ["exit-a", "exit-b"]) === "exit-b")!;
+
+type Spawn = { argv: string[]; stdin: string | null; envProxy: Record<string, string> };
+function spawns(): Spawn[] {
+ if (!existsSync(RECORD)) return [];
+ return readFileSync(RECORD, "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l));
+}
+
+async function list(slug: string, config: Record<string, unknown> = {}, log: string[] = [], holder?: object) {
+ mkdirSync(path.join(ROOT, "channels", slug), { recursive: true });
+ writeFileSync(
+ path.join(ROOT, "channels", slug, "config.json"),
+ JSON.stringify({ handling: "transcribe", url: "https://rumble.com/c/demo", ...config }),
+ );
+ return fetchFlatPlaylistUrls({
+ channelConfig: { handling: "transcribe", url: "https://rumble.com/c/demo", ...config } as never,
+ paths: { ...getPaths(), ytdlpBin: BIN },
+ channelSlug: slug,
+ onLog: (s: string) => log.push(s),
+ signal: new AbortController().signal,
+ ...(holder ? { listingRoute: holder } : {}),
+ } as never);
+}
+
+// Today's rumble listing argv (main a0ef2b1ae), pacing jitter off.
+const MAIN_ARGV = ["--flat-playlist", "--skip-download", "--print", "url", "--impersonate", "chrome", "--sleep-requests", "1", "https://rumble.com/c/demo"];
+const ROUTED_PREFIX = ["--ignore-config", "--config-locations", "-", "-v"];
+const PROXY_VARS = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "all_proxy", "no_proxy"];
+
+beforeEach(() => {
+ rmSync(RECORD, { force: true });
+ rmSync(path.join(ROOT, ".network"), { recursive: true, force: true });
+ rmSync(path.join(ROOT, ".auto-queue"), { recursive: true, force: true });
+ for (const d of existsSync(path.join(ROOT, "channels")) ? readdirSync(path.join(ROOT, "channels")) : []) {
+ rmSync(path.join(ROOT, "channels", d, "network-exit.json"), { force: true });
+ }
+ for (const k of PROXY_VARS) delete process.env[k];
+ process.env.FAKE_MODE = "ok";
+});
+
+test("no policy: the argv, the echo, the environment and the files are today's", async () => {
+ settings();
+ process.env.HTTPS_PROXY = "http://127.0.0.1:2";
+ const log: string[] = [];
+ assert.deepEqual(await list(ON_A, {}, log), ["https://rumble.com/v1-a.html", "https://rumble.com/v2-b.html"]);
+ assert.deepEqual(spawns(), [{ argv: MAIN_ARGV, stdin: null, envProxy: { HTTPS_PROXY: "http://127.0.0.1:2" } }]);
+ assert.deepEqual(log, [`$ ${BIN} ${MAIN_ARGV.join(" ")}\n`]);
+ assert.ok(!existsSync(path.join(ROOT, ".network")));
+ assert.ok(!existsSync(NE.channelExitPath(getPaths(), ON_A)));
+});
+
+test("through an exit: --ignore-config, the proxy on stdin only, every proxy variable dead or gone (findings 2-4)", async () => {
+ settings(RUMBLE_POLICY);
+ process.env.NO_PROXY = "*";
+ process.env.no_proxy = "*";
+ process.env.HTTPS_PROXY = "http://127.0.0.1:2";
+ const log: string[] = [];
+ await list(ON_A, {}, log);
+ const [s] = spawns();
+ assert.deepEqual(s!.argv, [...ROUTED_PREFIX, ...MAIN_ARGV]);
+ assert.equal(s!.stdin, `--proxy '${PROXY_A_URL}'\n`);
+ // NO_PROXY gone; the proxy variables point at a loopback port that refuses.
+ assert.deepEqual(Object.keys(s!.envProxy).sort(), ["ALL_PROXY", "HTTPS_PROXY", "HTTP_PROXY", "all_proxy", "http_proxy", "https_proxy"]);
+ for (const v of Object.values(s!.envProxy)) assert.equal(v, "socks5h://127.0.0.1:1");
+ const text = log.join("");
+ assert.ok(!text.includes(FAKE_CRED) && !text.includes("example-user-a"), text);
+ assert.ok(!text.includes("[debug]"), "yt-dlp's debug lines stay out of the job log");
+ assert.match(text, new RegExp(`Network exit: "exit-a" \\(socks5h://127\\.0\\.0\\.1:${proxyA.port} \\(credentials\\)\\)`));
+ assert.match(text, /yt-dlp confirmed the listing's proxy is exit "exit-a"/);
+});
+
+test("a direct spawn under a policy has every inherited proxy variable removed (finding 2)", async () => {
+ settings(RUMBLE_POLICY);
+ process.env.HTTPS_PROXY = "http://127.0.0.1:2";
+ process.env.no_proxy = "*";
+ await list(ON_A, { cookiesFromBrowser: "firefox", cookieMode: "always" });
+ const [s] = spawns();
+ assert.ok(!s!.argv.includes("--config-locations"));
+ assert.deepEqual(s!.envProxy, {});
+});
+
+test("a child that ignores stdin meets the dead proxy, never the direct path (finding 3)", async () => {
+ settings(RUMBLE_POLICY);
+ process.env.FAKE_MODE = "ignore-stdin";
+ const before = trap.connections();
+ await assert.rejects(list(ON_B), /through network exit "exit-b"|did not show/);
+ assert.equal(trap.connections(), before, "nothing reached the direct path");
+});
+
+test("a listing whose output does not show the proxy is discarded and fails closed (finding 3)", async () => {
+ settings(RUMBLE_POLICY);
+ process.env.FAKE_MODE = "no-map";
+ await assert.rejects(list(ON_B), (err: unknown) => {
+ assert.ok(err instanceof NetworkExitError);
+ assert.match(err.message, /could not show that the rumble listing went through network exit "exit-b" — its result is discarded/);
+ return true;
+ });
+});
+
+test("sticky: chosen once by the hash, recorded, kept; adding an exit moves no one", async () => {
+ settings(RUMBLE_POLICY);
+ await list(ON_B);
+ assert.equal((await NE.readChannelExitRecord(getPaths(), ON_B))!.exit, "exit-b");
+ settings({ ...RUMBLE_POLICY, exits: [...EXITS, exitRow("exit-c", proxyB.port)], platforms: { rumble: { exits: ["exit-c", "exit-a", "exit-b"] } } });
+ await list(ON_B);
+ assert.equal((await NE.readChannelExitRecord(getPaths(), ON_B))!.exit, "exit-b");
+});
+
+test("a recorded exit disabled or removed FAILS the listing; nothing re-chooses it (finding 5)", async () => {
+ settings(RUMBLE_POLICY);
+ await list(ON_A);
+ const n = spawns().length;
+ for (const net of [
+ { ...RUMBLE_POLICY, exits: [{ ...EXITS[0], enabled: false }, EXITS[1]] },
+ { ...RUMBLE_POLICY, exits: [EXITS[1]], platforms: { rumble: { exits: ["exit-b"] } } },
+ ]) {
+ settings(net);
+ await assert.rejects(list(ON_A), (err: unknown) => {
+ assert.ok(err instanceof NetworkExitError);
+ assert.match(err.message, /recorded network exit "exit-a" is no longer an enabled exit of rumble .* pnpm ops network-exit/);
+ return true;
+ });
+ }
+ assert.equal(spawns().length, n);
+ assert.equal((await NE.readChannelExitRecord(getPaths(), ON_A))!.exit, "exit-a");
+ // A policy taken away on purpose is direct again.
+ settings({ ...RUMBLE_POLICY, platforms: {} });
+ await list(ON_A);
+ assert.deepEqual(spawns().at(-1)!.argv, MAIN_ARGV);
+});
+
+test("unreadable settings, a broken network block, or missing credentials fail the listing, never direct (finding 5)", async () => {
+ settings(RUMBLE_POLICY);
+ await list(ON_A);
+ const n = spawns().length;
+ writeFileSync(process.env.SETTINGS_FILE!, "{ not json");
+ await assert.rejects(list(ON_A), /settings\.json could not be read .* the rumble listing was not sent/);
+ await assert.rejects(list(ON_B), /settings\.json could not be read/);
+ settings({ ...RUMBLE_POLICY, exits: [{ ...EXITS[0], host: "bad host" }, EXITS[1]] });
+ await assert.rejects(list(ON_A), /network settings do not validate: network\.exits\[0\]\.host/);
+ settings({ ...RUMBLE_POLICY, credentialsFile: path.join(ROOT, "absent.env") });
+ await assert.rejects(list(ON_A), /exit "exit-a" needs credentials/);
+ assert.equal(spawns().length, n);
+});
+
+test("reassign only by the action: network-exit {slug, exit}", async () => {
+ settings(RUMBLE_POLICY);
+ await list(ON_A);
+ assert.deepEqual(await NE.assignChannelExit({ paths: getPaths(), slug: ON_A, exit: "exit-b" }), { slug: ON_A, platform: "rumble", exit: "exit-b", previous: "exit-a" });
+ await list(ON_A);
+ assert.ok(spawns().at(-1)!.stdin!.includes(`:${proxyB.port}`));
+ await NE.assignChannelExit({ paths: getPaths(), slug: ON_A, exit: "direct" });
+ await list(ON_A);
+ assert.deepEqual(spawns().at(-1)!.argv, MAIN_ARGV);
+ await assert.rejects(NE.assignChannelExit({ paths: getPaths(), slug: ON_A, exit: "exit-z" }), /no exit "exit-z"/);
+});
+
+test("cookies supplied any way keep the listing direct (finding 4)", async () => {
+ const ways: Array<[string, Record<string, unknown>, Record<string, unknown>]> = [
+ ["global browser cookies, always", {}, { cookiesFromBrowser: "firefox", cookieMode: "always" }],
+ ["channel browser cookies, always", { cookiesFromBrowser: "firefox", cookieMode: "always" }, {}],
+ ["a cookie file", { ytdlpExtraArgs: ["--cookies", "/tmp/jar.txt"] }, {}],
+ ["an abbreviated option", { ytdlpExtraArgs: ["--cookies-from-b", "firefox"] }, {}],
+ ["a header", { ytdlpExtraArgs: ["--add-headers", "Cookie: cf_clearance=x"] }, {}],
+ ["a config file", { ytdlpExtraArgs: ["--config-locations", "/tmp/yt.conf"] }, {}],
+ ["netrc", { ytdlpExtraArgs: ["-n"] }, {}],
+ ["a Rumble channel made with the defaults", withRumbleDefaults({ handling: "transcribe", platform: "rumble", url: "https://rumble.com/c/demo" } as never) as never, {}],
+ ];
+ for (const [what, config, global] of ways) {
+ settings(RUMBLE_POLICY, global);
+ rmSync(RECORD, { force: true });
+ const log: string[] = [];
+ await list(ON_A, config, log);
+ const [s] = spawns();
+ assert.ok(!s!.argv.includes("--config-locations") || s!.argv.indexOf("--config-locations") > 3, what);
+ assert.equal(s!.stdin, null, what);
+ assert.match(log.join(""), /Network exit: direct \(this listing carries a login/, what);
+ }
+});
+
+test("a 429 through an exit rests that exit only; its channels wait; when both rest the platform is due", async () => {
+ settings(RUMBLE_POLICY);
+ process.env.FAKE_MODE = "429";
+ await assert.rejects(list(ON_A), (err: unknown) => {
+ assert.ok(err instanceof EnumerationIncompleteError);
+ assert.equal(err.exit, "exit-a");
+ assert.equal(err.platformBackoffDue, false);
+ return true;
+ });
+ assert.equal(await platformCooldownRemainingMs("rumble", getPaths()), 0);
+ process.env.FAKE_MODE = "ok";
+ const before = spawns().length;
+ await assert.rejects(list(ON_A), (err: unknown) => err instanceof JobDeferredError && /rests until/.test(err.message));
+ assert.equal(spawns().length, before, "no hop: nothing was sent");
+ assert.equal((await list(ON_B)).length, 2);
+ process.env.FAKE_MODE = "429";
+ await assert.rejects(list(ON_B), (err: unknown) => err instanceof EnumerationIncompleteError && err.platformBackoffDue === true);
+});
+
+test("one job, one exit: the route is pinned for every page; a rest mid-walk defers, never switches (finding 7)", async () => {
+ settings(RUMBLE_POLICY);
+ const job = {};
+ await list(ON_A, {}, [], job);
+ // A reassignment between two pages of the same job.
+ await NE.assignChannelExit({ paths: getPaths(), slug: ON_A, exit: "exit-b" });
+ await list(ON_A, {}, [], job);
+ const [p1, p2] = spawns();
+ assert.equal(p1!.stdin, p2!.stdin, "page 2 left by page 1's exit");
+ assert.ok(p2!.stdin!.includes(`:${proxyA.port}`));
+ // The next job takes the new assignment.
+ await list(ON_A);
+ assert.ok(spawns().at(-1)!.stdin!.includes(`:${proxyB.port}`));
+ // The pinned exit goes to rest mid-walk: the job defers.
+ await NE.restExit(getPaths(), "rumble", "exit-a", ["exit-a", "exit-b"]);
+ await assert.rejects(list(ON_A, {}, [], job), JobDeferredError);
+});
+
+test("a dead proxy fails closed: named error, nothing spawned, the direct trap untouched", async () => {
+ const dead = await closedPort();
+ const trapBefore = trap.connections();
+ settings({ ...RUMBLE_POLICY, exits: [exitRow("exit-a", dead, { credentials: true })], platforms: { rumble: { exits: ["exit-a"] } } });
+ await assert.rejects(list(ON_A), (err: unknown) => {
+ assert.ok(err instanceof NetworkExitError);
+ assert.match(err.message, /^network exit "exit-a" \(socks5h:\/\/127\.0\.0\.1:\d+ \(credentials\)\) did not answer: connection refused\. The rumble listing was not sent — a listing never falls back to direct\.$/);
+ return true;
+ });
+ assert.deepEqual(spawns(), []);
+ assert.equal(trap.connections(), trapBefore, "nothing reached the direct path");
+});
+
+test("the secret appears in no log, error, record, report or settings answer", async () => {
+ settings(RUMBLE_POLICY);
+ const log: string[] = [];
+ await list(ON_A, {}, log);
+ process.env.FAKE_MODE = "429";
+ let message = "";
+ await list(ON_A, {}, log).catch((e: Error) => (message = e.message));
+ assert.ok(message.length > 0);
+ const report = JSON.stringify(await NE.networkReport(getPaths()));
+ const files: string[] = [];
+ const walk = (d: string) => {
+ for (const n of readdirSync(d)) {
+ const p = path.join(d, n);
+ if (statSync(p).isDirectory()) walk(p);
+ else if (![KEYS, RECORD].includes(p)) files.push(readFileSync(p, "utf8"));
+ }
+ };
+ walk(ROOT);
+ for (const [what, text] of [["log", log.join("")], ["error", message], ["report", report], ["files incl. settings.json", files.join("\n")]] as const) {
+ assert.ok(!text.includes(FAKE_CRED), `${what} carries the secret`);
+ assert.ok(!text.includes("example-user-a:"), `${what} carries the userinfo`);
+ }
+});
+
+test("pacing per platform: two exits make the same requests per hour as one, at main's pace", async () => {
+ const config = { handling: "transcribe", url: "https://rumble.com/c/demo" } as never;
+ const run = async (slugs: string[]) => {
+ rmSync(RECORD, { force: true });
+ clearQueueGaps();
+ let now = 1_000_000;
+ const clock = { now: () => now, sleep: async (ms: number) => void (now += ms) };
+ const pacing = () => ({ jobGapSeconds: { rumble: 120 }, jitter: 0 });
+ const jobsDir = mkdtempSync(path.join(ROOT, "jobs-"));
+ for (let i = 0; ; i++) {
+ // The queue a listing waits on is named from its channel alone.
+ const queueKey = downloadQueueKey(config);
+ await waitForQueueGap({ paths: { jobsDir }, queueKey, pacing, clock });
+ if (now >= 1_000_000 + 3_600_000) break;
+ await list(slugs[i % slugs.length]!);
+ now += 5_000;
+ await noteQueueJobEnd({ jobsDir }, queueKey, now);
+ }
+ return spawns();
+ };
+ settings({ ...RUMBLE_POLICY, platforms: { rumble: { exits: ["exit-a"] } } });
+ const one = await run([ON_A]);
+ settings(RUMBLE_POLICY);
+ const two = await run([ON_A, ON_B]);
+ assert.equal(one.length, 29);
+ assert.equal(two.length, one.length);
+ for (const s of [...one, ...two]) assert.deepEqual(s.argv.slice(ROUTED_PREFIX.length), MAIN_ARGV);
+ assert.deepEqual(new Set(two.map((s) => /127\.0\.0\.1:(\d+)/.exec(s.stdin!)![1])), new Set([String(proxyA.port), String(proxyB.port)]));
+});
+
+test("the probe: connect-only at startup (no echo, can be off); the echo only when asked (finding 6)", async () => {
+ const echo = await startEchoServer("198.51.100.23\n");
+ const routed = await startFakeSocks5({ route: (host, port) => (host === "echo.exit.test" ? { host: "127.0.0.1", port } : null) });
+ try {
+ const exits = [exitRow("exit-a", routed.port), exitRow("exit-dead", await closedPort())];
+ const net = { exits, platforms: {}, credentialsFile: KEYS, echoUrl: `http://echo.exit.test:${echo.port}/` };
+ settings(net);
+ const lines: string[] = [];
+ NE.startupNetworkProbe({ log: (l) => lines.push(l), delayMs: 0, paths: getPaths() });
+ for (let i = 0; i < 100 && lines.length < 2; i++) await new Promise((r) => setTimeout(r, 20));
+ assert.deepEqual(lines.map((l) => l.split(":")[0]).sort(), ['network exit "exit-a"', 'network exit "exit-dead"']);
+ assert.equal(echo.hits(), 0, "the startup probe sends no echo request");
+ assert.equal(routed.greetings, 0, "and no SOCKS greeting: a connection only");
+ assert.ok(routed.connections > 0);
+ // Off: nothing at all.
+ settings({ ...net, startupProbe: false });
+ const before = routed.connections;
+ const quiet: string[] = [];
+ NE.startupNetworkProbe({ log: (l) => quiet.push(l), delayMs: 0, paths: getPaths() });
+ await new Promise((r) => setTimeout(r, 300));
+ assert.equal(routed.connections, before);
+ assert.deepEqual(quiet, []);
+ // The operator's explicit probe fetches the echo through the exit.
+ const loud = await NE.probeNetworkExits(getPaths(), undefined, new Date(), { explicit: true });
+ assert.equal(loud.exits["exit-a"]!.address, "198.51.100.23");
+ assert.equal(echo.hits(), 1);
+ } finally {
+ await Promise.all([echo.close(), routed.close()]);
+ }
+});
+
+test("in scope in a synthetic corpus: cookie-free Rumble channels and Twitch channels", () => {
+ const rumble = (extra: Record<string, unknown>) => ({ handling: "transcribe", platform: "rumble", url: "https://rumble.com/c/x", ...extra });
+ const corpus = [
+ withRumbleDefaults(rumble({}) as never),
+ withRumbleDefaults(rumble({}) as never),
+ withRumbleDefaults(rumble({}) as never),
+ rumble({ cookieMode: "when-required", cookiesFromBrowser: "firefox", ytdlpExtraArgs: ["--impersonate", "firefox"] }),
+ rumble({ ytdlpExtraArgs: ["--impersonate", "chrome"] }),
+ { handling: "transcribe", url: "https://www.twitch.tv/x/videos" },
+ { handling: "transcribe", url: "https://www.twitch.tv/y/videos", cookiesFromBrowser: "firefox", cookieMode: "always" },
+ { handling: "youtube", url: "https://www.youtube.com/@x" },
+ ];
+ const inScope = corpus.filter((c) => NE.listingRoutable(c as never, { cookiesFromBrowser: "", cookieMode: "when-required" }));
+ assert.equal(inScope.length, 3);
+});
+
+test("a policy whose exits are all disabled fails the listing; direct only when the policy names it (review 2 finding 3)", async () => {
+ settings({ ...RUMBLE_POLICY, exits: EXITS.map((e) => ({ ...e, enabled: false })) });
+ const fresh = "demo-rumble-unlisted";
+ await assert.rejects(list(fresh), (err: unknown) => {
+ assert.ok(err instanceof NetworkExitError);
+ assert.match(err.message, /network\.platforms\.rumble has no enabled exit .* the exits were turned off but the policy left in place/);
+ return true;
+ });
+ assert.equal(await NE.readChannelExitRecord(getPaths(), fresh), null, "nothing recorded");
+ assert.deepEqual(spawns(), []);
+ // A policy that NAMES direct may send a channel direct, and records it so.
+ settings({ ...RUMBLE_POLICY, exits: EXITS.map((e) => ({ ...e, enabled: false })), platforms: { rumble: { exits: ["direct", "exit-a"] } } });
+ await list(fresh);
+ assert.equal((await NE.readChannelExitRecord(getPaths(), fresh))!.exit, "direct");
+ assert.deepEqual(spawns().at(-1)!.argv, MAIN_ARGV);
+});
+
+test("a pinned exit disabled mid-walk, or a page that now carries a login, stops the job — never switches (review 2 nit 4)", async () => {
+ settings(RUMBLE_POLICY);
+ const job = {};
+ await list(ON_A, {}, [], job);
+ settings({ ...RUMBLE_POLICY, exits: [{ ...EXITS[0], enabled: false }, EXITS[1]] });
+ await assert.rejects(list(ON_A, {}, [], job), /exit "exit-a" was disabled while this job was using it/);
+ settings(RUMBLE_POLICY);
+ const job2 = {};
+ await list(ON_A, {}, [], job2);
+ await assert.rejects(list(ON_A, { cookiesFromBrowser: "firefox", cookieMode: "always" }, [], job2), /now carries a login/);
+ assert.equal(spawns().length, 2);
+});
+
+test("an aborted routed listing returns nothing (review 2 nit 5)", async () => {
+ settings(RUMBLE_POLICY);
+ mkdirSync(path.join(ROOT, "channels", ON_B), { recursive: true });
+ const ac = new AbortController();
+ process.env.FAKE_MODE = "slow";
+ const p = fetchFlatPlaylistUrls({
+ channelConfig: { handling: "transcribe", url: "https://rumble.com/c/demo" } as never,
+ paths: { ...getPaths(), ytdlpBin: BIN },
+ channelSlug: ON_B,
+ onLog: () => {},
+ signal: ac.signal,
+ });
+ for (let i = 0; i < 200 && spawns().length === 0; i++) await new Promise((r) => setTimeout(r, 10));
+ await new Promise((r) => setTimeout(r, 300));
+ ac.abort();
+ const urls = await p.catch(() => []);
+ assert.deepEqual(urls, []);
+});
+
+test("a rate limit is classified before the secret is scrubbed (review 2 nit 7)", async () => {
+ const keys = path.join(ROOT, "error-user.env");
+ writeFileSync(keys, "NETWORK_EXIT_EXIT_A=Error:Too\n");
+ chmodSync(keys, 0o600);
+ settings({ ...RUMBLE_POLICY, exits: [exitRow("exit-a", proxyB.port, { credentials: true }), EXITS[1]], credentialsFile: keys });
+ process.env.FAKE_MODE = "429";
+ await assert.rejects(list(ON_A), (err: unknown) => err instanceof EnumerationIncompleteError && err.exit === "exit-a");
+ assert.ok((await NE.exitRestUntil(getPaths(), "rumble", "exit-a"))! > Date.now());
+});
+
+// LANE verify-resume MEETS THE EXIT: a cut-short listing's entries are kept as
+// evidence for the pre-clean check — but only entries yt-dlp showed came
+// through the exit.
+async function storePlaylistJob(slug: string) {
+ mkdirSync(path.join(ROOT, "channels", slug), { recursive: true });
+ const config = { handling: "transcribe", url: "https://rumble.com/c/demo" };
+ writeFileSync(path.join(ROOT, "channels", slug, "config.json"), JSON.stringify(config));
+ return runYtdlp({
+ channelSlug: slug,
+ mode: "store-playlist",
+ channelConfig: config as never,
+ paths: { ...getPaths(), ytdlpBin: BIN },
+ onLog: () => {},
+ signal: new AbortController().signal,
+ });
+}
+
+test("a rate-limited listing CONFIRMED through its exit keeps its partial entries as evidence and rests the exit", async () => {
+ settings(RUMBLE_POLICY);
+ rmSync(path.join(ROOT, "channels", ON_A, "listing-evidence.json"), { force: true });
+ process.env.FAKE_MODE = "429";
+ await assert.rejects(storePlaylistJob(ON_A), (err: unknown) => err instanceof EnumerationIncompleteError && err.urls.length === 1 && err.exit === "exit-a");
+ const ev = await readListingEvidence(getPaths(), ON_A);
+ assert.ok(Object.keys(ev.seen).length > 0, JSON.stringify(ev));
+ assert.ok((await NE.exitRestUntil(getPaths(), "rumble", "exit-a"))! > Date.now());
+});
+
+test("a routed listing whose proxy use was NOT confirmed contributes no evidence (its entries are dropped first)", async () => {
+ settings(RUMBLE_POLICY);
+ rmSync(path.join(ROOT, "channels", ON_B, "listing-evidence.json"), { force: true });
+ process.env.FAKE_MODE = "no-map-429";
+ await assert.rejects(storePlaylistJob(ON_B), (err: unknown) => err instanceof EnumerationIncompleteError && err.urls.length === 0);
+ const ev = await readListingEvidence(getPaths(), ON_B);
+ assert.deepEqual(ev.seen, {});
+ // A clean exit with no confirmation: discarded, no evidence either.
+ process.env.FAKE_MODE = "no-map";
+ await NE.clearExitRest(getPaths(), "rumble", "exit-b");
+ await assert.rejects(storePlaylistJob(ON_B), /its result is discarded/);
+ assert.deepEqual((await readListingEvidence(getPaths(), ON_B)).seen, {});
+});
diff --git a/common/ytdlp/networkExitRealYtdlp.test.ts b/common/ytdlp/networkExitRealYtdlp.test.ts
@@ -0,0 +1,132 @@
+import { test, after } from "node:test";
+import assert from "node:assert/strict";
+import http from "node:http";
+import net from "node:net";
+import { execFileSync } from "node:child_process";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/networkExitRealYtdlp.test.ts
+//
+// THE REAL yt-dlp ON PATH, through the routed spawn (runYtdlp's
+// listThroughExit), against an in-process fake SOCKS5 proxy and a loopback
+// fake site (an RSS feed the generic extractor lists). Nothing leaves
+// 127.0.0.1: the listing URL names a TRAP port that only counts connections;
+// the proxy maps a CONNECT to that port onto the real site. So a listing that
+// arrives at the site came through the proxy, and one that went direct hits
+// the trap. Skipped when no yt-dlp is installed.
+
+const ROOT = mkdtempSync(path.join(os.tmpdir(), "net-real-ytdlp-"));
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+writeFileSync(process.env.SETTINGS_FILE, "{}\n");
+
+let haveYtdlp = true;
+try {
+ execFileSync("yt-dlp", ["--version"], { stdio: "ignore", timeout: 30_000 });
+} catch {
+ haveYtdlp = false;
+}
+
+const { listThroughExit } = await import("./runYtdlp");
+const { startCountingServer, startFakeSocks5 } = await import("../testing/fakeProxy");
+
+const RSS =
+ '<?xml version="1.0"?><rss version="2.0"><channel><title>t</title>' +
+ "<item><title>a</title><link>http://127.0.0.1:1/v1-a.html</link></item>" +
+ "<item><title>b</title><link>http://127.0.0.1:1/v2-b.html</link></item></channel></rss>";
+const seen: Array<Record<string, string | string[] | undefined>> = [];
+const site = http.createServer((req, res) => {
+ seen.push(req.headers);
+ res.writeHead(200, { "content-type": "application/rss+xml" });
+ res.end(RSS);
+});
+await new Promise<void>((r) => site.listen(0, "127.0.0.1", () => r()));
+const sitePort = (site.address() as net.AddressInfo).port;
+const trap = await startCountingServer();
+const FAKE_CRED = "fake-not-a-credential";
+const proxy = await startFakeSocks5({
+ username: "example-user-r",
+ password: FAKE_CRED,
+ route: (_h, p) => (p === trap.port ? { host: "127.0.0.1", port: sitePort } : null),
+});
+const refusing = await startFakeSocks5({ route: () => null });
+after(async () => {
+ await Promise.all([trap.close(), proxy.close(), refusing.close(), new Promise((r) => site.close(r))]);
+ rmSync(ROOT, { recursive: true, force: true });
+});
+
+const FEED = `http://127.0.0.1:${trap.port}/feed.rss`;
+const PROXY_URL = `socks5h://example-user-r:${FAKE_CRED}@127.0.0.1:${proxy.port}`;
+
+async function routed(extra: string[], opts: { proxyUrl?: string; cwd?: string } = {}) {
+ const log: string[] = [];
+ const urls = await listThroughExit({
+ bin: "yt-dlp",
+ cwd: opts.cwd ?? ROOT,
+ args: ["--flat-playlist", "--skip-download", "--print", "url", ...extra, FEED],
+ exit: "exit-r",
+ platform: "rumble",
+ proxyUrl: opts.proxyUrl ?? PROXY_URL,
+ secrets: [FAKE_CRED, `example-user-r:${FAKE_CRED}`, "example-user-r"],
+ onLog: (s) => log.push(s),
+ signal: new AbortController().signal,
+ });
+ return { urls, log: log.join("") };
+}
+
+const skip = haveYtdlp ? false : "no yt-dlp on PATH";
+
+test("the listing arrives through the proxy, not directly — urllib and curl_cffi (impersonate)", { skip }, async () => {
+ for (const extra of [[], ["--impersonate", "chrome"]]) {
+ const before = { site: seen.length, connects: proxy.connects.length };
+ const r = await routed(extra);
+ assert.deepEqual(r.urls, ["http://127.0.0.1:1/v1-a.html", "http://127.0.0.1:1/v2-b.html"], extra.join(" "));
+ assert.equal(seen.length, before.site + 1);
+ assert.deepEqual(proxy.connects.slice(before.connects), [{ atyp: "ipv4", host: "127.0.0.1", port: trap.port }]);
+ assert.equal(trap.connections(), 0, "nothing went direct");
+ assert.ok(!r.log.includes(FAKE_CRED) && !r.log.includes("example-user-r"), r.log);
+ }
+});
+
+test("an inherited NO_PROXY=* and HTTP(S)_PROXY cannot send it direct (finding 2)", { skip }, async () => {
+ const saved = { ...process.env };
+ Object.assign(process.env, { NO_PROXY: "*", no_proxy: "*", HTTP_PROXY: `http://127.0.0.1:${trap.port}`, HTTPS_PROXY: `http://127.0.0.1:${trap.port}` });
+ try {
+ const before = proxy.connects.length;
+ const r = await routed(["--impersonate", "chrome"]);
+ assert.equal(r.urls.length, 2);
+ assert.equal(proxy.connects.length, before + 1);
+ assert.equal(trap.connections(), 0);
+ } finally {
+ for (const k of ["NO_PROXY", "no_proxy", "HTTP_PROXY", "HTTPS_PROXY"]) if (saved[k] === undefined) delete process.env[k];
+ }
+});
+
+test("a yt-dlp.conf in the channel directory is ignored (finding 4)", { skip }, async () => {
+ const cwd = mkdtempSync(path.join(ROOT, "chan-"));
+ writeFileSync(path.join(cwd, "yt-dlp.conf"), '--add-headers "X-Leak: from-config"\n');
+ const before = seen.length;
+ await routed([], { cwd });
+ assert.equal(seen[before]!["x-leak"], undefined);
+});
+
+test("a proxy that refuses the destination fails the listing naming the exit; the direct trap stays at 0", { skip }, async () => {
+ await assert.rejects(routed([], { proxyUrl: `socks5h://127.0.0.1:${refusing.port}` }), (err: unknown) => {
+ assert.ok(err instanceof Error);
+ assert.match(err.message, /network exit "exit-r"/);
+ return true;
+ });
+ assert.equal(trap.connections(), 0);
+});
+
+test("a dead proxy: yt-dlp fails, the direct trap stays at 0", { skip }, async () => {
+ const dead = net.createServer();
+ await new Promise<void>((r) => dead.listen(0, "127.0.0.1", () => r()));
+ const port = (dead.address() as net.AddressInfo).port;
+ await new Promise((r) => dead.close(r));
+ await assert.rejects(routed([], { proxyUrl: `socks5h://127.0.0.1:${port}` }), /network exit "exit-r"/);
+ assert.equal(trap.connections(), 0);
+});
diff --git a/common/ytdlp/runOneYtdlp.ts b/common/ytdlp/runOneYtdlp.ts
@@ -14,6 +14,8 @@ import type { Paths } from "../lib/paths";
import { observeYtdlpServiceOutcome } from "../lib/serviceCookies-server";
import { jitterYtdlpSleeps } from "../lib/jitter";
import "../lib/childKillGuard";
+// What every child inherits (lib/childEnvGuard.mjs; review 2 of lane network-exits).
+import "../lib/childEnvGuard.mjs";
export const STDERR_TAIL_BYTES = 64 * 1024;
diff --git a/common/ytdlp/runYtdlp.ts b/common/ytdlp/runYtdlp.ts
@@ -97,7 +97,28 @@ import {
downloadGapMs,
isSubtitleDeferred,
} from "../jobs/platformBackoff";
-import { hasSubtitleRateLimit } from "../lib/availability";
+import { hasSubtitleRateLimit, isBotCheck } from "../lib/availability";
+import {
+ DIRECT_EXIT,
+ NetworkExitError,
+ exitDisplay,
+ exitPool,
+ redactFragments,
+ requestJar,
+} from "../lib/networkExits";
+import { preflightProxy } from "../lib/networkProxy-server";
+import {
+ clearExitRest,
+ countNetworkUse,
+ exitRestUntil,
+ listingPool,
+ resolveListingRoute,
+ loadNetworkStrict,
+ restExit,
+ restingSentence,
+ type ListingRoute,
+} from "../controller/networkExits";
+import { JobDeferredError } from "../jobs/jobDeferred";
import { computeKeepWindow, type KeepWindow } from "../controller/keptVideos";
import { writeCuesAfterDownload } from "../controller/normalizeTranscript";
import { downloadOneManaged } from "./downloadOneManaged";
@@ -123,6 +144,7 @@ import {
skipsAsShort,
} from "../lib/skipShorts";
import "../lib/childKillGuard";
+import { envWithoutProxies, routedChildEnv } from "../lib/childEnvGuard.mjs";
export type YtdlpMode =
| "store-playlist"
@@ -234,6 +256,10 @@ export type RunYtdlpOpts = {
// every `{...opts}` copy by reference; a run that asked nothing is not clean
// (release 17 re-review R3).
requestCounter?: { n: number };
+ // Internal: the network route of this JOB's listings (lane network-exits,
+ // review 1 finding 7), resolved on the first listing and shared by every
+ // `{...opts}` copy by reference — every page of a walk leaves by it.
+ listingRoute?: { route?: ListingRoute };
};
// The batch modes whose child writes media into `data/<id>/` — yt-dlp's own
@@ -252,7 +278,8 @@ const MEDIA_WRITING_MODES: ReadonlySet<RunYtdlpOpts["mode"]> = new Set([
// coarse timestamps rounds down, so the window opens this much earlier.
const TIER_SINCE_SLACK_MS = 2_000;
-export async function runYtdlp(opts: RunYtdlpOpts): Promise<void> {
+export async function runYtdlp(input: RunYtdlpOpts): Promise<void> {
+ const opts: RunYtdlpOpts = { ...input, listingRoute: input.listingRoute ?? {} };
if (!opts.channelConfig.url) {
throw new Error("Channel has no `url` configured");
}
@@ -493,6 +520,12 @@ export function dataDirIdForUrl(url: string): string | null {
// `Downloading page N` the extractor logged (null for an extractor that does
// not log pages); `count` is how many entries were printed before the cut.
//
+// `exit` is the network exit the listing went through (controller/
+// networkExits.ts; "direct" without one). `platformBackoffDue` says whether
+// the caller records the PLATFORM's cooldown, as it always did: true through
+// direct; through an exit only when every exit of the platform now rests — a
+// rate limit through one exit rests that exit alone.
+//
// `urls` ARE THOSE ENTRIES (lane verify-resume): what the source actually
// returned before it refused. Never a listing — nothing may be judged MISSING
// from it — but each entry in it was listed at the time of this attempt, which
@@ -503,26 +536,39 @@ export class EnumerationIncompleteError extends Error {
readonly pagesReached: number | null;
readonly count: number;
readonly urls: readonly string[];
+ readonly exit: string;
+ readonly platformBackoffDue: boolean;
constructor(
exitCode: number | undefined,
platform: string,
pagesReached: number | null,
count: number,
urls: readonly string[] = [],
+ via?: { exit: string; platformBackoffDue: boolean; restUntil?: number },
) {
super(
`yt-dlp exited with code ${exitCode} (rate-limited${
pagesReached !== null ? ` at page ${pagesReached}` : ""
- } of the listing, ${count} entries)`,
+ } of the listing, ${count} entries)` +
+ (via && via.exit !== DIRECT_EXIT
+ ? ` through network exit "${via.exit}"` +
+ (via.restUntil ? `, which rests until ${new Date(via.restUntil).toISOString()}` : "")
+ : ""),
);
this.name = "EnumerationIncompleteError";
this.platform = platform;
this.pagesReached = pagesReached;
this.count = count;
this.urls = urls;
+ this.exit = via?.exit ?? DIRECT_EXIT;
+ this.platformBackoffDue = via?.platformBackoffDue ?? true;
}
}
+// A listing that could not be sent through its network exit (lib/
+// networkExits.ts): never retried direct.
+export { NetworkExitError };
+
// The last `Downloading page N` an extractor logged — yt-dlp's paged channel
// extractors print `[RumbleChannel] <name>: Downloading page 155` per page.
export function lastListingPage(stderr: string): number | null {
@@ -560,11 +606,17 @@ async function enumeratePlaylistUrls(
// an existing entry or a max) is "stopped". Neither is a complete listing.
export type ListingEnd = "normal" | "stopped" | "cancelled";
+// THE LISTING, ROUTED (lane network-exits). `exit` is the network exit it went
+// through, or null when the platform has no network policy — and then the
+// request is today's, byte for byte: same argv, same echo, same environment,
+// same handling (spawnListing with no `via`). Under a policy the route is
+// resolved ONCE PER JOB (review 1, finding 7: `opts.listingRoute`, shared by
+// every page of a walk) and every page leaves by it.
async function enumeratePlaylist(
opts: RunYtdlpOpts,
root: string,
range?: { start: number; end?: number },
-): Promise<{ urls: string[]; ended: ListingEnd }> {
+): Promise<{ urls: string[]; ended: ListingEnd; exit: string | null }> {
const args: string[] = [
"--flat-playlist",
"--skip-download",
@@ -583,17 +635,265 @@ async function enumeratePlaylist(
),
opts.channelConfig.url!,
);
+ const platform = cooldownPlatformKey(opts.channelConfig);
+ let route = opts.listingRoute?.route;
+ if (!route) {
+ route = await resolveListingRoute({
+ paths: opts.paths,
+ slug: opts.channelSlug,
+ platform,
+ argv: args,
+ });
+ if (opts.listingRoute) opts.listingRoute.route = route;
+ }
+ if (route.kind === "none") {
+ return { ...(await spawnListing(opts, root, args)), exit: null };
+ }
+ if (route.kind === "exit" && opts.listingRoute?.route === route) await stillUsable(route, args, platform, opts.paths);
+ const exit = route.kind === "exit" ? route.exit.id : DIRECT_EXIT;
+ const via: ListingVia = { platform, exit, pool: listingPool(undefined, platform) ?? [] };
+ if (route.kind === "direct") {
+ opts.onLog(
+ `Network exit: direct (${
+ route.why === "jar"
+ ? `this listing carries a login — ${route.jar} — and a login never leaves the home address`
+ : "this channel's exit"
+ }).\n`,
+ );
+ } else {
+ // A RESTING EXIT: the channel waits for it (the job ends deferred and the
+ // scheduler comes back at its end); it never hops to another exit — not
+ // on the first page, not half way through a walk.
+ const restUntil = await exitRestUntil(opts.paths, platform, exit);
+ if (restUntil) throw new JobDeferredError(restingSentence(platform, exit, restUntil), restUntil);
+ // FAIL CLOSED: the proxy must answer before anything is sent through it,
+ // and nothing is ever sent direct instead.
+ const pf = await preflightProxy(route.proxyUrl);
+ if (!pf.ok) {
+ await countNetworkUse(opts.paths, platform, exit, { proxyFailures: 1 }).catch(() => {});
+ throw new NetworkExitError(
+ exit,
+ `network exit "${exit}" (${exitDisplay(route.exit)}) did not answer: ${redactFragments(pf.reason, route.secrets)}. ` +
+ `The ${platform} listing was not sent — a listing never falls back to direct.`,
+ );
+ }
+ via.proxyUrl = route.proxyUrl;
+ via.secrets = route.secrets;
+ opts.onLog(
+ `Network exit: "${exit}" (${exitDisplay(route.exit)}) for this ${platform} listing; ` +
+ `yt-dlp reads the proxy from its stdin, with --ignore-config.\n`,
+ );
+ }
+ return { ...(await spawnListing(opts, root, args, via)), exit };
+}
+
+// A ROUTE PINNED FOR THE JOB, CHECKED AGAIN BEFORE EACH LATER PAGE (review 2
+// nit 4): if this page's argv now carries a login, or the exit was disabled
+// or removed since the job began, the job stops — it never switches exit and
+// never goes direct. (Rests are checked per page below: they defer.)
+async function stillUsable(
+ route: Extract<ListingRoute, { kind: "exit" }>,
+ args: string[],
+ platform: string,
+ paths: Paths,
+): Promise<void> {
+ const jar = requestJar(args);
+ if (jar) {
+ throw new NetworkExitError(
+ route.exit.id,
+ `this ${platform} listing now carries a login (${jar}) and its job is pinned to network exit "${route.exit.id}"; ` +
+ `a login never leaves the home address, and a job never switches exit — the listing was not sent.`,
+ );
+ }
+ const strict = loadNetworkStrict(paths.settingsFile);
+ const now = strict.ok ? exitPool(strict.network, platform, "listing") : null;
+ if (!strict.ok || !now || !now.includes(route.exit.id)) {
+ throw new NetworkExitError(
+ route.exit.id,
+ `network exit "${route.exit.id}" was disabled while this job was using it` +
+ (strict.ok ? "" : ` (${strict.reason})`) +
+ `; the ${platform} listing stops here — a job never switches exit and never goes direct.`,
+ );
+ }
+}
+
+// How a listing under a network policy goes out: its platform, its exit, the
+// platform's pool (for the every-exit-rests check) and, through a non-direct
+// exit, the proxy URL (stdin only) and the exact values to scrub.
+type ListingVia = { platform: string; exit: string; pool: string[]; proxyUrl?: string; secrets?: string[] };
+
+// A yt-dlp config-file line is split shell-style (and `#` starts a comment),
+// so the URL goes in single quotes. The URL is built from validated parts
+// (lib/networkExits.ts proxyUrlOf) and holds no quote.
+function configQuote(s: string): string {
+ return `'${s.replace(/'/g, `'"'"'`)}'`;
+}
+
+// EVERY PROXY VARIABLE, any case (review 1, finding 2): the environments
+// come from lib/childEnvGuard.mjs, the one place a child's environment is
+// decided. libcurl (yt-dlp's curl_cffi backend, which `--impersonate` uses)
+// applies NO_PROXY even to an explicit --proxy: an inherited `NO_PROXY=*`
+// sent an impersonated listing direct with exit 0
+// (networkExitRealYtdlp.test.ts reproduces it). The routed child gets
+// routedChildEnv(): no inherited proxy, no credential, and every proxy
+// variable pointing at a dead loopback port (finding 3).
+export { routedChildEnv as routedEnv };
+
+// Lines for the job log from a routed child's stderr, a line at a time (a
+// value is never split across two writes): yt-dlp's `[debug]` lines (-v,
+// which prints the stdin config) are dropped, and every other line has the
+// exit's exact secret values removed.
+function routedStderr(onLog: (s: string) => void, secrets: readonly string[]) {
+ let pending = "";
+ const emit = (text: string) => {
+ const kept = text.split(/(?<=\n)/).filter((l) => !l.startsWith("[debug]"));
+ if (kept.length) onLog(redactFragments(kept.join(""), secrets));
+ };
+ return {
+ push(chunk: string) {
+ pending += chunk;
+ const nl = pending.lastIndexOf("\n");
+ if (nl < 0) return;
+ emit(pending.slice(0, nl + 1));
+ pending = pending.slice(nl + 1);
+ },
+ flush() {
+ if (pending) emit(pending);
+ pending = "";
+ },
+ };
+}
+
+// THE ROUTED SPAWN. `--ignore-config` (no user, cwd or system config rides
+// through the exit — finding 4), `--config-locations -` (the proxy on stdin,
+// never in argv or /proc/<pid>/cmdline), `-v` (so yt-dlp itself says which
+// proxy it used), an environment with every proxy variable pointing at a
+// dead loopback port (a child that ignored stdin fails instead of listing
+// direct — finding 3). `confirmed`: yt-dlp's own `Proxy map` line names
+// exactly this proxy as `all`.
+async function spawnThroughExit(o: {
+ bin: string;
+ cwd: string;
+ args: string[];
+ proxyUrl: string;
+ secrets: readonly string[];
+ onLog: (s: string) => void;
+ signal: AbortSignal;
+}): Promise<{ urls: string[]; exitCode: number | undefined; stderr: string; unscrubbed: string; confirmed: boolean }> {
+ const argv = ["--ignore-config", "--config-locations", "-", "-v", ...o.args];
+ o.onLog(`$ ${o.bin} ${argv.join(" ")}\n`);
+ const child = execa(o.bin, argv, {
+ cwd: o.cwd,
+ cancelSignal: o.signal,
+ all: false,
+ buffer: true,
+ reject: false,
+ input: `--proxy ${configQuote(o.proxyUrl)}\n`,
+ env: routedChildEnv(),
+ extendEnv: false,
+ });
+ const log = routedStderr(o.onLog, o.secrets);
+ child.stderr?.on("data", (c: Buffer) => log.push(c.toString("utf8")));
+ const result = await child;
+ log.flush();
+ const raw = String(result.stderr ?? "");
+ const confirmed = raw.split("\n").some((l) => l.trim() === `[debug] Proxy map: {'all': '${o.proxyUrl}'}`);
+ // Classified as yt-dlp wrote it (review 2 nit 7: a scrubbed short user name
+ // could rewrite "Error" or "429"); in memory only, never logged or thrown.
+ const unscrubbed = raw
+ .split("\n")
+ .filter((l) => !l.startsWith("[debug]"))
+ .join("\n");
+ const stderr = redactFragments(unscrubbed, o.secrets);
+ const urls = String(result.stdout ?? "")
+ .split("\n")
+ .map((s) => s.trim())
+ .filter(Boolean);
+ return { urls, exitCode: result.exitCode, stderr, unscrubbed, confirmed };
+}
+
+function discardedError(platform: string, exit: string): NetworkExitError {
+ return new NetworkExitError(
+ exit,
+ `network exit "${exit}": yt-dlp's output could not show that the ${platform} listing went through network exit ` +
+ `"${exit}" — its result is discarded and the listing fails (it never counts as a direct listing).`,
+ );
+}
+
+// ONE LISTING THROUGH AN EXIT, for a caller with no channel (the real-yt-dlp
+// test): the routed spawn, its failure naming the exit, an unconfirmed
+// result discarded.
+export async function listThroughExit(o: {
+ bin: string;
+ cwd: string;
+ args: string[];
+ exit: string;
+ platform: string;
+ proxyUrl: string;
+ secrets: readonly string[];
+ onLog: (s: string) => void;
+ signal: AbortSignal;
+}): Promise<string[]> {
+ const r = await spawnThroughExit(o);
+ if (r.exitCode !== 0 && r.exitCode !== 101) {
+ throw new Error(`yt-dlp exited with code ${r.exitCode} through network exit "${o.exit}"`);
+ }
+ if (!r.confirmed) throw discardedError(o.platform, o.exit);
+ o.onLog(`yt-dlp confirmed the listing's proxy is exit "${o.exit}".\n`);
+ return r.urls;
+}
+
+async function spawnListing(
+ opts: RunYtdlpOpts,
+ root: string,
+ args: string[],
+ via?: ListingVia,
+): Promise<{ urls: string[]; ended: ListingEnd }> {
// The fixed waits drawn once for this run (lib/jitter.mjs).
const spawned = jitterYtdlpSleeps(args);
- opts.onLog(`$ ${opts.paths.ytdlpBin} ${spawned.join(" ")}\n`);
if (opts.requestCounter) opts.requestCounter.n++;
+ if (via) await countNetworkUse(opts.paths, via.platform, via.exit, { requests: 1 }).catch(() => {});
+ if (via?.proxyUrl) {
+ const r = await spawnThroughExit({
+ bin: opts.paths.ytdlpBin,
+ cwd: root,
+ args: spawned,
+ proxyUrl: via.proxyUrl,
+ secrets: via.secrets ?? [],
+ onLog: opts.onLog,
+ signal: opts.signal,
+ });
+ // An aborted listing is not a listing, and nothing unconfirmed is kept
+ // (review 2 nit 5) — not as a listing, not as evidence.
+ if (opts.signal.aborted) return { urls: [], ended: "cancelled" };
+ // ONLY A CONFIRMED LISTING IS EVIDENCE (lane verify-resume meets the
+ // exit): entries of a listing whose proxy use yt-dlp did not show are
+ // dropped before anything can record them — a rate-limited one still
+ // rests the exit, with no entries; a confirmed one keeps the entries it
+ // printed on its EnumerationIncompleteError.
+ const kept = r.confirmed ? r.urls : [];
+ if (r.exitCode !== 0 && r.exitCode !== 101) {
+ await listingFailedVia(opts, via, r.exitCode, r.unscrubbed, kept);
+ }
+ if (!r.confirmed) throw discardedError(via.platform, via.exit);
+ opts.onLog(`yt-dlp confirmed the listing's proxy is exit "${via.exit}".\n`);
+ if (r.exitCode === 101) opts.onLog(`yt-dlp stopped on existing entry (exit 101).\n`);
+ // A clean listing through an exit ends its rest and its escalation.
+ await clearExitRest(opts.paths, via.platform, via.exit).catch(() => {});
+ return { urls: r.urls, ended: r.exitCode === 0 ? "normal" : "stopped" };
+ }
+ opts.onLog(`$ ${opts.paths.ytdlpBin} ${spawned.join(" ")}\n`);
+ // Under a policy, a DIRECT listing's environment has every proxy variable
+ // removed (finding 2): an inherited proxy never carries it — or its cookies
+ // — somewhere unintended. Without a policy, today's environment.
const child = execa(opts.paths.ytdlpBin, spawned, {
cwd: root,
cancelSignal: opts.signal,
all: false,
buffer: true,
reject: false,
+ ...(via ? { env: envWithoutProxies(), extendEnv: false } : {}),
});
child.stderr?.on("data", (c: Buffer) => opts.onLog(c.toString("utf8")));
const result = await child;
@@ -611,6 +911,7 @@ async function enumeratePlaylist(
!opts.signal.aborted
) {
const stderr = String(result.stderr ?? "");
+ if (via) await listingFailedVia(opts, via, result.exitCode, stderr, urls);
// A bot check on the listing is the service's cookies (cookie refresh
// alerts, lib/serviceCookies.ts), whatever else it is.
await observeStderrServiceSignal(opts.paths, stderr, {
@@ -668,7 +969,7 @@ async function enumerateNoting(
root: string,
source: RecordedListing["source"],
range?: { start: number; end?: number },
-): Promise<{ urls: string[]; at: string; ended: ListingEnd }> {
+): Promise<{ urls: string[]; at: string; ended: ListingEnd; exit: string | null }> {
const at = new Date().toISOString();
try {
return { ...(await enumeratePlaylist(opts, root, range)), at };
@@ -688,17 +989,70 @@ async function enumerateNoting(
}
}
+// A FAILED LISTING UNDER A NETWORK POLICY. Counted for the trial. Through
+// direct, nothing else changes: the caller goes on to today's handling.
+// Through an exit it never returns: a rate limit or a bot check RESTS the
+// exit for the platform (the cookie alert is not raised — the request carried
+// no cookies, and the answer was to the exit's address); the platform's own
+// cooldown is due only when every exit of the pool rests after a RATE LIMIT
+// (a bot check records no platform cooldown, as on direct).
+async function listingFailedVia(
+ opts: RunYtdlpOpts,
+ via: ListingVia,
+ exitCode: number | undefined,
+ stderr: string,
+ urls: readonly string[],
+): Promise<void> {
+ const rateLimited = classifyDownloadFailure(stderr, undefined) === "rate_limit";
+ const botCheck = isBotCheck(stderr);
+ const proxyFailed = via.exit !== DIRECT_EXIT && /proxy|socks/i.test(stderr);
+ await countNetworkUse(opts.paths, via.platform, via.exit, {
+ ...(rateLimited ? { rateLimits: 1 } : {}),
+ ...(botCheck ? { botChecks: 1 } : {}),
+ ...(proxyFailed ? { proxyFailures: 1 } : {}),
+ ...((rateLimited || botCheck) && via.exit !== DIRECT_EXIT ? { rests: 1 } : {}),
+ }).catch(() => {});
+ if (via.exit === DIRECT_EXIT) return;
+ if (rateLimited || botCheck) {
+ const { until, allRest } = await restExit(opts.paths, via.platform, via.exit, via.pool);
+ opts.onLog(
+ `Network exit "${via.exit}" rests for ${via.platform} until ${new Date(until).toISOString()} after ${
+ rateLimited ? "a rate limit" : "a bot check"
+ }; its channels wait for it` +
+ (allRest
+ ? rateLimited
+ ? ` — every exit of ${via.platform} now rests, so ${via.platform} cools down as before`
+ : ` — every exit of ${via.platform} now rests`
+ : "") +
+ `.\n`,
+ );
+ if (rateLimited) {
+ throw new EnumerationIncompleteError(exitCode, via.platform, lastListingPage(stderr), urls.length, urls, {
+ exit: via.exit,
+ platformBackoffDue: allRest,
+ restUntil: until,
+ });
+ }
+ throw new Error(
+ `yt-dlp exited with code ${exitCode}: a bot check through network exit "${via.exit}", which rests until ${new Date(until).toISOString()}`,
+ );
+ }
+ throw new Error(`yt-dlp exited with code ${exitCode} through network exit "${via.exit}"`);
+}
+
// Thin exported wrapper over the module-private enumeratePlaylistUrls for
// callers (e.g. the quick availability check) that only need a one-shot fresh
// flat-playlist fetch and shouldn't have to fabricate a full RunYtdlpOpts.
// enumeratePlaylistUrls only reads channelConfig, paths.ytdlpBin, onLog and
-// signal — never mode/tracker — so the cast is safe.
+// signal — never mode/tracker — so the cast is safe. `listingRoute` pins the
+// network route across several calls of one job (default: this call alone).
export type FlatPlaylistOpts = {
channelConfig: ChannelConfig;
paths: Paths;
channelSlug: string;
onLog: (s: string) => void;
signal: AbortSignal;
+ listingRoute?: { route?: ListingRoute };
// 1-based first entry; > 1 reads `-I <start>:` (see enumeratePlaylistUrls).
start?: number;
};
@@ -713,7 +1067,7 @@ export async function fetchFlatPlaylist(opts: FlatPlaylistOpts): Promise<{ urls:
const root = path.join(opts.paths.channelsDir, opts.channelSlug);
const start = opts.start && opts.start > 1 ? Math.floor(opts.start) : undefined;
return enumeratePlaylist(
- { ...opts, mode: "store-playlist" } as RunYtdlpOpts,
+ { ...opts, mode: "store-playlist", listingRoute: opts.listingRoute ?? {} } as RunYtdlpOpts,
root,
start ? { start } : undefined,
);
@@ -823,6 +1177,8 @@ async function acceptEnumeration(
opts: RunYtdlpOpts,
root: string,
urls: ReadonlyArray<string>,
+ // The listing's network exit (null: the platform has no network policy).
+ exit: string | null = null,
): Promise<{
decision: ListingDecision;
roster: Roster;
@@ -852,6 +1208,7 @@ async function acceptEnumeration(
at: now,
listedCount: listedIds.size,
verdict: decision.verdict,
+ ...(exit !== null ? { exit } : {}),
});
await writeRoster(opts.paths, opts.channelSlug, roster);
@@ -861,8 +1218,8 @@ async function acceptEnumeration(
async function storePlaylist(opts: RunYtdlpOpts): Promise<void> {
const root = channelRoot(opts);
await mkdir(root, { recursive: true });
- const { urls, at, ended } = await enumerateNoting(opts, root, "store-playlist");
- const { decision } = await acceptEnumeration(opts, root, urls);
+ const { urls, at, ended, exit } = await enumerateNoting(opts, root, "store-playlist");
+ const { decision } = await acceptEnumeration(opts, root, urls, exit);
// Complete when the lister ended normally (a cancelled one is a prefix),
// WHETHER OR NOT THE SHRINK GUARD ACCEPTS IT (review 2, F2): the guard
// keeps a sudden shrink from rewriting the playlist and the missing sets,
@@ -2270,10 +2627,11 @@ async function syncFullSweep(opts: RunYtdlpOpts): Promise<void> {
// the roster (additive, so this is safe unconditionally) and decide
// whether the listing itself may be acted on.
let urls: string[];
+ let listingExit: string | null;
let listedAt: string;
let listingEnd: ListingEnd;
try {
- ({ urls, at: listedAt, ended: listingEnd } = await enumerateNoting(opts, root, "sync-full"));
+ ({ urls, at: listedAt, ended: listingEnd, exit: listingExit } = await enumerateNoting(opts, root, "sync-full"));
} catch (err) {
if (!(err instanceof EnumerationIncompleteError)) throw err;
// A 429 part-way through the listing: what was printed is a prefix, not a
@@ -2282,8 +2640,11 @@ async function syncFullSweep(opts: RunYtdlpOpts): Promise<void> {
// a download's 429 does, then do this sync's job the cheap way.
// Best-effort, as on the download path: a failed state write must not fail
// the sync this branch exists to rescue.
+ // Through a network exit the exit rests instead (controller/
+ // networkExits.ts), and the platform cools down only once every exit of
+ // it rests (platformBackoffDue).
try {
- await opts.onPlatformBackoff?.("rate_limit");
+ if (err.platformBackoffDue) await opts.onPlatformBackoff?.("rate_limit");
} catch (backoffErr) {
opts.onLog(
`Warning: could not record the ${err.platform} cooldown (${
@@ -2294,7 +2655,7 @@ async function syncFullSweep(opts: RunYtdlpOpts): Promise<void> {
opts.onLog(
`Full sweep incomplete: 429 at ${
err.pagesReached !== null ? `page ${err.pagesReached}` : "an unknown page"
- } of the listing, ${err.count} entries — not a listing. Ran the paged walk instead; syncs wait for the ${err.platform} cooldown, then the sweep is retried.\n`,
+ } of the listing, ${err.count} entries — not a listing. Ran the paged walk instead; syncs wait for ${err.exit !== DIRECT_EXIT && !err.platformBackoffDue ? `network exit "${err.exit}" to rest` : `the ${err.platform} cooldown`}, then the sweep is retried.\n`,
);
if (opts.signal.aborted) return;
return syncPaged(opts);
@@ -2305,6 +2666,7 @@ async function syncFullSweep(opts: RunYtdlpOpts): Promise<void> {
opts,
root,
urls,
+ listingExit,
);
opts.onLog(`Full sweep: ${decision.reason}.\n`);
// Complete when it ended normally, accepted or not (see storePlaylist).
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,31 @@
# Changelog
## [Unreleased]
+- **Network exits (trial): rumble and twitch listings through named proxies.**
+ - New `settings.network`: exits `{id, label, scheme, host, port, credentials, enabled}` (`socks5h`, `socks5`,
+ `http`, `https`), a policy per platform, cookie-jar pins, `credentialsFile` and `startupProbe`. Absent = every
+ request direct, exactly as before.
+ - Credentials are never a setting: they are read from `NETWORK_EXIT_<ID>` in the environment or the mode-600
+ `credentialsFile`, percent-encoded. A proxy URL with credentials in it is refused.
+ - The trial routes only the listing requests of rumble and twitch. Any other platform or request kind, and any cookie jar
+ given an exit, is refused when saved. A listing that carries a login stays direct — so Rumble channels with the
+ browser clearance cookie (the default) stay direct.
+ - A channel's exit is a stable hash of its slug, recorded on its first listing. Only `pnpm ops network-exit` moves it;
+ a disabled or removed recorded exit fails the listing. One job keeps one exit for all its pages.
+ - Pacing is unchanged: gaps, pace, cooldowns and holds count every exit together. A 429 or bot check through an exit
+ rests that exit, and its channels wait (the sync ends deferred). The platform cools down only when every exit rests.
+ - Fail closed: a dead proxy, unreadable settings, missing credentials, or a yt-dlp output that does not show the proxy
+ fail the listing and name the exit. Routed listings run with `--ignore-config`, the proxy on stdin, and every proxy
+ variable pointed at a dead port; direct listings under a policy have them removed.
+ - Once any network policy exists, no child process (yt-dlp, gallery-dl, ffmpeg, a browser) inherits a proxy variable,
+ and `NETWORK_EXIT_*` is moved out of the environment at boot so no child ever sees it. A policy whose exits are all
+ disabled fails its listings; the key file must be yours, mode 600, under the config directory.
+ The policy is read from the editor's settings file in every process; when it cannot be read, a policy is
+ assumed. Saving any policy also takes an inherited proxy from wrangler, git, pnpm and the browsers. The editor
+ and umtool refuse to start if this guard cannot install. Every yt-dlp option is classified by hand; one that is
+ not counts as a login.
+ - `pnpm ops network`, `pnpm ops network-exit`, `pnpm ops get network [--probe]`, and /settings → Network exits. The
+ startup probe only connects to each proxy and can be turned off. Not a disguise: no fingerprint or user-agent changes.
- **The copies scan dates a re-upload by the stream's day, not the upload's, and says what it could not date.**
- Before, it dated every video by its channel's `recordedDate` rule, else its upload day. A re-upload channel with
no rule was dated by its uploads, months after the streams its live mirror held, and the scan answered "0
diff --git a/editor/app/api/ops/_read.ts b/editor/app/api/ops/_read.ts
@@ -41,6 +41,9 @@ export async function readRoute(
// talks to. Any string under a key that names a secret is replaced by
// "<redacted>" ("" stays "", so "unset" still reads as unset).
const SECRET_KEY = /token|secret|password|passwd|api[-_]?key|credential/i;
+// Paths, not secrets: the file a secret lives in is shown (review 2 of lane
+// network-exits — the operator reads which key file is in use).
+const PATH_KEYS = new Set(["credentialsFile"]);
export function redactSecrets<T>(value: T): T {
if (Array.isArray(value)) return value.map(redactSecrets) as T;
@@ -48,7 +51,7 @@ export function redactSecrets<T>(value: T): T {
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
out[k] =
- SECRET_KEY.test(k) && typeof v === "string" && v !== ""
+ SECRET_KEY.test(k) && !PATH_KEYS.has(k) && typeof v === "string" && v !== ""
? "<redacted>"
: redactSecrets(v);
}
diff --git a/editor/app/api/ops/network-exit/route.ts b/editor/app/api/ops/network-exit/route.ts
@@ -0,0 +1,25 @@
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { NetworkInputError, assignChannelExit } from "yt-dlp-transcript-common/controller/networkExits";
+import { OpsInputError, ops, reqSlug, reqString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, exit }
+//
+// THE OPERATOR'S REASSIGNMENT of a channel's network exit (lane
+// network-exits): the only way a channel's sticky exit changes besides its
+// exit being removed or disabled. `exit` is one of the platform's enabled
+// exits or "direct". Answers { ok, slug, platform, exit, previous }. Refused
+// for a channel whose platform has no network policy.
+export async function POST(request: Request) {
+ return ops(request, ["slug", "exit"], async (body) => {
+ try {
+ const r = await assignChannelExit({ paths: getPaths(), slug: reqSlug(body, "slug"), exit: reqString(body, "exit") });
+ return NextResponse.json({ ok: true, ...r });
+ } catch (e) {
+ if (e instanceof NetworkInputError) throw new OpsInputError(e.message);
+ throw e;
+ }
+ });
+}
diff --git a/editor/app/api/ops/network/route.ts b/editor/app/api/ops/network/route.ts
@@ -0,0 +1,51 @@
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { NETWORK_REQUEST_KEYS } from "yt-dlp-transcript-common/lib/networkExits";
+import { networkReport, probeNetworkExits } from "yt-dlp-transcript-common/controller/networkExits";
+import { NetworkSaveError, saveNetworkRequest } from "../../../settings/networkSave";
+import { OpsInputError, ops } from "../_lib";
+import { readRoute, redactSecrets } from "../_read";
+import { directEcho } from "../../../settings/networkProbe";
+
+export const dynamic = "force-dynamic";
+
+// NAMED NETWORK EXITS (lane network-exits; common/lib/networkExits.ts).
+//
+// GET /api/ops/network[?probe=1]
+// -> { ok, network: { limits, trialScope, exits: [{id, label, display, scheme,
+// host, port, credentials, enabled, probe, channels}], platforms: {<p>: {exits, mode, kinds, pool, allRest}
+// | {…, ignored}}, jars, echoUrl, rests: [{platform, exit, until, fails}],
+// usage: {"1d": {"<platform>/<exit>": {requests, rateLimits, botChecks,
+// rests, proxyFailures}}, "7d": …}, lastProbeAt } }
+// Reads files only; no field holds a secret (credentials live in
+// network.credentialsFile). `probe=1` — the operator's explicit probe —
+// first asks each enabled exit's proxy to answer (connect + SOCKS
+// greeting/login; no destination) and, only when network.echoUrl is set,
+// fetches it through each exit and once direct to name the address each
+// presents.
+//
+// POST { exits? | upsertExit? | removeExit? | platforms? | jars? | echoUrl? |
+// credentialsFile? | startupProbe? }
+// -> { ok, network: <the saved block> }
+// One write through the network writer (settings/networkSave.ts): refused
+// whole, every problem named, when it routes anything outside the trial
+// (rumble and twitch listings), gives a cookie jar an exit, or sends a
+// proxy URL with credentials in it.
+export async function GET(request: Request) {
+ return readRoute(request, ["probe"], async (q) => {
+ const paths = getPaths();
+ if (q.get("probe") === "1") await probeNetworkExits(paths, undefined, new Date(), { explicit: true, getDirect: directEcho });
+ return { network: redactSecrets(await networkReport(paths)) };
+ });
+}
+
+export async function POST(request: Request) {
+ return ops(request, NETWORK_REQUEST_KEYS, async (body) => {
+ try {
+ return NextResponse.json({ ok: true, network: redactSecrets(await saveNetworkRequest(body)) });
+ } catch (e) {
+ if (e instanceof NetworkSaveError) throw new OpsInputError(e.message);
+ throw e;
+ }
+ });
+}
diff --git a/editor/app/api/ops/settings/patch.ts b/editor/app/api/ops/settings/patch.ts
@@ -13,6 +13,8 @@ import { localOnlySettingsRefusal } from "yt-dlp-transcript-common/lib/llm/local
// - remoteArchives: an archive's corpus.json is read when it is connected.
// - storage: a location is probed and its volume recorded when added or
// re-pointed (/storage); a raw root would skip both.
+// - network: a proxy sent back masked must keep its stored credentials,
+// which only the network writer knows to do (common/lib/networkExits.ts).
export const OWNED_KEYS: Readonly<Record<string, string>> = {
channelPriority: "it is written with the lanes' trees — use `pnpm ops channel-priority`",
autoQueue:
@@ -20,6 +22,8 @@ export const OWNED_KEYS: Readonly<Record<string, string>> = {
workers: "workers are saved on /workers; `pnpm ops workers` enables and disables them",
remoteArchives: "an archive is probed (its corpus.json read) when it is connected — use `pnpm ops archives` or /sites → Connect an archive",
storage: "locations are added and re-pointed on /storage, which probes them; a channel's media moves with `pnpm ops relocate`",
+ network:
+ "network exits are written by `pnpm ops network` (or /settings → Network exits), which keeps a masked proxy's stored credentials and refuses what the trial does not route",
};
function isObject(v: unknown): v is Record<string, unknown> {
diff --git a/editor/app/channels/[slug]/pipelineActions.ts b/editor/app/channels/[slug]/pipelineActions.ts
@@ -36,6 +36,7 @@ import {
runRemoteListing,
} from "yt-dlp-transcript-common/controller/remoteListing";
import { EnumerationIncompleteError } from "yt-dlp-transcript-common/ytdlp/runYtdlp";
+import { listingRestRefusal } from "yt-dlp-transcript-common/controller/networkExits";
import {
importPlatformSignal,
resolveBitchuteImportUrl,
@@ -225,6 +226,13 @@ async function runPipelineAction(
};
}
}
+ // A LISTING ON A RESTING NETWORK EXIT waits (controller/networkExits.ts):
+ // the channel's recorded exit drew a rate limit, and a channel never moves
+ // to another exit on a failure. Read only; the listing itself checks again.
+ if (mode === "sync" || mode === "store-playlist") {
+ const resting = await listingRestRefusal(paths, slug, channelConfig.url);
+ if (resting) return { ok: false, info: true, error: resting.sentence };
+ }
// store-playlist only fetches the video list (no media written), so it is not
// gated; every other mode downloads audio/subtitles into transcriptsDir.
if (mode !== "store-playlist") {
@@ -1033,7 +1041,7 @@ export async function remoteListingAction(slug: string): Promise<StreamActionRes
const result = await runRemoteListing({ paths, slug, channelConfig, platform, onLog, signal });
onLog(`${REMOTE_LISTING_RESULT_MARKER}${JSON.stringify(result)}\n`);
} catch (err) {
- if (err instanceof EnumerationIncompleteError) {
+ if (err instanceof EnumerationIncompleteError && err.platformBackoffDue) {
await recordDownloadBackoff(platform, paths, "rate_limit").catch(() => {});
}
throw err;
diff --git a/editor/app/settings/components/NetworkExitsSection.tsx b/editor/app/settings/components/NetworkExitsSection.tsx
@@ -0,0 +1,302 @@
+"use client";
+
+// NETWORK EXITS on /settings (lane network-exits). Every control is the twin
+// of a `pnpm ops` call and gets the same refusals:
+// Save exit / Enable / Disable network {"upsertExit": {...}}
+// Remove network {"removeExit": "<id>"}
+// a platform's Save / Clear network {"platforms": {"<p>": {...} | null}}
+// Echo URL Save network {"echoUrl": "..."}
+// Startup probe on / off network {"startupProbe": true | false}
+// Probe exits get network --probe
+// Assign network-exit {"slug", "exit"}
+// No proxy credentials ever reach this page: an exit is scheme, host, port
+// and "credentials: yes/no"; the user and password live in the key file
+// network.credentialsFile names (one NETWORK_EXIT_<ID>=user:password line).
+
+import { useState, useTransition } from "react";
+import {
+ assignChannelExitAction,
+ probeNetworkAction,
+ saveNetworkAction,
+ type NetworkReport,
+} from "../networkActions";
+
+const BUTTON = "rounded-md border border-border px-2 py-1 text-xs hover:bg-muted disabled:opacity-50";
+const INPUT = "rounded-md border border-border bg-background px-2 py-1 text-sm";
+const TRIAL_PLATFORMS = ["rumble", "twitch"] as const;
+
+function probeText(p: NetworkReport["exits"][number]["probe"]): string {
+ if (!p) return "not probed";
+ if (!p.reachable) return `unreachable: ${p.reason ?? "?"}`;
+ const addr = p.address ? `, shows ${p.address}` : p.echoError ? `, echo failed: ${p.echoError}` : "";
+ return `answers${p.ms !== undefined ? ` (${p.ms} ms)` : ""}${addr}`;
+}
+
+export function NetworkExitsSection({ initial }: { initial: NetworkReport }) {
+ const [report, setReport] = useState(initial);
+ const [error, setError] = useState<string | null>(null);
+ const [pending, start] = useTransition();
+ const [draft, setDraft] = useState({ id: "", label: "", proxy: "", credentials: false });
+ const [echoUrl, setEchoUrl] = useState(initial.echoUrl);
+ const [assign, setAssign] = useState({ slug: "", exit: "direct" });
+ const exits = report.exits.filter((e) => e.id !== "direct");
+
+ const run = (fn: () => Promise<{ ok: true; report: NetworkReport } | { ok: false; error: string }>) =>
+ start(async () => {
+ setError(null);
+ const r = await fn();
+ if (r.ok) setReport(r.report);
+ else setError(r.error);
+ });
+ const save = (body: Record<string, unknown>) => run(() => saveNetworkAction(body));
+
+ const policyExits = (p: string): string[] => report.platforms[p]?.exits ?? [];
+ const togglePolicy = (p: string, id: string, on: boolean) => {
+ const cur = policyExits(p);
+ const next = on ? [...cur, id] : cur.filter((x) => x !== id);
+ save({ platforms: { [p]: next.length ? { exits: next, mode: "sticky", kinds: ["listing"] } : null } });
+ };
+
+ const counts = Object.entries(report.usage["7d"]).sort(([a], [b]) => a.localeCompare(b));
+
+ return (
+ <div className="flex flex-col gap-4" aria-label="network exits">
+ <div>
+ <h2 className="text-lg font-semibold">Network exits</h2>
+ <p className="text-xs text-muted-foreground">
+ Trial: rumble and twitch listings only. Logged-in requests stay direct. Not a disguise: no fingerprint or
+ user-agent changes.
+ </p>
+ </div>
+
+ <table className="text-sm w-full">
+ <thead>
+ <tr className="border-b border-border text-left">
+ <th className="py-1 pr-3 font-medium">Exit</th>
+ <th className="py-1 pr-3 font-medium">Proxy</th>
+ <th className="py-1 pr-3 font-medium">Probe</th>
+ <th className="py-1 font-medium" />
+ </tr>
+ </thead>
+ <tbody>
+ {report.exits.map((e) => (
+ <tr key={e.id} className="border-b border-border align-top">
+ <td className="py-1 pr-3">
+ <span className="font-mono">{e.id}</span>
+ {e.label !== e.id && <span className="text-muted-foreground"> {e.label}</span>}
+ {!e.enabled && <span className="text-muted-foreground"> (disabled)</span>}
+ </td>
+ <td className="py-1 pr-3 font-mono text-xs break-all">
+ {e.display}
+ {e.channels > 0 && <span className="text-muted-foreground"> · {e.channels} channel{e.channels === 1 ? "" : "s"}</span>}
+ </td>
+ <td className="py-1 pr-3 text-xs">{probeText(e.probe)}</td>
+ <td className="py-1 whitespace-nowrap">
+ {e.id !== "direct" && (
+ <span className="flex gap-1">
+ <button
+ type="button"
+ className={BUTTON}
+ disabled={pending}
+ onClick={() => save({ upsertExit: { id: e.id, enabled: !e.enabled } })}
+ >
+ {e.enabled ? "Disable" : "Enable"}
+ </button>
+ <button
+ type="button"
+ className={BUTTON}
+ disabled={pending}
+ onClick={() =>
+ setDraft({ id: e.id, label: e.label, proxy: `${e.scheme}://${e.host}:${e.port}`, credentials: e.credentials })
+ }
+ >
+ Edit
+ </button>
+ <button type="button" className={BUTTON} disabled={pending} onClick={() => save({ removeExit: e.id })}>
+ Remove
+ </button>
+ </span>
+ )}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+
+ <form
+ className="flex flex-wrap items-end gap-2"
+ onSubmit={(ev) => {
+ ev.preventDefault();
+ save({
+ upsertExit: {
+ id: draft.id.trim(),
+ label: draft.label.trim() || draft.id.trim(),
+ proxy: draft.proxy.trim(),
+ credentials: draft.credentials,
+ },
+ });
+ }}
+ >
+ <label className="flex flex-col text-xs">
+ Id
+ <input className={INPUT} value={draft.id} onChange={(e) => setDraft({ ...draft, id: e.target.value })} placeholder="nl-ams-1" />
+ </label>
+ <label className="flex flex-col text-xs">
+ Label
+ <input className={INPUT} value={draft.label} onChange={(e) => setDraft({ ...draft, label: e.target.value })} />
+ </label>
+ <label className="flex flex-col text-xs grow">
+ Proxy URL
+ <input
+ className={`${INPUT} font-mono`}
+ value={draft.proxy}
+ onChange={(e) => setDraft({ ...draft, proxy: e.target.value })}
+ placeholder="socks5h://host:1080 (no credentials)"
+ autoComplete="off"
+ spellCheck={false}
+ />
+ </label>
+ <label className="flex items-center gap-1 text-xs">
+ <input
+ type="checkbox"
+ checked={draft.credentials}
+ onChange={(e) => setDraft({ ...draft, credentials: e.target.checked })}
+ />
+ Credentials (in the key file)
+ </label>
+ <button type="submit" className={BUTTON} disabled={pending || !draft.id.trim() || !draft.proxy.trim()}>
+ Save exit
+ </button>
+ </form>
+
+ <div className="flex flex-col gap-2">
+ {TRIAL_PLATFORMS.map((p) => (
+ <div key={p} className="flex flex-wrap items-center gap-3 text-sm" aria-label={`${p} listing policy`}>
+ <span className="font-medium w-16">{p}</span>
+ {["direct", ...exits.map((e) => e.id)].map((id) => (
+ <label key={id} className="flex items-center gap-1 text-xs">
+ <input
+ type="checkbox"
+ disabled={pending}
+ checked={policyExits(p).includes(id)}
+ onChange={(ev) => togglePolicy(p, id, ev.target.checked)}
+ />
+ <span className="font-mono">{id}</span>
+ </label>
+ ))}
+ {report.platforms[p] ? (
+ <span className="text-xs text-muted-foreground">
+ listings spread over {report.platforms[p]!.pool?.join(", ") || "no enabled exit (direct)"}
+ {report.platforms[p]!.allRest ? " — every exit rests" : ""}
+ </span>
+ ) : (
+ <span className="text-xs text-muted-foreground">no policy: direct</span>
+ )}
+ </div>
+ ))}
+ </div>
+
+ <form
+ className="flex flex-wrap items-end gap-2"
+ onSubmit={(ev) => {
+ ev.preventDefault();
+ run(() => assignChannelExitAction(assign.slug.trim(), assign.exit));
+ }}
+ >
+ <label className="flex flex-col text-xs">
+ Channel
+ <input className={INPUT} value={assign.slug} onChange={(e) => setAssign({ ...assign, slug: e.target.value })} placeholder="slug" />
+ </label>
+ <label className="flex flex-col text-xs">
+ Exit
+ <select className={INPUT} value={assign.exit} onChange={(e) => setAssign({ ...assign, exit: e.target.value })}>
+ {["direct", ...exits.map((e) => e.id)].map((id) => (
+ <option key={id} value={id}>
+ {id}
+ </option>
+ ))}
+ </select>
+ </label>
+ <button type="submit" className={BUTTON} disabled={pending || !assign.slug.trim()}>
+ Assign
+ </button>
+ </form>
+
+ <div className="flex flex-wrap items-end gap-2">
+ <label className="flex flex-col text-xs grow">
+ Echo URL (probe only; blank = no request)
+ <input className={`${INPUT} font-mono`} value={echoUrl} onChange={(e) => setEchoUrl(e.target.value)} placeholder="https://…" />
+ </label>
+ <button type="button" className={BUTTON} disabled={pending} onClick={() => save({ echoUrl: echoUrl.trim() })}>
+ Save echo URL
+ </button>
+ <button type="button" className={BUTTON} disabled={pending} onClick={() => run(() => probeNetworkAction())}>
+ Probe exits
+ </button>
+ <label className="flex items-center gap-1 text-xs">
+ <input
+ type="checkbox"
+ disabled={pending}
+ checked={report.startupProbe}
+ onChange={(e) => save({ startupProbe: e.target.checked })}
+ />
+ Connect to each proxy at startup
+ </label>
+ </div>
+ <p className="text-xs text-muted-foreground">
+ Credentials: <span className="font-mono">{report.credentialsFile}</span> (mode 600), one{" "}
+ <span className="font-mono">NETWORK_EXIT_<ID>=user:password</span> line per exit, percent-encoded.
+ </p>
+ {report.settingsProblem && (
+ <p role="alert" className="text-xs text-destructive">
+ {report.settingsProblem}
+ </p>
+ )}
+
+ {report.rests.length > 0 && (
+ <ul className="text-xs" aria-label="resting exits">
+ {report.rests.map((r) => (
+ <li key={`${r.platform}/${r.exit}`}>
+ {r.platform} exit <span className="font-mono">{r.exit}</span> rests until {r.until.slice(11, 16)} UTC ({r.fails} in a row)
+ </li>
+ ))}
+ </ul>
+ )}
+
+ {counts.length > 0 && (
+ <table className="text-xs w-full" aria-label="network exit counts">
+ <thead>
+ <tr className="border-b border-border text-left">
+ <th className="py-1 pr-3 font-medium">Platform / exit</th>
+ <th className="py-1 pr-3 font-medium">Requests 1d / 7d</th>
+ <th className="py-1 pr-3 font-medium">429s</th>
+ <th className="py-1 pr-3 font-medium">Bot checks</th>
+ <th className="py-1 pr-3 font-medium">Rests</th>
+ <th className="py-1 font-medium">Proxy failures</th>
+ </tr>
+ </thead>
+ <tbody>
+ {counts.map(([k, c]) => (
+ <tr key={k} className="border-b border-border">
+ <td className="py-1 pr-3 font-mono">{k}</td>
+ <td className="py-1 pr-3">
+ {report.usage["1d"][k]?.requests ?? 0} / {c.requests}
+ </td>
+ <td className="py-1 pr-3">{c.rateLimits}</td>
+ <td className="py-1 pr-3">{c.botChecks}</td>
+ <td className="py-1 pr-3">{c.rests}</td>
+ <td className="py-1">{c.proxyFailures}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+
+ {error && (
+ <p role="alert" aria-label="network exits error" className="text-xs text-destructive">
+ {error}
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/editor/app/settings/components/SettingsForm.tsx b/editor/app/settings/components/SettingsForm.tsx
@@ -42,7 +42,9 @@ import {
type Props = {
// The settings WITHOUT `autoQueue` (the lanes' policy trees): this form
// reads none of it, and the page does not send it (settings/page.tsx).
- initial: Omit<SiteSettings, "autoQueue">;
+ // `network` stays server-side: its proxies may carry credentials
+ // (NetworkExitsSection gets a masked view).
+ initial: Omit<SiteSettings, "autoQueue" | "network">;
};
export function SettingsForm({ initial }: Props) {
diff --git a/editor/app/settings/networkActions.ts b/editor/app/settings/networkActions.ts
@@ -0,0 +1,63 @@
+"use server";
+
+// /settings → Network exits (lane network-exits). Each action is the twin of a
+// `pnpm ops` call: save → `pnpm ops network`, assign → `pnpm ops network-exit`,
+// probe → `pnpm ops get network --probe`. No answer holds a secret: the
+// settings never do (credentials live in network.credentialsFile).
+
+import { revalidatePath } from "next/cache";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import {
+ NetworkInputError,
+ assignChannelExit,
+ networkReport,
+ probeNetworkExits,
+ type NetworkReportView,
+} from "yt-dlp-transcript-common/controller/networkExits";
+import { NetworkSaveError, saveNetworkRequest } from "./networkSave";
+import { directEcho } from "./networkProbe";
+
+export type NetworkReport = NetworkReportView;
+type Answer = { ok: true; report: NetworkReport } | { ok: false; error: string };
+
+async function report(): Promise<NetworkReport> {
+ // Built from the stored, secret-free form (controller/networkExits.ts).
+ return networkReport(getPaths());
+}
+
+function refusal(e: unknown): { ok: false; error: string } {
+ if (e instanceof NetworkSaveError || e instanceof NetworkInputError) return { ok: false, error: e.message };
+ return { ok: false, error: (e as Error).message ?? String(e) };
+}
+
+export async function networkReportAction(): Promise<NetworkReport> {
+ return report();
+}
+
+export async function saveNetworkAction(body: Record<string, unknown>): Promise<Answer> {
+ try {
+ await saveNetworkRequest(body);
+ revalidatePath("/settings");
+ return { ok: true, report: await report() };
+ } catch (e) {
+ return refusal(e);
+ }
+}
+
+export async function assignChannelExitAction(slug: string, exit: string): Promise<Answer> {
+ try {
+ await assignChannelExit({ paths: getPaths(), slug, exit });
+ return { ok: true, report: await report() };
+ } catch (e) {
+ return refusal(e);
+ }
+}
+
+export async function probeNetworkAction(): Promise<Answer> {
+ try {
+ await probeNetworkExits(getPaths(), undefined, new Date(), { explicit: true, getDirect: directEcho });
+ return { ok: true, report: await report() };
+ } catch (e) {
+ return refusal(e);
+ }
+}
diff --git a/editor/app/settings/networkProbe.ts b/editor/app/settings/networkProbe.ts
@@ -0,0 +1,12 @@
+// The probe's one DIRECT request (lane network-exits): the operator's
+// address-echo URL fetched without a proxy, so `get network --probe` shows the
+// home address beside each exit's. Made only when network.echoUrl is set.
+export async function directEcho(url: string): Promise<{ ok: true; body: string } | { ok: false; reason: string }> {
+ try {
+ const res = await fetch(url, { signal: AbortSignal.timeout(8_000), headers: { accept: "text/plain, */*" } });
+ const body = (await res.text()).slice(0, 4096);
+ return res.ok ? { ok: true, body } : { ok: false, reason: `HTTP ${res.status}` };
+ } catch (e) {
+ return { ok: false, reason: (e as Error).message };
+ }
+}
diff --git a/editor/app/settings/networkSave.test.ts b/editor/app/settings/networkSave.test.ts
@@ -0,0 +1,95 @@
+import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { test, after } from "node:test";
+import assert from "node:assert/strict";
+
+// Run with: pnpm -C editor exec tsx --test app/settings/networkSave.test.ts
+//
+// THE NETWORK EXITS' ONE WRITER (lane network-exits): what `pnpm ops network`
+// and /settings → Network exits save and refuse. Review 1, finding 1: a
+// proxy's credentials are never a setting — a URL carrying them is refused
+// (with how to percent-encode, and where the key file is), and every answer
+// is built from the stored, secret-free form. getPaths() memoizes, so
+// SETTINGS_FILE is set before the module under test is imported.
+
+const ROOT = mkdtempSync(path.join(os.tmpdir(), "network-save-"));
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+writeFileSync(process.env.SETTINGS_FILE, "{}\n");
+
+const { saveNetworkRequest, NetworkSaveError } = await import("./networkSave");
+const { saveSettings } = await import("./saveSettings");
+const { getSettings } = await import("yt-dlp-transcript-common/lib/settings");
+const { redactSecrets } = await import("../api/ops/_read");
+const { settingsPatchProblem, OWNED_KEYS } = await import("../api/ops/settings/patch");
+
+after(() => rm(ROOT, { recursive: true, force: true }));
+
+const FAKE_CRED = "fake-not-a-credential";
+
+test("an exit and a rumble listing policy save; credentials are a yes/no", async () => {
+ const a = await saveNetworkRequest({ upsertExit: { id: "exit-a", proxy: "socks5h://exit-a.example.test:1080", credentials: true } });
+ assert.deepEqual(a.exits[0], { id: "exit-a", label: "exit-a", scheme: "socks5h", host: "exit-a.example.test", port: 1080, credentials: true, enabled: true });
+ await saveNetworkRequest({ upsertExit: { id: "exit-b", proxy: "socks5h://exit-b.example.test:1080" } });
+ const b = await saveNetworkRequest({ platforms: { rumble: { exits: ["direct", "exit-a", "exit-b"], mode: "sticky" } } });
+ assert.deepEqual(b.platforms.rumble, { exits: ["direct", "exit-a", "exit-b"], mode: "sticky", kinds: ["listing"] });
+});
+
+test("a proxy URL that carries credentials is refused whole, never stored or echoed (finding 1)", async () => {
+ const before = readFileSync(process.env.SETTINGS_FILE!, "utf8");
+ for (const proxy of [
+ `socks5h://example-user:${FAKE_CRED}@exit-c.example.test:1080`,
+ `socks5h://example-user:p@ss'${FAKE_CRED}@exit-c.example.test:1080`,
+ `socks5h://example-user:"${FAKE_CRED} x@exit-c.example.test:1080`,
+ ]) {
+ await assert.rejects(saveNetworkRequest({ upsertExit: { id: "exit-c", proxy } }), (e: unknown) => {
+ assert.ok(e instanceof NetworkSaveError);
+ assert.match(e.message, /credentials are not a setting|percent-encode/);
+ assert.ok(!e.message.includes(FAKE_CRED));
+ return true;
+ });
+ }
+ assert.equal(readFileSync(process.env.SETTINGS_FILE!, "utf8"), before, "nothing written");
+ assert.ok(!before.includes(FAKE_CRED));
+});
+
+test("out-of-scope platforms and kinds, and jar assignments, are refused whole with the trial's sentence", async () => {
+ const before = readFileSync(process.env.SETTINGS_FILE!, "utf8");
+ for (const [body, re] of [
+ [{ platforms: { youtube: { exits: ["exit-a"] } } }, /network\.platforms\.youtube: refused — the network-exit trial routes only the listing requests of rumble and twitch/],
+ [{ platforms: { twitch: { exits: ["exit-a"], kinds: ["download"] } } }, /kinds: "download" refused/],
+ [{ jars: { "browser:firefox": "exit-a" } }, /network\.jars\.browser:firefox: refused — a request that carries a login/],
+ [{ platforms: { rumble: { exits: ["exit-z"] } } }, /"exit-z" is not a defined exit/],
+ [{ credentialsFile: "a-pasted-value" }, /credentialsFile: the PATH of the mode-600 file/],
+ ] as const) {
+ await assert.rejects(saveNetworkRequest(body as Record<string, unknown>), (e: unknown) => {
+ assert.ok(e instanceof NetworkSaveError);
+ assert.match(e.message, re);
+ return true;
+ });
+ }
+ assert.equal(readFileSync(process.env.SETTINGS_FILE!, "utf8"), before, "nothing written");
+});
+
+test("the settings writer's floor refuses a raw out-of-scope network block too", async () => {
+ await assert.rejects(
+ saveSettings({ network: { ...getSettings().network, platforms: { youtube: { exits: ["direct", "x"], mode: "sticky", kinds: ["listing"] } } } }),
+ /network: not saved — network\.platforms\.youtube: refused/,
+ );
+});
+
+test("`pnpm ops settings` refuses network as owned; redactSecrets leaves a legitimate @ alone (finding 10)", () => {
+ assert.ok(OWNED_KEYS.network);
+ assert.match(settingsPatchProblem({ network: {} }, ["network"], {})!, /"network" is not patched here: network exits are written by `pnpm ops network`/);
+ const red = redactSecrets({ url: "https://example.org?mail=a@b.example", repo: "ssh://git@host.example/repo", token: "t", credentialsFile: "~/.config/x.env" });
+ assert.deepEqual(red, { url: "https://example.org?mail=a@b.example", repo: "ssh://git@host.example/repo", token: "<redacted>", credentialsFile: "~/.config/x.env" });
+});
+
+test("removing an exit takes it out of every policy; the startup probe can be turned off", async () => {
+ const r = await saveNetworkRequest({ removeExit: "exit-a" });
+ assert.deepEqual(r.platforms.rumble!.exits, ["direct", "exit-b"]);
+ const off = await saveNetworkRequest({ startupProbe: false });
+ assert.equal(off.startupProbe, false);
+});
diff --git a/editor/app/settings/networkSave.ts b/editor/app/settings/networkSave.ts
@@ -0,0 +1,36 @@
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import {
+ NetworkRequestError,
+ applyNetworkRequest,
+ networkSettingsProblems,
+ sanitizeNetwork,
+ type NetworkSettings,
+} from "yt-dlp-transcript-common/lib/networkExits";
+import { saveSettingsHeld, withSettingsLock } from "./saveSettings";
+
+// THE NETWORK EXITS' ONE WRITER (lane network-exits): `pnpm ops network` and
+// /settings → Network exits both send a request here. Applied to the stored
+// block (a masked proxy keeps its stored credentials), refused whole with
+// every problem named when the result is outside the trial
+// (networkSettingsProblems), then saved. The block holds no secret (review 1,
+// finding 1: credentials live in network.credentialsFile), so the answer is
+// the saved block as it is.
+//
+// Not a "use server" module: the ops route and networkActions.ts call it.
+export class NetworkSaveError extends Error {}
+
+export async function saveNetworkRequest(body: Record<string, unknown>): Promise<NetworkSettings> {
+ return withSettingsLock(async () => {
+ let next: Record<string, unknown>;
+ try {
+ next = applyNetworkRequest(getSettings().network, body);
+ } catch (e) {
+ if (e instanceof NetworkRequestError) throw new NetworkSaveError(e.message);
+ throw e;
+ }
+ const problems = networkSettingsProblems(next);
+ if (problems.length) throw new NetworkSaveError(`not saved — ${problems.join("; ")}`);
+ await saveSettingsHeld({ network: sanitizeNetwork(next) });
+ return getSettings().network;
+ });
+}
diff --git a/editor/app/settings/page.tsx b/editor/app/settings/page.tsx
@@ -18,6 +18,8 @@ import { xPacingOf } from "../lib/xPacing";
import { xMaxCookieAgeMinutes } from "yt-dlp-transcript-common/social/xCookieSource";
import { ArchiveSourcesSection } from "./components/ArchiveSessionSection";
import { readArchiveSessionStatus } from "yt-dlp-transcript-common/lib/archives/archiveTodaySession";
+import { NetworkExitsSection } from "./components/NetworkExitsSection";
+import { networkReportAction } from "./networkActions";
export const dynamic = "force-dynamic";
@@ -49,8 +51,12 @@ export default async function SettingsPage() {
// payload). Leaving it out cannot lose it: the save builds its patch from
// the submitted fields alone and merges it over the stored file
// (settings/actions.ts; pinned in saveSettingsAction.test.ts).
- const { autoQueue: _autoQueue, ...formSettings } = settings;
+ const { autoQueue: _autoQueue, network: _network, ...formSettings } = settings;
void _autoQueue;
+ // NETWORK EXITS NEVER REACH THE BROWSER RAW: a proxy URL may carry
+ // credentials. The section below gets the masked report.
+ void _network;
+ const network = await networkReportAction();
return (
<div className="flex flex-col gap-8">
@@ -128,6 +134,10 @@ export default async function SettingsPage() {
</section>
<section className="flex flex-col gap-3 border-t border-border pt-6">
+ <NetworkExitsSection initial={network} />
+ </section>
+
+ <section className="flex flex-col gap-3 border-t border-border pt-6">
<details>
<summary className="cursor-pointer text-lg font-semibold">
System paths
diff --git a/editor/app/settings/saveSettings.ts b/editor/app/settings/saveSettings.ts
@@ -6,6 +6,7 @@ import {
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { withJsonFileLock } from "yt-dlp-transcript-common/lib/jsonFile-server";
import { localOnlySettingsRefusal } from "yt-dlp-transcript-common/lib/llm/localOnly";
+import { networkSettingsProblems } from "yt-dlp-transcript-common/lib/networkExits";
// THE EDITOR'S ONE SETTINGS WRITER (one-core phase 3 slice 4a).
//
@@ -77,6 +78,13 @@ export async function saveSettingsHeld(patch: Patch): Promise<void> {
// actions): a route off `local`, or a model server not on this machine.
const localOnly = localOnlySettingsRefusal(patch as Record<string, unknown>, merged as unknown as Record<string, unknown>);
if (localOnly) throw new Error(localOnly);
+ // NETWORK EXITS (common/lib/networkExits.ts): a `network` block outside the
+ // trial's scope — another platform, another request kind, a cookie jar
+ // given an exit — is refused here too, whichever writer sent it.
+ if ((patch as Record<string, unknown>).network !== undefined) {
+ const problems = networkSettingsProblems((patch as Record<string, unknown>).network);
+ if (problems.length) throw new Error(`network: not saved — ${problems.join("; ")}`);
+ }
await writeSettings(merged);
}
diff --git a/editor/instrumentation.ts b/editor/instrumentation.ts
@@ -19,6 +19,26 @@ export async function register() {
// its transitive imports (runTick -> server actions, lmdb, fs) are Node-only,
// so guard the import — and run nothing on Edge.
if (process.env.NEXT_RUNTIME !== "nodejs") return;
+ // WHAT EVERY CHILD INHERITS (lane network-exits, reviews 2-3): before
+ // anything can spawn, NETWORK_EXIT_* credentials leave process.env and, once
+ // a network policy exists, no child inherits a proxy variable
+ // (common/lib/childEnvGuard.mjs; lib/childEnvGuard.gate.test.ts). The policy
+ // is read from the editor's own settings file. A guard that does not install
+ // is no boot: the editor refuses to start rather than run unguarded.
+ try {
+ const { setNetworkPolicySettingsFile } = await import("yt-dlp-transcript-common/lib/childEnvGuard.mjs");
+ const { getPaths } = await import("yt-dlp-transcript-common/lib/paths");
+ setNetworkPolicySettingsFile(getPaths().settingsFile);
+ } catch (e) {
+ // Nothing that runs before the exit may hand a child a credential.
+ for (const k of Object.keys(process.env)) if (k.startsWith("NETWORK_EXIT_")) delete process.env[k];
+ console.error(
+ `editor refuses to start: the child environment guard (common/lib/childEnvGuard.mjs) did not install — ${
+ e instanceof Error ? e.message : String(e)
+ }`,
+ );
+ process.exit(1);
+ }
// STORED TEXT NEEDS node:zlib zstd (common/lib/zstdSupport.mjs): on an older
// Node every caption or chat stored as `.zst` would read as unreadable — the
// index would drop its text, a lane would schedule work for it. The editor
@@ -376,6 +396,20 @@ export async function register() {
}
}
+ // NETWORK EXITS' STARTUP PROBE (lane network-exits): a minute after boot,
+ // when an exit is enabled, each proxy is asked to answer (no destination;
+ // the echo URL only when the operator set one). Below the idle gate — it
+ // connects out — and not on the e2e test server.
+ // See common/controller/networkExits.ts.
+ if (process.env.E2E_TEST_ROUTES !== "1") {
+ try {
+ const { startupNetworkProbe } = await import("yt-dlp-transcript-common/controller/networkExits");
+ startupNetworkProbe({ log: (line) => console.log(line) });
+ } catch {
+ /* a probe that fails to arm must not block server readiness */
+ }
+ }
+
// THE RECURRING REPORTS (umtool R5): the report-schedule lane — a scan now
// and every minute, ONE report-tick job per due schedule, held by its pause
// gate. Below the idle gate: a tick is generation work.
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -17,6 +17,7 @@
// pnpm ops get job <id> [--tail [<lines>]]
// pnpm ops get jobs [--active | --failed] [--kind <kind>] [--slug <slug>] [--limit <n>]
// pnpm ops get remote-listing <slug>
+// pnpm ops get network [--probe]
// pnpm ops get transcript <videoId> [--slug <slug>]
// pnpm ops get coverage <slug>
// pnpm ops job <cancel|drain|promote|force-release|retry> <id>... [--wait]
@@ -68,6 +69,10 @@
// pnpm ops live-recording-ack --json '{"slug":"demo-yt","id":"<videoId>"}'
// pnpm ops live-preclip --json '{"slug":"demo-yt","id":"<videoId>","action":"status"}'
// pnpm ops live-clip --json '{"slug":"demo-yt","id":"<videoId>","start":3605,"end":3660}' --wait
+// pnpm ops network --json '{"upsertExit":{"id":"exit-a","proxy":"socks5h://nl-ams-wg-socks5-001.relays.mullvad.net:1080"}}'
+// pnpm ops network --json '{"platforms":{"rumble":{"exits":["direct","exit-a","exit-b"],"mode":"sticky"}}}'
+// pnpm ops network --json '{"startupProbe":false}'
+// pnpm ops network-exit --json '{"slug":"demo-rumble","exit":"exit-b"}'
// pnpm ops keep-videos --json '{"slug":"demo-rumble","ids":["v1abcde"],"note":"keep"}'
// pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","dryRun":true}'
// pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","target":600}' --wait
@@ -321,6 +326,11 @@ const GETTERS = {
key ? `/api/ops/settings?key=${encodeURIComponent(key)}` : "/api/ops/settings",
// The /storage page: each location, mounted or not, its free space and tiers.
storage: () => "/api/ops/storage",
+ // Named network exits (lane network-exits): each exit (proxy masked) and its
+ // last probe, the platform policies, the resting exits and the 1- and 7-day
+ // counts per platform and exit. --probe first asks each enabled exit's proxy
+ // to answer (and, only with network.echoUrl set, the address it presents).
+ network: (_arg, { probe }) => (probe ? "/api/ops/network?probe=1" : "/api/ops/network"),
// Saved videos holding two copies (a download over a container already in
// the store keeps both): each one's active copy and its flagged alternates.
"saved-alternates": (slug) =>
@@ -445,6 +455,7 @@ const GET_JOBS = {
// Nouns whose read takes no argument. `get channel` without a slug is a
// mistake; `get tags` without one is the whole vocabulary.
const GET_ARG_OPTIONAL = new Set([
+ "network",
"tags",
"channels",
"publish",
@@ -480,6 +491,7 @@ const GET_FLAGS = {
job: ["tail"],
jobs: ["active", "failed", "kind", "slug", "limit"],
"live-recordings": ["all"],
+ network: ["probe"],
};
// The row buttons of /jobs (`POST /api/ops/job`), as `job <verb> <id…>`.
@@ -704,6 +716,12 @@ const ACTIONS = [
// ({slug, sweep}).
"settings",
"clear-platform-hold",
+ // NAMED NETWORK EXITS (lane network-exits): the exits, the platform
+ // policies, the jars and the echo URL through their one writer
+ // ({exits | upsertExit | removeExit | platforms | jars | echoUrl}); one
+ // channel's sticky exit reassigned ({slug, exit}).
+ "network",
+ "network-exit",
// COOKIE REFRESH ALERTS: a service's alert rechecked with one request
// through its own path ({service}), dismissed ({service}), or the jobs it
// stopped re-run once it is OK again ({service}).
@@ -950,6 +968,7 @@ export function parseArgs(argv) {
let leads = false;
let accounts = false;
let all = false;
+ let probe = false;
// record-live only: return once media bytes are being written.
let waitStarted = false;
let tail = 0;
@@ -1001,6 +1020,9 @@ export function parseArgs(argv) {
} else if (arg === "--all") {
all = true;
used.add("all");
+ } else if (arg === "--probe") {
+ probe = true;
+ used.add("probe");
} else if (arg === "--wait-started") {
waitStarted = true;
} else if (arg === "--active" || arg === "--failed") {
@@ -1122,7 +1144,7 @@ export function parseArgs(argv) {
}
return {
method: "GET",
- path: GETTERS[noun](positional[2], { counts, leads, accounts, all, tail, jobs }),
+ path: GETTERS[noun](positional[2], { counts, leads, accounts, all, tail, jobs, probe }),
wait: false,
quiet,
waitTimeout,
@@ -1410,6 +1432,7 @@ export function usage() {
" pnpm ops job wait <id>... [--wait-timeout <seconds>]",
" pnpm ops get settings [<key>]",
" pnpm ops get storage | sites | workers | auto-queue | scheduler",
+ " pnpm ops get network [--probe]",
" pnpm ops get saved-alternates [<slug>]",
" pnpm ops get compaction-review [<slug>]",
" pnpm ops get kept-originals [<slug>]",
@@ -1699,7 +1722,7 @@ export function usage() {
' {"patch": {"<top-level key>": value, …}} (SETTINGS.md). A block\'s keys',
' merge one level; an array, a scalar or an object nested in a block',
' replaces. Refused before anything is written: an unknown key; a key',
- ' another writer owns (channelPriority, autoQueue, workers, storage — the',
+ ' another writer owns (channelPriority, autoQueue, workers, storage, network — the',
' refusal names it); a value the schema would not keep as sent (clamped,',
' dropped), named with what would be saved. Answers the saved values.',
"",
@@ -1757,6 +1780,41 @@ export function usage() {
'clear-platform-hold clears a platform\'s rate-limit hold, backoff and raised',
' pace, as the lane strip\'s Clear hold: {"platform"}. Answers the sentence.',
"",
+ 'network writes the named network exits (settings.network) through their one',
+ ' writer, as /settings → Network exits: {"upsertExit": {"id", "label"?,',
+ ' "proxy"?: "socks5h://host:port", "credentials"?: true|false, "enabled"?}},',
+ ' {"removeExit": "<id>"} (also out of every policy), {"exits": [...]} (the',
+ ' whole list, stored form {id, label, scheme, host, port, credentials,',
+ ' enabled}), {"platforms": {"<platform>": {"exits": [ids, "direct" allowed],',
+ ' "mode": "sticky"} | null}}, {"jars": {...}}, {"echoUrl": "<url>" | ""},',
+ ' {"credentialsFile": "<path>"}, {"startupProbe": true|false}. CREDENTIALS',
+ ' ARE NEVER A SETTING: a proxy URL with user:password in it is refused; give',
+ ' the exit "credentials": true and put NETWORK_EXIT_<ID>=user:password',
+ ' (percent-encoded) in the mode-600 file network.credentialsFile names',
+ ' (default ~/.config/archilyzer/network-exits.env), or in the environment.',
+ ' THE TRIAL routes only rumble and twitch LISTINGS: any other platform or',
+ ' request kind, and any cookie jar given an exit, is refused whole, every',
+ ' problem named. A channel\'s exit is a stable hash of its slug over the',
+ ' enabled exits, recorded on its first listing; a recorded exit that is',
+ ' disabled or removed FAILS that channel\'s listings until network-exit',
+ ' moves it, and a policy whose exits are all disabled fails every listing',
+ ' ("direct" only when the policy names it). One job keeps one exit for',
+ ' every page. Once any policy exists no child process inherits a proxy',
+ ' variable, and NETWORK_EXIT_* never reaches a child. A listing that carries a',
+ ' login (cookies, a header, a token, a config file) goes direct; a 429 or',
+ ' bot check rests that exit (its channels wait); a proxy that does not',
+ ' answer, unreadable settings, missing credentials, or a yt-dlp output that',
+ ' does not show the proxy fail the listing — never a fallback to direct. Not',
+ ' a disguise: no fingerprint or user-agent changes, and a login never moves.',
+ ' get network [--probe] reports each exit (no secret in it), the rests, the',
+ ' channels per exit and the 1- and 7-day counts; --probe asks each proxy to',
+ ' answer (and fetches network.echoUrl through it only when set). The',
+ ' startup probe only connects to each proxy (startupProbe: false turns it off).',
+ "",
+ 'network-exit reassigns one channel\'s exit: {"slug", "exit"} (an enabled',
+ ' exit of its platform\'s policy, or "direct"). The only way a channel moves',
+ ' besides its exit being removed or disabled.',
+ "",
'recheck-service asks a service whose cookie refresh alert is up ONE request',
' through its own path, as the dashboard banner\'s Recheck: {"service"}',
' ("rumble", "youtube", "odysee", "archive.today", "x", "instagram" or a',
diff --git a/settings.json.example b/settings.json.example
@@ -27,6 +27,14 @@
"jobGapSeconds": {},
"jitter": 0.25
},
+ "network": {
+ "exits": [],
+ "platforms": {},
+ "jars": {},
+ "echoUrl": "",
+ "credentialsFile": "~/.config/archilyzer/network-exits.env",
+ "startupProbe": true
+ },
"downloadFormat": "auto",
"sourceVideoQuality": "original",
"minFreeDiskGB": 5,
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -148,6 +148,11 @@
// umtool candidates <project> [ls | import <sweep.md> | add <json>] proposed clips for the Cut tab's Candidates panel
// umtool ingredient <channel>/<video> [--window <from>-<to>] [--used-in] [--json] a recording's life cycle, nine stages (/ingredients)
import process from "node:process";
+// What every child inherits (lane network-exits): installed before anything
+// can spawn (common/lib/childEnvGuard.mjs), and told below which settings
+// file holds the policy — the editor's (SETTINGS_FILE, else the checkout's),
+// never the cwd's.
+import { setNetworkPolicySettingsFile } from "../../common/lib/childEnvGuard.mjs";
import { zstdSupportProblem } from "yt-dlp-transcript-common/lib/zstdSupport.mjs";
import {
PROJECT_KINDS,
@@ -177,6 +182,10 @@ import { rejectionOf } from "../lib/report/rejectReasons.mjs";
import { hms } from "umtool-report-to-video/attribution";
import { gappedLength, gapSpan, gapsOf, gapsText, parseGapSpec } from "umtool-report-to-video/gaps";
+// The policy the child-environment guard reads is the settings file getPaths()
+// names in this process (umtool/lib/paths.mjs editorSettingsFile).
+setNetworkPolicySettingsFile(editorSettingsFile());
+
/** What the walk said about a clip, with why when it was rejected: "rejected (irrelevant: covered in c07)". */
const reviewWords = (e) => {
const r = rejectionOf(e);
@@ -194,7 +203,7 @@ import { probeTools } from "../lib/tools.mjs";
import { notesCommand } from "../lib/annotations/cli.mjs";
import { scaffoldReportVideo } from "../lib/projects/scaffold.mjs";
import { rootsReport } from "../lib/system/roots.mjs";
-import { ARTICLES_DIR, ARTICLES_KEY, MEDIA_ROOT, MEDIA_TIERED, SITES_DIR } from "../lib/paths.mjs";
+import { ARTICLES_DIR, ARTICLES_KEY, MEDIA_ROOT, MEDIA_TIERED, SITES_DIR, editorSettingsFile } from "../lib/paths.mjs";
import {
deliverablesState,
moveDeliverables,
diff --git a/umtool/instrumentation.ts b/umtool/instrumentation.ts
@@ -13,6 +13,25 @@ import { isIdleBoot } from "yt-dlp-transcript-common/lib/idleBoot";
export async function register() {
if (process.env.NEXT_RUNTIME !== "nodejs") return;
+ // WHAT EVERY CHILD INHERITS (lane network-exits, reviews 2-3): before anything
+ // can spawn, NETWORK_EXIT_* credentials leave process.env and, once a
+ // network policy exists, no child inherits a proxy variable
+ // (common/lib/childEnvGuard.mjs; lib/childEnvGuard.gate.test.ts).
+ try {
+ const { setNetworkPolicySettingsFile } = await import("yt-dlp-transcript-common/lib/childEnvGuard.mjs");
+ const { getPaths } = await import("yt-dlp-transcript-common/lib/paths");
+ setNetworkPolicySettingsFile(getPaths().settingsFile);
+ } catch (e) {
+ // Nothing that runs before the exit may hand a child a credential.
+ for (const k of Object.keys(process.env)) if (k.startsWith("NETWORK_EXIT_")) delete process.env[k];
+ // A guard that does not install is no boot (review 3 nit 4).
+ console.error(
+ `umtool refuses to start: the child environment guard (common/lib/childEnvGuard.mjs) did not install — ${
+ e instanceof Error ? e.message : String(e)
+ }`,
+ );
+ process.exit(1);
+ }
// ARCHILYZER_NO_NETWORK (common/lib/noNetwork.mjs) is the test harness's switch. A server booted with it reaches
// no site at all, so it is said first and loudly: set by accident in a service unit, it must not pass for a
// normal boot.
diff --git a/umtool/lib/editorSettingsFile.test.mjs b/umtool/lib/editorSettingsFile.test.mjs
@@ -0,0 +1,35 @@
+import { test, after } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { editorSettingsFile } from "./paths.mjs";
+
+// Run with: node --test umtool/lib/editorSettingsFile.test.mjs
+//
+// THE SETTINGS FILE THE umtool CLI NAMES TO THE CHILD-ENVIRONMENT GUARD
+// (lane network-exits, review 4 nit 3): the one common/lib/paths.ts getPaths()
+// reads in the same process — SETTINGS_FILE, else the workspace found by
+// walking up from the cwd (8 levels) — and, where getPaths() would find none
+// (a project directory outside every checkout), the CLI's own checkout's, so
+// a policy there is never missed.
+
+const DIR = mkdtempSync(path.join(os.tmpdir(), "editor-settings-file-"));
+after(() => rmSync(DIR, { recursive: true, force: true }));
+const repo = path.join(DIR, "repo");
+mkdirSync(path.join(repo, "a", "b"), { recursive: true });
+writeFileSync(path.join(repo, "pnpm-workspace.yaml"), "");
+const outside = path.join(DIR, "project");
+mkdirSync(outside, { recursive: true });
+
+test("SETTINGS_FILE wins, as in getPaths()", () => {
+ assert.equal(editorSettingsFile({ cwd: outside, env: { SETTINGS_FILE: "/x/settings.json" }, fallbackRoot: repo }), "/x/settings.json");
+});
+
+test("a cwd inside a checkout names that checkout's file, as getPaths() does", () => {
+ assert.equal(editorSettingsFile({ cwd: path.join(repo, "a", "b"), env: {}, fallbackRoot: "/elsewhere" }), path.join(repo, "settings.json"));
+});
+
+test("a cwd outside every checkout names the CLI's own checkout's file", () => {
+ assert.equal(editorSettingsFile({ cwd: outside, env: {}, fallbackRoot: repo }), path.join(repo, "settings.json"));
+});
diff --git a/umtool/lib/paths.mjs b/umtool/lib/paths.mjs
@@ -211,6 +211,29 @@ export function findCheckout(start) {
}
/**
+ * THE SETTINGS FILE THE EDITOR'S CODE READS IN THIS PROCESS, for the
+ * child-environment guard (lane network-exits, common/lib/childEnvGuard.mjs):
+ * what common/lib/paths.ts getPaths() resolves — SETTINGS_FILE, else the
+ * workspace found walking up from the cwd (8 levels) — and, where that finds
+ * none (a project directory outside every checkout), `fallbackRoot`'s (the
+ * CLI's own checkout), so a policy there is never missed.
+ * @param {{ cwd?: string, env?: Record<string, string | undefined>, fallbackRoot?: string }} [o]
+ */
+export function editorSettingsFile({ cwd = process.cwd(), env = process.env, fallbackRoot = REPO_ROOT } = {}) {
+ if (env.SETTINGS_FILE) return env.SETTINGS_FILE;
+ let dir = path.resolve(/* turbopackIgnore: true */ cwd);
+ for (let i = 0; i < 8; i++) {
+ if (existsSync(path.join(/* turbopackIgnore: true */ dir, "pnpm-workspace.yaml"))) {
+ return path.join(/* turbopackIgnore: true */ dir, "settings.json");
+ }
+ const up = path.dirname(/* turbopackIgnore: true */ dir);
+ if (up === dir) break;
+ dir = up;
+ }
+ return path.join(/* turbopackIgnore: true */ fallbackRoot, "settings.json");
+}
+
+/**
* The checkout THIS MODULE is in -- `<repo>/umtool/lib/paths.mjs` -- or null
* (a bundle, where import.meta.url is not the file on disk: the Next server's
* cwd walk answers there).