Archilyzer · Source

archilyzer

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

commit 8ef019cc2020d081a10b13bd42dd423ee3a8d0e4
parent a184fb60607a11f50df31af15d78c4c1144a6689
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 17:42:36 -0500

network exits, review 2: no child inherits a credential or (under a policy) a proxy, an all-disabled policy fails, yt-dlp's own option rules

- lib/childEnvGuard.mjs: NETWORK_EXIT_* is moved out of process.env into a private map at boot; a hook on
  Node's own spawn (and the sync exports) drops every credential and, once any network policy exists,
  every inherited proxy variable from every child — yt-dlp, gallery-dl, ffmpeg, browsers. No policy:
  children get main's environment. Installed by the editor, umtool, the archilyzer CLI and the umtool CLI,
  and imported by every common module that spawns a networking tool; a gate test holds them to it.
- A policy whose exits are all disabled fails its listings; direct only when the policy names it.
- A pinned route is re-checked each page (an exit disabled or a login appearing stops the job); an aborted
  listing returns nothing; a rate limit is classified before the secret is scrubbed.
- requestJar resolves options against the installed yt-dlp's own parser table (lib/ytdlpOptions.ts),
  abbreviations, clusters and glued values included; --alias, --load-info-json, unknown options and URL
  userinfo pin a listing; --prox is the channel's own proxy. A test fails when yt-dlp's table changes.
- The key file must be ours, mode 600, under the config directory or ARCHILYZER_CREDENTIALS_DIR, read
  through one descriptor. Test credentials are obvious placeholders.

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

Diffstat:
MCOMMANDS.md | 2+-
MENVIRONMENT.md | 4+++-
MOPERATING.md | 31+++++++++++++++++++++----------
MSETTINGS.md | 4++--
Mcommon/bin/archilyzer.ts | 3+++
Mcommon/controller/checkAvailability.ts | 2++
Mcommon/controller/networkExits.ts | 27++++++++++++++-------------
Mcommon/controller/recordLive.ts | 2++
Acommon/lib/childEnvGuard.d.mts | 13+++++++++++++
Acommon/lib/childEnvGuard.fixture.mjs | 38++++++++++++++++++++++++++++++++++++++
Acommon/lib/childEnvGuard.gate.test.ts | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/childEnvGuard.mjs | 199+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/childEnvGuard.test.ts | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/envVars.ts | 4+++-
Mcommon/lib/networkCredentials-server.test.ts | 27+++++++++++++++++++++++----
Mcommon/lib/networkCredentials-server.ts | 71++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Mcommon/lib/networkExits.test.ts | 74+++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------
Mcommon/lib/networkExits.ts | 154++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------------
Mcommon/lib/networkProxy-server.test.ts | 16++++++++--------
Acommon/lib/ytdlpOptions.ts | 383+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/package.json | 1+
Mcommon/publish/reportExports.ts | 2++
Mcommon/social/forumSession.ts | 2++
Mcommon/social/instagramGalleryDlFetcher.ts | 2++
Mcommon/ytdlp/audioCheckedDownload.ts | 2++
Mcommon/ytdlp/metadataScan.ts | 2++
Mcommon/ytdlp/networkExitListing.test.ts | 81++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mcommon/ytdlp/networkExitRealYtdlp.test.ts | 12++++++------
Mcommon/ytdlp/runOneYtdlp.ts | 2++
Mcommon/ytdlp/runYtdlp.ts | 97++++++++++++++++++++++++++++++++++++++++++++++++-------------------------------
Meditor/CHANGELOG.md | 3+++
Meditor/app/api/ops/_read.ts | 5++++-
Meditor/app/settings/networkSave.test.ts | 18+++++++++---------
Meditor/instrumentation.ts | 11+++++++++++
Mscripts/archilyzer-ops.mjs | 5++++-
Mumtool/bin/umtool.mjs | 3+++
Mumtool/instrumentation.ts | 11+++++++++++
37 files changed, 1277 insertions(+), 185 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -198,7 +198,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `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" — "&lt;tts engine&gt;:&lt;stock voice&gt;" (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": {"&lt;top-level key&gt;": 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": "&lt;id&gt;"} (also out of every policy), {"exits": \[...\]} (the whole list, stored form {id, label, scheme, host, port, credentials, enabled}), {"platforms": {"&lt;platform&gt;": {"exits": \[ids, "direct" allowed\], "mode": "sticky"} \| null}}, {"jars": {...}}, {"echoUrl": "&lt;url&gt;" \| ""}, {"credentialsFile": "&lt;path&gt;"}, {"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\_&lt;ID&gt;=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. One job keeps one exit for every page. 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` | 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": "&lt;id&gt;"} (also out of every policy), {"exits": \[...\]} (the whole list, stored form {id, label, scheme, host, port, credentials, enabled}), {"platforms": {"&lt;platform&gt;": {"exits": \[ids, "direct" allowed\], "mode": "sticky"} \| null}}, {"jars": {...}}, {"echoUrl": "&lt;url&gt;" \| ""}, {"credentialsFile": "&lt;path&gt;"}, {"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\_&lt;ID&gt;=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"}. rerun-service-jobs retries every job a service's cookie alert stopped, once it is OK again: {"service"} -&gt; {jobIds, skipped}. --wait follows them. | `pnpm ops recheck-service --json '{"service":"rumble"}'`<br>`pnpm ops recheck-service --json '{"service":"x"}'` | | `dismiss-service` | — | | 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 @@ -265,21 +265,28 @@ pnpm ops network --json '{"platforms":{"rumble":null}}' # back to direct 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 `user:password@` in it is refused. Put the credentials where the archive - keeps its other keys: the environment variable `NETWORK_EXIT_<ID>` (id upper-cased, `-` as `_`), else one - line `NETWORK_EXIT_<ID>=user:password` in the mode-600 file `network.credentialsFile` names (default - `~/.config/archilyzer/network-exits.env`; a file others can read is refused). Percent-encode both parts: - `my pass#1` is `my%20pass%231`. + 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*; it never switches 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`, or `--config-locations` in the - channel's args (any unambiguous abbreviation counts). A routed listing runs with `--ignore-config`, so no + `--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. @@ -291,8 +298,12 @@ pnpm ops network --json '{"platforms":{"rumble":null}}' # back to direct 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. A direct listing under a policy has every inherited - proxy variable removed. `socks5h://` has the proxy resolve the hostname; `socks5://` resolves it here. + 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. `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 diff --git a/SETTINGS.md b/SETTINGS.md @@ -310,10 +310,10 @@ NAMED NETWORK EXITS (lane network-exits): proxies a listing may leave through, a | 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, and ignored if written by hand. 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. 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. | +| `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. Never the credentials themselves — a value that is not a path is refused. A file the group or others can read is refused. | +| `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[]` diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -8,6 +8,9 @@ // 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). +import "../lib/childEnvGuard.mjs"; import type { Command } from "./_cli"; import { runCli, runIfEntryPoint } from "./_cli"; 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 @@ -30,6 +30,7 @@ import { exitPool, NetworkExitError, defaultNetworkSettings, + ownProxy, exitDisplay, isRoutable, networkSettingsProblems, @@ -180,20 +181,13 @@ 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, the channel's exit is - // `direct`, or the pool has no enabled exit. - | { kind: "direct"; why: "jar" | "assigned" | "no-enabled-exit"; jar?: string } + // 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[] }; -function hasOwnProxy(argv: readonly string[]): boolean { - for (const a of argv) { - if (a === "--") break; - if (a === "--proxy" || a.startsWith("--proxy=")) return true; - } - return false; -} // 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 @@ -229,11 +223,18 @@ export async function resolveListingRoute(args: { network = strict.network; } const pool = exitPool(network, args.platform, "listing"); - if (pool === null || hasOwnProxy(args.argv)) return { kind: "none" }; + 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 }; - if (pool.length === 0 && !(await readChannelExitRecord(args.paths, args.slug))) { - return { kind: "direct", why: "no-enabled-exit" }; + // 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" }; 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/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,38 @@ +// The fixture of childEnvGuard.test.ts, run as its own node process: the +// environment is set up the way an operator's service would carry it, the +// guard is installed, and a child is spawned every way the app spawns one. +// Prints what each child saw (proxy and credential NAMES and values) as JSON. +import { readFileSync } from "node:fs"; + +const childScript = + "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 settingsFile = process.argv[2]; +Object.assign(process.env, { + SETTINGS_FILE: settingsFile, + HTTPS_PROXY: "http://127.0.0.1:2", + no_proxy: "*", + NETWORK_EXIT_EXIT_A: "fixture-user:fixture-value", +}); +const guard = await import("./childEnvGuard.mjs"); +const cp = await import("node:child_process"); +const { execa } = await import("execa"); +const out = { parentHasCredential: "NETWORK_EXIT_EXIT_A" in process.env, captured: guard.networkExitEnvValue("NETWORK_EXIT_EXIT_A") !== undefined }; +const run = (child) => + new Promise((resolve) => { + let s = ""; + child.stdout.on("data", (d) => (s += d)); + child.on("close", () => resolve(JSON.parse(s || "{}"))); + }); +out.spawn = await run(cp.spawn(process.execPath, ["-e", childScript])); +out.execFile = await run(cp.execFile(process.execPath, ["-e", childScript])); +out.execa = JSON.parse((await execa(process.execPath, ["-e", childScript])).stdout || "{}"); +out.execaOwnEnv = JSON.parse( + (await execa(process.execPath, ["-e", childScript], { env: { ...process.env, ALL_PROXY: "http://127.0.0.1:3" } })).stdout || "{}", +); +out.routed = JSON.parse( + (await execa(process.execPath, ["-e", childScript], { env: guard.routedChildEnv(), extendEnv: false })).stdout || "{}", +); +out.spawnSync = JSON.parse(cp.spawnSync(process.execPath, ["-e", childScript]).stdout.toString() || "{}"); +out.execFileSync = JSON.parse(cp.execFileSync(process.execPath, ["-e", childScript]).toString() || "{}"); +void readFileSync; +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,89 @@ +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, []); +}); diff --git a/common/lib/childEnvGuard.mjs b/common/lib/childEnvGuard.mjs @@ -0,0 +1,199 @@ +// 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 and execa +// all reach with the final environment (`envPairs`) — and on the +// child_process sync exports (spawnSync, execSync, execFileSync). 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. +// +// 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, { ChildProcess } from "node:child_process"; +import { readFileSync, statSync } from "node:fs"; +import { syncBuiltinESMExports } from "node:module"; +import path from "node:path"; + +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, cache: { file: string, mtimeMs: number, size: number, active: boolean } | null }} */ +function state() { + const g = /** @type {any} */ (globalThis); + if (!g[STATE]) g[STATE] = { creds: new Map(), settingsFile: null, 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. The editor and the CLI set it +// from getPaths(); otherwise SETTINGS_FILE, else the workspace root's. +/** @param {string} file */ +export function setNetworkPolicySettingsFile(file) { + state().settingsFile = file; + state().cache = null; +} + +function settingsFile() { + const st = state(); + if (st.settingsFile) return st.settingsFile; + if (process.env.SETTINGS_FILE) return process.env.SETTINGS_FILE; + let dir = process.cwd(); + for (let i = 0; i < 8; i++) { + try { + statSync(path.join(dir, "pnpm-workspace.yaml")); + return path.join(dir, "settings.json"); + } catch { + const up = path.dirname(dir); + if (up === dir) break; + dir = up; + } + } + return path.join(process.cwd(), "settings.json"); +} + +// Whether a network policy exists. Absent file: no. Unreadable, not JSON: +// yes (fail safe). Re-read when the file changes. +export function networkPolicyActive() { + const file = settingsFile(); + let st; + try { + st = statSync(file); + } catch (e) { + return /** @type {NodeJS.ErrnoException} */ (e).code === "ENOENT" || /** @type {NodeJS.ErrnoException} */ (e).code === "ENOTDIR" ? false : true; + } + const s = state(); + if (s.cache && s.cache.file === file && 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 { + active = true; + } + s.cache = { file, 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); + return spawn.call(this, options); + }; + proto[MARK] = true; + // The sync API does not pass through the prototype: wrap its exports. + const cp = /** @type {any} */ (childProcess); + for (const name of ["spawnSync", "execSync", "execFileSync"]) { + const orig = cp[name]; + cp[name] = function guardedSync(/** @type {any[]} */ ...args) { + // (file, args?, options?) or (command, options?): the options object is + // the last plain object argument; give it a filtered env. + let at = args.findIndex((a, i) => i > 0 && a && typeof a === "object" && !Array.isArray(a)); + if (at < 0) { + args.push({}); + at = args.length - 1; + } + args[at] = { ...args[at], env: filterEnv(args[at].env ?? process.env) }; + return orig.apply(this, args); + }; + } + syncBuiltinESMExports(); +} + +installChildEnvGuard(); diff --git a/common/lib/childEnvGuard.test.ts b/common/lib/childEnvGuard.test.ts @@ -0,0 +1,60 @@ +import { test, after } from "node:test"; +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdtempSync, 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 +// +// REVIEW 2, findings 1 and 2: no child ever inherits a NETWORK_EXIT_* +// credential, and once ANY network policy exists no child inherits a proxy +// variable — whichever API spawns it (spawn, execFile, execa, a custom env, +// spawnSync, execFileSync). With no policy the environment is main's. The +// routed spawn keeps only its dead-proxy backstop. Each case runs in a fresh +// node process (lib/childEnvGuard.fixture.mjs). + +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(settings: string | null) { + const 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)) env[k] = v; + return JSON.parse(execFileSync(process.execPath, [path.join(HERE, "childEnvGuard.fixture.mjs"), file], { env, cwd: HERE }).toString()); +} + +const WAYS = ["spawn", "execFile", "execa", "execaOwnEnv", "spawnSync", "execFileSync"] as const; + +test("a credential is moved out of process.env at load and no child inherits it (finding 1)", () => { + const r = run(null); + assert.equal(r.parentHasCredential, false); + assert.equal(r.captured, true); + for (const w of [...WAYS, "routed"]) assert.ok(!Object.keys(r[w]).some((k) => k.startsWith("NETWORK_EXIT_")), w); +}); + +test("no policy: every child's proxy variables are main's (unchanged)", () => { + const r = run(JSON.stringify({ network: { exits: [], platforms: {} } })); + for (const w of ["spawn", "execFile", "execa", "spawnSync", "execFileSync"] as const) { + assert.deepEqual(r[w], { HTTPS_PROXY: "http://127.0.0.1:2", no_proxy: "*" }, w); + } + assert.equal(r.execaOwnEnv.ALL_PROXY, "http://127.0.0.1:3"); +}); + +test("any policy: no child inherits a proxy variable, however it is spawned (finding 2)", () => { + const policy = { network: { exits: [], platforms: { twitch: { exits: ["direct"], mode: "sticky" } } } }; + const r = run(JSON.stringify(policy)); + for (const w of WAYS) assert.deepEqual(r[w], {}, w); + // The routed spawn carries only its dead-proxy backstop. + 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("unreadable settings strip too (fail safe)", () => { + const r = run("{ not json"); + for (const w of WAYS) assert.deepEqual(r[w], {}, w); +}); 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 @@ -3,7 +3,8 @@ import assert from "node:assert/strict"; import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; -import { readExitCredentials } from "./networkCredentials-server"; +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 @@ -13,6 +14,7 @@ import { readExitCredentials } from "./networkCredentials-server"; // 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 }; @@ -37,15 +39,32 @@ test("the environment first, then the mode-600 file", () => { }); 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:secret-one\n", 0o644), env: {} }); + 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:p@ss-two\n"), env: {} }); + 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("ss-two")); + 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 @@ -1,14 +1,27 @@ -// A NETWORK EXIT'S CREDENTIALS (lane network-exits, review 1 finding 1), -// 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. A -// file the group or others can read is refused. 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. +// 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 { readFileSync, statSync } from "node:fs"; +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, @@ -22,6 +35,26 @@ export type ExitCredentialsRead = { ok: true; creds: ExitCredentials | null } | 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>> } = {}, @@ -33,24 +66,32 @@ export function readExitCredentials( 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 ?? process.env)[key]?.trim(); + const envValue = (o.env ? o.env[key] : networkExitEnvValue(key))?.trim(); if (envValue) return parsed(envValue, "the environment"); - const file = expandHome(keyFile); - let mode: number; + const refused = credentialsFileRefusal(keyFile); + if (refused) return { ok: false, reason: `${refused}; exit "${exit.id}" needs credentials.` }; + let fd: number; try { - mode = statSync(file).mode; + 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`, }; } - if (mode & 0o077) return { ok: false, reason: `${keyFile} is readable by others — chmod 600 it first; exit "${exit.id}" is off until then.` }; let text: string; try { - text = readFileSync(file, "utf8"); + 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+/, ""); diff --git a/common/lib/networkExits.test.ts b/common/lib/networkExits.test.ts @@ -18,8 +18,27 @@ import { 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"; + +// 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 @@ -70,7 +89,7 @@ test("a proxy URL with credentials is refused at save; raw special characters ge }); test("credentials in the key file: user:password, percent-encoded, unreserved only", () => { - assert.deepEqual(parseCredentials("user-one:s3cr%27et"), { username: "user-one", password: "s3cr'et", encoded: "user-one:s3cr%27et" }); + 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); @@ -82,15 +101,15 @@ test("credentials in the key file: user:password, percent-encoded, unreserved on test("the proxy URL is built from the parsed parts; the fragments are exact values", () => { const n = net(); - const creds = parseCredentials("user-one:s3cr%27et"); + const creds = parseCredentials("example-user:fake%27value"); assert.ok(!("error" in creds)); - assert.equal(proxyUrlOf(n.exits[0]!, creds), "socks5h://user-one:s3cr%27et@exit-a.example.test:1080"); + 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 ["user-one:s3cr%27et", "s3cr%27et", "s3cr'et", "s3cr\\'et", "user-one"]) assert.ok(frags.includes(f), f); - const line = "[debug] | Stdin config: ['--proxy', 'socks5h://user-one:s3cr%27et@exit-a.example.test:1080'] s3cr\\'et"; + 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("s3cr") && !red.includes("user-one"), red); + 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"); }); @@ -105,9 +124,9 @@ test("a policy for rumble or twitch listings is accepted; another platform, kind 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: "FAKE-TEST-VALUE" }); + 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("hunter2")); + 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"))); @@ -132,29 +151,50 @@ test("the pool skips disabled exits; out-of-scope is null", () => { assert.equal(exitPool(sanitizeNetwork({ ...net(), platforms: { youtube: { exits: ["exit-a"] } } }), "youtube", "listing"), null); }); -test("requestJar: cookies, tokens, headers or config files in any spelling pin the request (finding 4)", () => { - const base = ["--flat-playlist", "--skip-download", "--print", "url", "--impersonate", "chrome", "-I", "1:50", "--sleep-requests", "1"]; +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"], - [["--cookies-from-b", "firefox"], "login:--cookies-from-b"], - [["--cook", "/tmp/j"], "login:--cook"], [["--add-headers", "X-Any: 1"], "header"], [["--add-header=Referer: x"], "header"], [["--username", "u"], "login:--username"], - [["-u", "u"], "login:-u"], - [["-n"], "login:-n"], - [["-vn"], "login:-vn"], + [["--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"], - [["--config-location=/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/); @@ -164,7 +204,7 @@ test("applyNetworkRequest: a proxy URL fills the fields; credentials only as yes 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:p%40ss@h:1" } }), /credentials are not a setting/); + 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"); diff --git a/common/lib/networkExits.ts b/common/lib/networkExits.ts @@ -16,8 +16,8 @@ // - `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, and the resolver -// answers direct for it even when settings.json was edited by hand. +// 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 @@ -32,6 +32,7 @@ // mask; a child's own output is scrubbed of the exact secret values. import type { FieldDocs } from "./fieldDocs"; +import { YTDLP_OPTIONS } from "./ytdlpOptions"; export const DIRECT_EXIT = "direct"; @@ -115,10 +116,12 @@ export const NETWORK_SETTINGS_FIELD_DOCS: FieldDocs<NetworkSettings> = { "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, and ignored if written by hand. Each channel's exit is chosen once, on its first listing, by a stable " + + "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. One job keeps one exit for all its " + + "(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 " + @@ -137,8 +140,10 @@ export const NETWORK_SETTINGS_FIELD_DOCS: FieldDocs<NetworkSettings> = { 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. Never the credentials themselves — a value that is " + - "not a path is refused. A file the group or others can read is refused.", + "`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.", @@ -340,9 +345,14 @@ export function sanitizeNetwork(v: unknown): NetworkSettings { 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 { - const s = v.trim(); - return s.length > 0 && (s.includes("/") || s.startsWith("~")); + 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 { @@ -486,13 +496,14 @@ export function exitById(network: NetworkSettings | undefined, id: string): Netw return network?.exits.find((e) => e.id === id); } -// Long options that can carry a login, a token, a header or another config -// (which could carry any of those). yt-dlp accepts any unambiguous prefix of a -// long option, so an argument that is a prefix (4+ characters) of one of -// these counts too. -const LOGIN_LONG_OPTIONS = [ - "--cookies", - "--cookies-from-browser", +// THE OPTIONS THAT MAKE A REQUEST A LOGGED-IN ONE, by yt-dlp's long name +// (lib/ytdlpOptions.ts is the table they are resolved against). +const COOKIE_OPTIONS = new Set(["--cookies", "--cookies-from-browser"]); +const HEADER_OPTIONS = new Set(["--add-headers"]); +// Another config, an alias (which can expand to any option) or an info file +// (which can carry headers and cookies): anything could be in it. +const CONFIG_OPTIONS = new Set(["--config-locations", "--alias", "--load-info-json", "--batch-file"]); +const LOGIN_OPTIONS = new Set([ "--username", "--password", "--twofactor", @@ -507,45 +518,90 @@ const LOGIN_LONG_OPTIONS = [ "--client-certificate-key", "--client-certificate-password", "--extractor-args", -]; -const HEADER_LONG_OPTIONS = ["--add-header", "--add-headers"]; -const CONFIG_LONG_OPTIONS = ["--config-location", "--config-locations"]; -// Short options of the same kind (-u user, -p pass, -n netrc, -2 twofactor), -// alone or in a cluster of flags. -const LOGIN_SHORT = /^-(?!-)[A-Za-z0-9]*[unp2][A-Za-z0-9]*$/; - -function prefixOf(arg: string, options: readonly string[]): boolean { - const name = arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg; - return name.length >= 6 && options.some((o) => o.startsWith(name)); +]); +const PROXY_OPTIONS = new Set(["--proxy", "--geo-verification-proxy"]); + +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; } -// THE LOGIN A REQUEST CARRIES, read off its final argv (`--` ends options): -// the jar id, or null for a logged-out request. Conservative by design: any -// cookie, credential, token-bearing extractor argument, any extra header and -// any other config file makes the request pinned (review 1, finding 4). The -// routed listing also passes --ignore-config, so no config file the argv does -// not name is read through an exit. -export function requestJar(argv: readonly string[]): string | null { - const valueOf = (i: number, opt: string): string | undefined => { - const a = argv[i]!; - if (a === opt) return argv[i + 1]; - if (a.startsWith(`${opt}=`)) return a.slice(opt.length + 1); - return undefined; - }; +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 === "--") break; - const browser = valueOf(i, "--cookies-from-browser"); - if (browser !== undefined) return `browser:${browser}`; - const file = valueOf(i, "--cookies"); - if (file !== undefined) return `file:${file}`; - if (LOGIN_SHORT.test(a)) return `login:${a}`; - if (!a.startsWith("--")) continue; - if (prefixOf(a, CONFIG_LONG_OPTIONS)) return "config"; - if (prefixOf(a, HEADER_LONG_OPTIONS)) return "header"; - if (prefixOf(a, LOGIN_LONG_OPTIONS)) return `login:${a.includes("=") ? a.slice(0, a.indexOf("=")) : a}`; + 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 null; + 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 ?? ""}`; + if (COOKIE_OPTIONS.has(o.long)) return `login:${o.long}`; + if (HEADER_OPTIONS.has(o.long)) return "header"; + if (CONFIG_OPTIONS.has(o.long)) return "config"; + if (LOGIN_OPTIONS.has(o.long)) return `login:${o.long}`; + } + 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 && PROXY_OPTIONS.has(o.long)); } // A JAR NEVER USES TWO EXITS: changing a jar's exit while the jar is fresh diff --git a/common/lib/networkProxy-server.test.ts b/common/lib/networkProxy-server.test.ts @@ -26,15 +26,15 @@ 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: "user-one", password: "pa:ss#word", route: routeEcho }); +const socksAuth = await startFakeSocks5({ username: "example-user", password: "fake:value#1", route: routeEcho }); const socksOpen = await startFakeSocks5({ route: routeEcho }); -const httpProxy = await startFakeHttpProxy({ auth: "user-one:pw", 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://user-one:${encodeURIComponent("pa:ss#word")}@127.0.0.1:${socksAuth.port}`; +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); @@ -43,11 +43,11 @@ test("preflight: a SOCKS5 proxy that accepts the exit's login answers", async () }); test("preflight: wrong credentials and a dead proxy fail, never naming the password", async () => { - const bad = await preflightProxy(`socks5h://user-one:wrong-secret@127.0.0.1:${socksAuth.port}`); + 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("wrong-secret")); - const dead = await preflightProxy(`socks5h://u:dead-secret@127.0.0.1:${await closedPort()}`); + 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}`); @@ -69,10 +69,10 @@ test("socks5 resolves here and sends an address", async () => { }); test("an HTTP CONNECT proxy with Basic auth tunnels; a 407 is a refusal", async () => { - const ok = await getThroughProxy(`http://user-one:pw@127.0.0.1:${httpProxy.port}`, `http://echo.exit.test:${echo.port}/`); + 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://user-one:nope@127.0.0.1:${httpProxy.port}`, "echo.exit.test", echo.port); + 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/); }); 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 @@ -58,6 +58,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/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 @@ -17,6 +17,7 @@ import path from "node:path"; 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, EnumerationIncompleteError, NetworkExitError } = await import("./runYtdlp"); @@ -30,9 +31,9 @@ const { waitForQueueGap, noteQueueJobEnd, clearQueueGaps } = await import("../jo const { withRumbleDefaults } = await import("../lib/rumbleDefaults"); const { closedPort, startCountingServer, startEchoServer, startFakeSocks5 } = await import("../testing/fakeProxy"); -const SECRET = "hunter2-very-secret"; +const FAKE_CRED = "fake-not-a-credential"; const trap = await startCountingServer(); -const proxyA = await startFakeSocks5({ username: "user-a", password: SECRET, route: () => null }); +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()]); @@ -41,10 +42,10 @@ after(async () => { // 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=user-a:${SECRET}\n`); +writeFileSync(KEYS, `NETWORK_EXIT_EXIT_A=example-user-a:${FAKE_CRED}\n`); chmodSync(KEYS, 0o600); -const PROXY_A_URL = `socks5h://user-a:${SECRET}@127.0.0.1:${proxyA.port}`; +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"); @@ -64,6 +65,10 @@ 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") 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") { process.stdout.write("https://rumble.com/v1-a.html\\n"); @@ -165,7 +170,7 @@ test("through an exit: --ignore-config, the proxy on stdin only, every proxy var 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(SECRET) && !text.includes("user-a"), text); + 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"/); @@ -303,9 +308,8 @@ test("one job, one exit: the route is pinned for every page; a rest mid-walk def settings(RUMBLE_POLICY); const job = {}; await list(ON_A, {}, [], job); - // A reassignment and a policy change between two pages of the same job. + // A reassignment between two pages of the same job. await NE.assignChannelExit({ paths: getPaths(), slug: ON_A, exit: "exit-b" }); - settings({ ...RUMBLE_POLICY, platforms: { rumble: { exits: ["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"); @@ -350,8 +354,8 @@ test("the secret appears in no log, error, record, report or settings answer", a }; 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(SECRET), `${what} carries the secret`); - assert.ok(!text.includes("user-a:"), `${what} carries the userinfo`); + assert.ok(!text.includes(FAKE_CRED), `${what} carries the secret`); + assert.ok(!text.includes("example-user-a:"), `${what} carries the userinfo`); } }); @@ -431,3 +435,62 @@ test("in scope in a synthetic corpus: cookie-free Rumble channels and Twitch cha 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()); +}); diff --git a/common/ytdlp/networkExitRealYtdlp.test.ts b/common/ytdlp/networkExitRealYtdlp.test.ts @@ -46,10 +46,10 @@ const site = http.createServer((req, res) => { 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 SECRET = "real-ytdlp-secret"; +const FAKE_CRED = "fake-not-a-credential"; const proxy = await startFakeSocks5({ - username: "user-r", - password: SECRET, + 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 }); @@ -59,7 +59,7 @@ after(async () => { }); const FEED = `http://127.0.0.1:${trap.port}/feed.rss`; -const PROXY_URL = `socks5h://user-r:${SECRET}@127.0.0.1:${proxy.port}`; +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[] = []; @@ -70,7 +70,7 @@ async function routed(extra: string[], opts: { proxyUrl?: string; cwd?: string } exit: "exit-r", platform: "rumble", proxyUrl: opts.proxyUrl ?? PROXY_URL, - secrets: [SECRET, `user-r:${SECRET}`, "user-r"], + secrets: [FAKE_CRED, `example-user-r:${FAKE_CRED}`, "example-user-r"], onLog: (s) => log.push(s), signal: new AbortController().signal, }); @@ -87,7 +87,7 @@ test("the listing arrives through the proxy, not directly — urllib and curl_cf 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(SECRET) && !r.log.includes("user-r"), r.log); + assert.ok(!r.log.includes(FAKE_CRED) && !r.log.includes("example-user-r"), r.log); } }); 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 @@ -96,7 +96,9 @@ import { DIRECT_EXIT, NetworkExitError, exitDisplay, + exitPool, redactFragments, + requestJar, } from "../lib/networkExits"; import { preflightProxy } from "../lib/networkProxy-server"; import { @@ -105,6 +107,7 @@ import { exitRestUntil, listingPool, resolveListingRoute, + loadNetworkStrict, restExit, restingSentence, type ListingRoute, @@ -135,6 +138,7 @@ import { skipsAsShort, } from "../lib/skipShorts"; import "../lib/childKillGuard"; +import { envWithoutProxies, routedChildEnv } from "../lib/childEnvGuard.mjs"; export type YtdlpMode = | "store-playlist" @@ -621,6 +625,7 @@ async function enumeratePlaylistListing( if (route.kind === "none") { return { urls: 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") { @@ -628,9 +633,7 @@ async function enumeratePlaylistListing( `Network exit: direct (${ route.why === "jar" ? `this listing carries a login — ${route.jar} — and a login never leaves the home address` - : route.why === "no-enabled-exit" - ? `${platform}'s policy has no enabled exit` - : "this channel's exit" + : "this channel's exit" }).\n`, ); } else { @@ -660,6 +663,36 @@ async function enumeratePlaylistListing( return { urls: 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. @@ -672,29 +705,15 @@ function configQuote(s: string): string { return `'${s.replace(/'/g, `'"'"'`)}'`; } -// EVERY PROXY VARIABLE, any case (review 1, finding 2). 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). -const PROXY_ENV_RE = /^(?:https?|all|no|ftp|socks)_proxy$/i; -// A loopback port nothing listens on (1, tcpmux; binding it needs root): the -// proxy a routed child meets if it did not read its stdin config (finding 3). -export const DEAD_PROXY = "socks5h://127.0.0.1:1"; - -function envWithoutProxies(): Record<string, string> { - const out: Record<string, string> = {}; - for (const [k, v] of Object.entries(process.env)) if (v !== undefined && !PROXY_ENV_RE.test(k)) out[k] = v; - return out; -} - -export function routedEnv(): Record<string, string> { - const env = envWithoutProxies(); - for (const k of ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"]) { - env[k] = DEAD_PROXY; - env[k.toLowerCase()] = DEAD_PROXY; - } - return env; -} +// 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, @@ -736,7 +755,7 @@ async function spawnThroughExit(o: { secrets: readonly string[]; onLog: (s: string) => void; signal: AbortSignal; -}): Promise<{ urls: string[]; exitCode: number | undefined; stderr: string; confirmed: boolean }> { +}): 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, { @@ -746,7 +765,7 @@ async function spawnThroughExit(o: { buffer: true, reject: false, input: `--proxy ${configQuote(o.proxyUrl)}\n`, - env: routedEnv(), + env: routedChildEnv(), extendEnv: false, }); const log = routedStderr(o.onLog, o.secrets); @@ -755,18 +774,18 @@ async function spawnThroughExit(o: { log.flush(); const raw = String(result.stderr ?? ""); const confirmed = raw.split("\n").some((l) => l.trim() === `[debug] Proxy map: {'all': '${o.proxyUrl}'}`); - const stderr = redactFragments( - raw - .split("\n") - .filter((l) => !l.startsWith("[debug]")) - .join("\n"), - o.secrets, - ); + // 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, confirmed }; + return { urls, exitCode: result.exitCode, stderr, unscrubbed, confirmed }; } function discardedError(platform: string, exit: string): NetworkExitError { @@ -820,9 +839,11 @@ async function spawnListing( onLog: opts.onLog, signal: opts.signal, }); - if (opts.signal.aborted) return r.urls; + // An aborted listing is not a listing, and nothing unconfirmed is kept + // (review 2 nit 5). + if (opts.signal.aborted) return []; if (r.exitCode !== 0 && r.exitCode !== 101) { - await listingFailedVia(opts, via, r.exitCode, r.stderr, r.urls.length); + await listingFailedVia(opts, via, r.exitCode, r.unscrubbed, r.urls.length); } if (!r.confirmed) throw discardedError(via.platform, via.exit); opts.onLog(`yt-dlp confirmed the listing's proxy is exit "${via.exit}".\n`); diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -17,6 +17,9 @@ - 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. - `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. - **umtool: name a channel once for a whole cut.** 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/settings/networkSave.test.ts b/editor/app/settings/networkSave.test.ts @@ -27,7 +27,7 @@ const { settingsPatchProblem, OWNED_KEYS } = await import("../api/ops/settings/p after(() => rm(ROOT, { recursive: true, force: true })); -const SECRET = "pw-not-for-logs"; +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 } }); @@ -40,19 +40,19 @@ test("an exit and a rumble listing policy save; credentials are a yes/no", async 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://user-one:${SECRET}@exit-c.example.test:1080`, - `socks5h://user-one:p@ss'${SECRET}@exit-c.example.test:1080`, - `socks5h://user-one:"${SECRET} x@exit-c.example.test:1080`, + `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(SECRET)); + assert.ok(!e.message.includes(FAKE_CRED)); return true; }); } assert.equal(readFileSync(process.env.SETTINGS_FILE!, "utf8"), before, "nothing written"); - assert.ok(!before.includes(SECRET)); + 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 () => { @@ -62,7 +62,7 @@ test("out-of-scope platforms and kinds, and jar assignments, are refused whole w [{ 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-secret" }, /credentialsFile: the PATH of the mode-600 file/], + [{ 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); @@ -83,8 +83,8 @@ test("the settings writer's floor refuses a raw out-of-scope network block too", 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" }); - assert.deepEqual(red, { url: "https://example.org?mail=a@b.example", repo: "ssh://git@host.example/repo", token: "<redacted>" }); + 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 () => { diff --git a/editor/instrumentation.ts b/editor/instrumentation.ts @@ -19,6 +19,17 @@ 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, review 2): 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) { + console.error(`editor: the child environment guard failed to install: ${e instanceof Error ? e.message : String(e)}`); + } // 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/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1764,7 +1764,10 @@ export function usage() { ' 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. One job keeps one exit for every page. A listing that carries a', + ' 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', diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -148,6 +148,9 @@ // 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). +import "../../common/lib/childEnvGuard.mjs"; import { PROJECT_KINDS, REPORTS_ROOT, diff --git a/umtool/instrumentation.ts b/umtool/instrumentation.ts @@ -13,6 +13,17 @@ 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, review 2): 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) { + console.error(`umtool: the child environment guard failed to install: ${e instanceof Error ? e.message : String(e)}`); + } // 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.