commit a184fb60607a11f50df31af15d78c4c1144a6689
parent 71a92b39f8d21ffb73a7d0db193d5f3d93db5411
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 21 Nov 2026 16:01:43 -0500
network exits, review 1: credentials out of settings, fail closed everywhere, one exit per job, the real yt-dlp proven through the proxy
- Credentials are never a setting: an exit is {id, label, scheme, host, port, credentials, enabled};
the user and password come from NETWORK_EXIT_<ID> or the mode-600 network.credentialsFile (the
archive.org key-file convention). A proxy URL with userinfo is refused at save, with how to
percent-encode. Nothing is masked by pattern any more; redactSecrets is key-based again.
- Routed listings run with --ignore-config, the proxy on stdin, -v, and every proxy variable pointed at
a dead loopback port; the result is kept only when yt-dlp's own Proxy map names the exit's proxy.
A direct listing under a policy has every inherited proxy variable removed (an inherited NO_PROXY=*
sent an impersonated listing direct: reproduced with the real yt-dlp).
- Cookies, headers, logins, extractor args and config files in any spelling keep a listing direct.
- Unreadable settings, an invalid network block, missing credentials, or a recorded exit that is no
longer enabled fail the listing; only network-exit reassigns.
- One route per job, kept for every page; a rest mid-walk defers.
- The startup probe only connects (no greeting, no echo) and can be turned off.
- Tests against the real yt-dlp on PATH with an in-process SOCKS5 proxy and a loopback RSS site.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
22 files changed, 1520 insertions(+), 693 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" — "<tts engine>:<stock voice>" (orpheus:zac, orpheus:leah, kokoro:am\_michael, ...; settings.voice.convert.target); a file, a path or a recording is REFUSED as a target (no real person's voice) — and "engine" (openvoice \| seed-vc, each installed by `archilyzer voice setup --engine <id>`). "pitch" is where the result's pitch comes from (settings.voice.convert.pitch): "target" — the stock voice's own, the read's intonation flattened to it; "source" — the pitch the take was read at (raise your voice and it rises); "contour" — the read's rises and falls, moved as a whole to the stock voice's register. "semitones" (-12 to 12) then moves a followed pitch; left out, a followed pitch takes settings.voice.convert.semitones (0 unless set). source and contour are seed-vc's, on its optional f0 model (`archilyzer voice setup --engine seed-vc --with f0`; slower, 44.1 kHz); openvoice refuses them. The target's reference is synthesized once through the tts op and kept. The result adds target, voice, pitch (semitones and f0 — the medians heard and the move applied — when followed), synthetic: true and the disclosure line. | |
| `settings` | settings patches settings.json through the editor's one writer: {"patch": {"<top-level key>": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage, 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"?, "enabled"?}}, {"removeExit": "<id>"} (also out of every policy), {"exits": \[...\]} (the whole list), {"platforms": {"<platform>": {"exits": \[ids, "direct" allowed\], "mode": "sticky"} \| null}}, {"jars": {...}}, {"echoUrl": "<url>" \| ""}. Proxy URLs: socks5h://, socks5://, http://, https:// with a port; credentials are secrets, answered as <redacted>@, and a masked proxy sent back keeps the stored one. 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 once; a listing that carries a login goes direct; a 429 or bot check rests that exit (its channels wait); a proxy that does not answer fails the listing naming the exit, never falling back to direct. Not a disguise: no fingerprint or user-agent changes, and a login never moves. get network \[--probe\] reports each exit, the rests and the 1- and 7-day counts; --probe asks each proxy to answer (and fetches network.echoUrl through it only when set). | `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"}}}'` |
+| `network` | network writes the named network exits (settings.network) through their one writer, as /settings → Network exits: {"upsertExit": {"id", "label"?, "proxy"?: "socks5h://host:port", "credentials"?: true\|false, "enabled"?}}, {"removeExit": "<id>"} (also out of every policy), {"exits": \[...\]} (the whole list, stored form {id, label, scheme, host, port, credentials, enabled}), {"platforms": {"<platform>": {"exits": \[ids, "direct" allowed\], "mode": "sticky"} \| null}}, {"jars": {...}}, {"echoUrl": "<url>" \| ""}, {"credentialsFile": "<path>"}, {"startupProbe": true\|false}. CREDENTIALS ARE NEVER A SETTING: a proxy URL with user:password in it is refused; give the exit "credentials": true and put NETWORK\_EXIT\_<ID>=user:password (percent-encoded) in the mode-600 file network.credentialsFile names (default ~/.config/archilyzer/network-exits.env), or in the environment. THE TRIAL routes only rumble and twitch LISTINGS: any other platform or request kind, and any cookie jar given an exit, is refused whole, every problem named. A channel's exit is a stable hash of its slug over the enabled exits, recorded on its first listing; a recorded exit that is disabled or removed FAILS that channel's listings until network-exit moves it. 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-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"} -> {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/OPERATING.md b/OPERATING.md
@@ -241,12 +241,12 @@ pnpm ops dismiss-service --json '{"service":"rumble"}'
# two exits (worked example: Mullvad — while this machine is connected to the VPN, each WireGuard relay
# offers a SOCKS5 proxy on port 1080 at its own hostname, resolvable only inside the tunnel)
pnpm ops network --json '{"upsertExit":{"id":"nl-ams-1","proxy":"socks5h://nl-ams-wg-socks5-001.relays.mullvad.net:1080"}}'
-pnpm ops network --json '{"upsertExit":{"id":"se-sto-1","proxy":"socks5h://se-sto-wg-socks5-001.relays.mullvad.net:1080"}}'
+pnpm ops network --json '{"upsertExit":{"id":"relay-2","proxy":"socks5h://<another relay hostname>:1080"}}'
# spread rumble's listings over them, direct kept in the pool as the comparison
-pnpm ops network --json '{"platforms":{"rumble":{"exits":["direct","nl-ams-1","se-sto-1"],"mode":"sticky"}}}'
+pnpm ops network --json '{"platforms":{"rumble":{"exits":["direct","nl-ams-1","relay-2"],"mode":"sticky"}}}'
pnpm ops get network --probe # each proxy answers? (+ the address, with echoUrl set)
-pnpm ops get network # rests and the 1/7-day counts per platform and exit
-pnpm ops network-exit --json '{"slug":"demo-rumble","exit":"se-sto-1"}' # move one channel by hand
+pnpm ops get network # rests, channels per exit, 1/7-day counts
+pnpm ops network-exit --json '{"slug":"demo-rumble","exit":"relay-2"}' # move one channel by hand
pnpm ops network --json '{"platforms":{"rumble":null}}' # back to direct
```
@@ -257,23 +257,48 @@ pnpm ops network --json '{"platforms":{"rumble":null}}' # back to direct
- **The trial routes only the LISTING (flat-playlist) requests of rumble and twitch.** Downloads,
metadata, subtitles, clips, live recordings and every other platform go direct; a policy for anything
else, or a cookie jar given an exit, is refused when saved (`TRIAL_SCOPE`, `common/lib/networkExits.ts`).
+- **Rumble channels with the browser clearance cookie stay direct.** A new Rumble channel is made with
+ Firefox's cookies and `cookieMode` "always" (`common/lib/rumbleDefaults.ts`), so its listing carries the
+ Cloudflare clearance — a login, bound to the address it was earned from. On Rumble the trial covers only
+ channels whose listing carries no cookies (`cookieMode` "when-required" or no `cookiesFromBrowser`). In a
+ synthetic example of five Rumble channels (three made with the defaults), two Twitch channels (one with
+ cookies "always") and one YouTube channel, three can be routed: the two cookie-free Rumble channels and
+ the cookie-free Twitch channel (`listingRoutable`, tested in `ytdlp/networkExitListing.test.ts`).
+- **Credentials are never a setting.** An exit is stored as scheme, host, port and `credentials`
+ true/false. A proxy URL with `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`.
- **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`. It moves only when that exit is removed
- or disabled, or by `network-exit` — never per request, never on a failure.
-- **A listing that carries a login goes direct** — cookies (`cookieMode` "always" with `cookiesFromBrowser`,
- a cookie file, a Cookie header) or an account. A Rumble channel with its Firefox clearance jar therefore
- stays direct: a clearance is bound to the address it was earned from.
+ 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.
+- **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.
+- **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
+ user, system or channel-directory yt-dlp config rides through an exit.
- **Pacing is unchanged**: the queue gap, the pace, the cooldown and the hold count every exit together —
more exits never means more requests per hour.
- **A 429 or bot check through an exit rests that exit** for the platform, on the platform cooldown's curve;
- the channels on it wait (their sync ends *deferred* until the rest ends) and never hop. When every exit of
- the platform rests, the platform cools down as before. A clean listing through the exit ends its rest.
-- **Fail closed**: a proxy that does not answer, refuses, or cannot log in fails the listing with
- `network exit "<id>" (…) did not answer: … — a listing never falls back to direct`. `socks5h://` has the
- proxy resolve the hostname; `socks5://` resolves it here.
-- **Secrets**: credentials in a proxy URL (`socks5h://user:pass@host:port`) are never logged or recorded;
- every answer shows `<redacted>@`, and the URL reaches yt-dlp on its stdin, not its command line. Records
- store the exit id only (the roster's `lastSweep.exit`, the counts in `transcripts/.network/`).
+ the channels on it wait (their sync ends *deferred* until the rest ends) and never hop. When every exit
+ rests after a 429, the platform cools down as before. A clean listing through the exit ends its rest.
+- **Fail closed**: a proxy that does not answer, refuses, or cannot log in; a settings.json that cannot be
+ read or a network block that does not validate; missing credentials; or a yt-dlp output whose `Proxy map`
+ does not name the exit's proxy — each fails the listing with a sentence naming the exit, and the result
+ is discarded. The routed child gets its proxy on stdin and an environment whose proxy variables all point
+ at a dead loopback port (`NO_PROXY` removed: libcurl applies it even to an explicit proxy), so a child
+ that ignored stdin fails instead of listing direct. A direct listing under a policy has every inherited
+ proxy variable removed. `socks5h://` has the proxy resolve the hostname; `socks5://` resolves it here.
+ With the VPN down, every preflight asks the home resolver for the relay's name.
+- **Probes**: the startup probe (a minute after boot, when an exit is enabled) only connects to each proxy —
+ no greeting, no destination, no echo; `{"startupProbe": false}` turns it off. The echo URL is fetched only
+ by the operator's `get network --probe`.
+- **Records** store the exit id only (the roster's `lastSweep.exit`, the counts in `transcripts/.network/`).
+ Neither those nor `network-exit.json` are copied into a published site.
- **Live recordings** (not built): a recording would take its channel's exit once at its start and keep it
for every part and reconnect; a dead proxy would end it failed, never continue direct.
- /settings → **Network exits** has every control above.
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -309,10 +309,12 @@ 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, proxy, 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 by a stable hash of its slug over the platform's enabled exits and recorded in `channels/<slug>/network-exit.json`; it changes only when that exit is removed or disabled, or by `pnpm ops network-exit`. 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 the platform cools down as before. A proxy that does not answer fails the listing 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:<name>`). A request that carries a login is pinned: this exit, else direct — 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 (a Rumble channel listing with its Firefox clearance jar stays direct). |
-| `echoUrl` | `""` | An address-echo URL (`http(s)://…`, answering the caller's public address as text) that `pnpm ops get network --probe` fetches through each exit to show the address it presents. Blank (the default) = the probe only checks that each proxy answers, and nothing else is requested. |
+| `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. |
+| `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. |
+| `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[]`
@@ -320,10 +322,13 @@ Per entry — each entry spells its own values.
| Key | Description |
|---|---|
-| `id` | The exit's name in policies, records and `pnpm ops`: lowercase letters, digits and `-`, up to 40, not `direct`. Records store this, never the proxy URL. |
+| `id` | The exit's name in policies, records and `pnpm ops`: lowercase letters, digits and `-`, up to 40, not `direct`. Records store this, never the proxy. |
| `label` | A display name (defaults to the id). |
-| `proxy` | The proxy URL with its port: `socks5h://host:port` (the hostname is resolved by the proxy), `socks5://host:port` (resolved here), `http://host:port` or `https://host:port`. Credentials (`socks5h://user:pass@host:port`) are a SECRET: never logged, never in an argv echo, a record or an ops answer — shown as `<redacted>@`. The URL reaches yt-dlp on its stdin, not its command line. |
-| `enabled` | Off = the exit is out of every pool; channels recorded on it are re-chosen over the remaining exits on their next listing. |
+| `scheme` | `socks5h` (the hostname is resolved by the proxy), `socks5` (resolved here), `http` or `https`. `pnpm ops network` also takes the whole as `proxy: "socks5h://host:port"`. |
+| `host` | The proxy's hostname or IP address (letters, digits, `.`, `-`; an IPv6 address in brackets). |
+| `port` | The proxy's port, 1–65535. |
+| `credentials` | Whether the proxy needs a user and password. They are read from `network.credentialsFile` (or its environment variable), never from settings.json; an exit that needs them and has none fails its listings. |
+| `enabled` | Off = the exit is out of every pool; a channel already recorded on it fails its listings until `pnpm ops network-exit` moves it. |
#### `network.platforms.<platform>`
@@ -342,7 +347,9 @@ Default:
"exits": [],
"platforms": {},
"jars": {},
- "echoUrl": ""
+ "echoUrl": "",
+ "credentialsFile": "~/.config/archilyzer/network-exits.env",
+ "startupProbe": true
}
```
diff --git a/common/controller/networkExits.ts b/common/controller/networkExits.ts
@@ -13,8 +13,13 @@
// None of them ever holds a proxy URL — only exit ids.
import path from "node:path";
-import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../lib/jsonFile-server";
-import type { Paths } from "../lib/paths";
+import { readdir } from "node:fs/promises";
+import { readJsonFile, readJsonFileSync, withJsonFileLock, writeJsonAtomic } from "../lib/jsonFile-server";
+import { getPaths, type Paths } from "../lib/paths";
+import type { ChannelConfig } from "../lib/channelConfig";
+import { alwaysCookies, cookieArgs, resolveCookiePolicy, type CookieMode } from "../lib/cookiePolicy";
+import { platformArgs } from "../ytdlp/platformArgs.mjs";
+import { readExitCredentials } from "../lib/networkCredentials-server";
import { getSettings } from "../lib/settings";
import { detectPlatform } from "../lib/platform";
import {
@@ -23,9 +28,15 @@ import {
TRIAL_SCOPE_SENTENCE,
exitById,
exitPool,
+ NetworkExitError,
+ defaultNetworkSettings,
+ exitDisplay,
isRoutable,
- maskProxyUrl,
+ networkSettingsProblems,
+ proxyUrlOf,
requestJar,
+ sanitizeNetwork,
+ secretFragmentsOf,
stickyExitFor,
type NetworkExit,
type NetworkSettings,
@@ -100,11 +111,12 @@ export async function readChannelExitRecord(
};
}
-// The record is honoured while its exit is in the platform's pool (or is the
-// operator's `direct`). Otherwise — the first listing, the exit removed or
-// disabled, the channel moved platform — the hash chooses over the pool and
-// the choice is written. NOTHING ELSE moves a channel: no failure path calls
-// this with a smaller pool.
+// THE FIRST LISTING CHOOSES; NOTHING ELSE DOES (review 1, finding 5). With
+// no record for this platform the hash chooses over the pool and the choice
+// is written. A record is honoured while its exit is in the pool (or is the
+// operator's `direct`); a recorded exit that is disabled or removed FAILS the
+// listing — it is never re-chosen and never sent direct. Only
+// assignChannelExit (`pnpm ops network-exit`) moves a channel.
async function stickyChannelExit(
paths: Paths,
slug: string,
@@ -118,6 +130,12 @@ async function stickyChannelExit(
if (rec && rec.platform === platform) {
if (pool.includes(rec.exit)) return rec.exit;
if (rec.by === "operator" && rec.exit === DIRECT_EXIT) return rec.exit;
+ throw new NetworkExitError(
+ rec.exit,
+ `this channel's recorded network exit "${rec.exit}" is no longer an enabled exit of ${platform} ` +
+ `(enabled: ${pool.join(", ") || "none"}). The ${platform} listing was not sent; a channel is never moved by ` +
+ `itself — reassign it: pnpm ops network-exit --json '{"slug":"${slug}","exit":"<exit or direct>"}'.`,
+ );
}
const exit = stickyExitFor(slug, pool);
const next: ChannelExitRecord = {
@@ -125,15 +143,7 @@ async function stickyChannelExit(
exit,
by: "hash",
at: now.toISOString(),
- ...(rec
- ? {
- previous: rec.exit,
- reason:
- rec.platform !== platform
- ? `the channel moved from ${rec.platform} to ${platform}`
- : `"${rec.exit}" is no longer an enabled exit of ${platform}`,
- }
- : {}),
+ ...(rec ? { previous: rec.exit, reason: `the channel moved from ${rec.platform} to ${platform}` } : {}),
};
await writeJsonAtomic(file, next, { mkdir: true });
return exit;
@@ -141,6 +151,29 @@ async function stickyChannelExit(
}
// ---------------------------------------------------------------------------
+// THE SETTINGS, READ STRICTLY FOR A ROUTE (review 1, finding 5)
+//
+// getSettings() answers defaults for a file it cannot read, which for a route
+// would mean "no policy": direct, silently. The listing reads the file itself:
+// absent = no policy; unreadable, not JSON, or a network block the writers
+// would refuse = the listing FAILS.
+export type StrictNetwork = { ok: true; network: NetworkSettings | undefined } | { ok: false; reason: string };
+
+export function loadNetworkStrict(file: string = getPaths().settingsFile): StrictNetwork {
+ const r = readJsonFileSync(file);
+ if (!r.ok) {
+ return r.reason === "absent"
+ ? { ok: true, network: undefined }
+ : { ok: false, reason: `settings.json could not be read (${r.reason})` };
+ }
+ const raw = isObject(r.value) ? r.value.network : undefined;
+ if (raw === undefined) return { ok: true, network: undefined };
+ const problems = networkSettingsProblems(raw);
+ if (problems.length) return { ok: false, reason: `the network settings do not validate: ${problems.join("; ")}` };
+ return { ok: true, network: sanitizeNetwork(raw) };
+}
+
+// ---------------------------------------------------------------------------
// THE ROUTE OF ONE LISTING
export type ListingRoute =
@@ -150,7 +183,9 @@ export type ListingRoute =
// 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 }
- | { kind: "exit"; exit: NetworkExit };
+ // 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) {
@@ -161,7 +196,7 @@ function hasOwnProxy(argv: readonly string[]): boolean {
}
// THE JAR'S EXIT. The trial never routes a login: whatever settings.json
-// says (the writers refuse an assignment; a hand edit is ignored here), a
+// says (the writers refuse an assignment; a hand edit fails validation), a
// request carrying one goes direct. Widening this is one deliberate change.
export const JAR_ROUTING_ALLOWED = false;
export function jarExit(network: NetworkSettings | undefined, jar: string): string {
@@ -176,23 +211,57 @@ export async function resolveListingRoute(args: {
argv: readonly string[];
network?: NetworkSettings;
now?: Date;
+ env?: Readonly<Record<string, string | undefined>>;
}): Promise<ListingRoute> {
- const network = args.network ?? settingsNetwork();
+ // Only the trial's platforms can be routed; every other listing is today's
+ // without reading anything.
+ if (!isRoutable(args.platform, "listing")) return { kind: "none" };
+ let network = args.network;
+ if (!network) {
+ const strict = loadNetworkStrict(args.paths.settingsFile);
+ if (!strict.ok) {
+ throw new NetworkExitError(
+ DIRECT_EXIT,
+ `${strict.reason}; the ${args.platform} listing was not sent — a listing never goes direct because its ` +
+ `network settings could not be read.`,
+ );
+ }
+ network = strict.network;
+ }
const pool = exitPool(network, args.platform, "listing");
if (pool === null || hasOwnProxy(args.argv)) return { kind: "none" };
const jar = requestJar(args.argv);
- if (jar) {
- const pinned = jarExit(network, jar);
- const exit = pinned === DIRECT_EXIT ? undefined : exitById(network, pinned);
- return exit?.enabled ? { kind: "exit", exit } : { kind: "direct", why: "jar", jar };
+ 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" };
}
- if (pool.length === 0) return { kind: "direct", why: "no-enabled-exit" };
const id = await stickyChannelExit(args.paths, args.slug, args.platform, pool, args.now ?? new Date());
if (id === DIRECT_EXIT) return { kind: "direct", why: "assigned" };
const exit = exitById(network, id);
- // In the pool means defined and enabled; a race with a settings write
- // answers direct-by-assignment rather than an undefined proxy.
- return exit ? { kind: "exit", exit } : { kind: "direct", why: "assigned" };
+ if (!exit) throw new NetworkExitError(id, `network exit "${id}" is not defined; the ${args.platform} listing was not sent.`);
+ const creds = readExitCredentials(exit, { file: network!.credentialsFile, ...(args.env ? { env: args.env } : {}) });
+ if (!creds.ok) {
+ throw new NetworkExitError(id, `${creds.reason} The ${args.platform} listing was not sent — it never falls back to direct.`);
+ }
+ return { kind: "exit", exit, proxyUrl: proxyUrlOf(exit, creds.creds), secrets: secretFragmentsOf(creds.creds) };
+}
+
+// WHETHER A CHANNEL'S LISTING CAN LEAVE THROUGH AN EXIT AT ALL: on a trial
+// platform and carrying no login (its cookies by the resolved policy, its own
+// args). A Rumble channel made with the defaults carries the Firefox
+// clearance cookie, so it cannot. `global` is settings' cookie pair.
+export function listingRoutable(
+ config: ChannelConfig,
+ global: { cookiesFromBrowser?: string; cookieMode?: CookieMode },
+): boolean {
+ const platform = detectPlatform(config.url) ?? "unknown";
+ if (!isRoutable(platform, "listing")) return false;
+ const argv = [
+ ...cookieArgs(alwaysCookies(resolveCookiePolicy(global, config))),
+ ...platformArgs(detectPlatform(config.url)),
+ ...(config.ytdlpExtraArgs ?? []),
+ ];
+ return requestJar(argv) === null;
}
// ---------------------------------------------------------------------------
@@ -458,37 +527,53 @@ async function readProbe(paths: Paths): Promise<ProbeFile | null> {
return r.value as unknown as ProbeFile;
}
-// EACH ENABLED EXIT'S PROXY is asked to answer (the preflight a listing
-// makes: a TCP or TLS connect and, for SOCKS, the greeting and login — no
-// destination). Only when `echoUrl` is set is that URL fetched, through each
-// exit and once direct, to name the address each presents. Nothing else.
+// EACH ENABLED EXIT'S PROXY is asked to answer. Two depths (review 1,
+// finding 6):
+// - the startup probe (`explicit` false): a TCP (or TLS) connect only — no
+// greeting, no login, no destination, no echo;
+// - the operator's `get network --probe` (`explicit` true): the preflight a
+// listing makes (connect, SOCKS greeting and login) and, only when
+// `echoUrl` is set, that URL fetched through each exit and once direct to
+// name the address each presents.
export async function probeNetworkExits(
paths: Paths,
network: NetworkSettings | undefined = settingsNetwork(),
now: Date = new Date(),
deps: {
+ explicit?: boolean;
preflight?: typeof preflightProxy;
get?: typeof getThroughProxy;
getDirect?: (url: string) => Promise<{ ok: true; body: string } | { ok: false; reason: string }>;
+ env?: Readonly<Record<string, string | undefined>>;
} = {},
): Promise<ProbeFile> {
const preflight = deps.preflight ?? preflightProxy;
const get = deps.get ?? getThroughProxy;
+ const explicit = deps.explicit === true;
const out: ProbeFile = { at: now.toISOString(), exits: {} };
for (const e of network?.exits ?? []) {
if (!e.enabled) continue;
- const pf = await preflight(e.proxy);
+ let url = proxyUrlOf(e, null);
+ if (explicit) {
+ const creds = readExitCredentials(e, { file: network!.credentialsFile, ...(deps.env ? { env: deps.env } : {}) });
+ if (!creds.ok) {
+ out.exits[e.id] = { at: now.toISOString(), reachable: false, reason: creds.reason };
+ continue;
+ }
+ url = proxyUrlOf(e, creds.creds);
+ }
+ const pf = await preflight(url, undefined, { connectOnly: !explicit });
const probe: ExitProbe = { at: now.toISOString(), reachable: pf.ok };
if (pf.ok) probe.ms = pf.ms;
else probe.reason = pf.reason;
- if (pf.ok && network?.echoUrl) {
- const r = await get(e.proxy, network.echoUrl);
+ if (explicit && pf.ok && network?.echoUrl) {
+ const r = await get(url, network.echoUrl);
if (r.ok) probe.address = addressInEcho(r.body);
else probe.echoError = r.reason;
}
out.exits[e.id] = probe;
}
- if (network?.echoUrl && deps.getDirect) {
+ if (explicit && network?.echoUrl && deps.getDirect) {
const r = await deps.getDirect(network.echoUrl);
out.exits[DIRECT_EXIT] = {
at: now.toISOString(),
@@ -503,25 +588,67 @@ export async function probeNetworkExits(
export type NetworkReportView = {
limits: string;
trialScope: { platforms: typeof TRIAL_SCOPE; sentence: string };
- exits: Array<{ id: string; label: string; proxy: string | null; enabled: boolean; probe: ExitProbe | null }>;
+ // Built from the stored form: there is no secret in it to mask.
+ exits: Array<{
+ id: string;
+ label: string;
+ display: string;
+ scheme: string | null;
+ host: string | null;
+ port: number | null;
+ credentials: boolean;
+ enabled: boolean;
+ probe: ExitProbe | null;
+ channels: number;
+ }>;
platforms: Record<
string,
NetworkSettings["platforms"][string] & { pool?: string[]; allRest?: boolean; ignored?: string }
>;
jars: Record<string, string>;
echoUrl: string;
+ credentialsFile: string;
+ startupProbe: boolean;
+ settingsProblem: string | null;
rests: Array<{ platform: string; exit: string; until: string; fails: number }>;
usage: { "1d": Record<string, NetworkUsageCounts>; "7d": Record<string, NetworkUsageCounts> };
lastProbeAt: string | null;
};
+// How many channels are recorded on each exit (a disabled exit's channels
+// fail their listings until reassigned — the report says how many).
+async function channelsByExit(paths: Paths): Promise<Record<string, number>> {
+ const out: Record<string, number> = {};
+ let slugs: string[] = [];
+ try {
+ slugs = await readdir(paths.channelsDir);
+ } catch {
+ return out;
+ }
+ for (const slug of slugs) {
+ const rec = await readChannelExitRecord(paths, slug);
+ if (rec) out[rec.exit] = (out[rec.exit] ?? 0) + 1;
+ }
+ return out;
+}
+
export async function networkReport(
paths: Paths,
- network: NetworkSettings | undefined = settingsNetwork(),
+ network?: NetworkSettings,
now: number = Date.now(),
): Promise<NetworkReportView> {
+ let settingsProblem: string | null = null;
+ if (!network) {
+ const strict = loadNetworkStrict(paths.settingsFile);
+ if (strict.ok) network = strict.network;
+ else {
+ settingsProblem = strict.reason;
+ network = settingsNetwork();
+ }
+ }
const rests = await readRests(paths);
const probe = await readProbe(paths);
+ const counts = await channelsByExit(paths);
const platforms: NetworkReportView["platforms"] = {};
for (const [platform, policy] of Object.entries(network?.platforms ?? {})) {
const pool = exitPool(network, platform, "listing");
@@ -532,22 +659,42 @@ export async function networkReport(
: { pool, allRest: await allExitsRest(paths, platform, pool, now) }),
};
}
+ const d = defaultNetworkSettings();
return {
limits: NETWORK_LIMITS_SENTENCE,
trialScope: { platforms: TRIAL_SCOPE, sentence: TRIAL_SCOPE_SENTENCE },
exits: [
- { id: DIRECT_EXIT, label: "Direct (no proxy)", proxy: null, enabled: true, probe: probe?.exits[DIRECT_EXIT] ?? null },
+ {
+ id: DIRECT_EXIT,
+ label: "Direct (no proxy)",
+ display: "no proxy",
+ scheme: null,
+ host: null,
+ port: null,
+ credentials: false,
+ enabled: true,
+ probe: probe?.exits[DIRECT_EXIT] ?? null,
+ channels: counts[DIRECT_EXIT] ?? 0,
+ },
...(network?.exits ?? []).map((e) => ({
id: e.id,
label: e.label,
- proxy: maskProxyUrl(e.proxy),
+ display: exitDisplay(e),
+ scheme: e.scheme,
+ host: e.host,
+ port: e.port,
+ credentials: e.credentials,
enabled: e.enabled,
probe: probe?.exits[e.id] ?? null,
+ channels: counts[e.id] ?? 0,
})),
],
platforms,
jars: network?.jars ?? {},
echoUrl: network?.echoUrl ?? "",
+ credentialsFile: network?.credentialsFile ?? d.credentialsFile,
+ startupProbe: network?.startupProbe ?? d.startupProbe,
+ settingsProblem,
rests: Object.entries(rests)
.filter(([, e]) => e.until > now)
.map(([k, e]) => {
@@ -560,23 +707,22 @@ export async function networkReport(
}
// THE STARTUP PROBE: once, a minute after the editor boots, when an exit is
-// enabled — each proxy asked to answer (no destination) and, only when
-// network.echoUrl is set, the echo fetched through it. One line per exit in
-// the server log; the answers land in probe.json for `get network`. Never
-// throws; armed below the idle gate (editor/instrumentation.ts).
+// enabled and `network.startupProbe` is on — a TCP connect to each proxy and
+// nothing else (no greeting, no destination, no echo). One line per exit in
+// the server log; the answers land in probe.json. Never throws; armed below
+// the idle gate (editor/instrumentation.ts).
export function startupNetworkProbe(opts: { log: (line: string) => void; delayMs?: number; paths?: Paths }): void {
const t = setTimeout(() => {
void (async () => {
try {
- const network = settingsNetwork();
- if (!network?.exits.some((e) => e.enabled)) return;
- const { getPaths } = await import("../lib/paths");
- const probe = await probeNetworkExits(opts.paths ?? getPaths(), network);
+ const paths = opts.paths ?? getPaths();
+ const strict = loadNetworkStrict(paths.settingsFile);
+ if (!strict.ok) return opts.log(`network exits: no startup probe — ${strict.reason}`);
+ const network = strict.network;
+ if (!network?.startupProbe || !network.exits.some((e) => e.enabled)) return;
+ const probe = await probeNetworkExits(paths, network, new Date(), { explicit: false });
for (const [id, p] of Object.entries(probe.exits)) {
- opts.log(
- `network exit "${id}": ${p.reachable ? "answers" : `unreachable — ${p.reason ?? "?"}`}` +
- (p.address ? `, shows ${p.address}` : p.echoError ? `, echo failed — ${p.echoError}` : ""),
- );
+ opts.log(`network exit "${id}": ${p.reachable ? "accepts a connection" : `unreachable — ${p.reason ?? "?"}`}`);
}
} catch (e) {
opts.log(`network exits: the startup probe failed — ${(e as Error).message}`);
@@ -587,7 +733,7 @@ export function startupNetworkProbe(opts: { log: (line: string) => void; delayMs
}
// What the listing needs to send a request through an exit, read once per
-// listing: the pool (for the all-rest check) and the routable kinds.
+// listing: the pool (for the all-rest check).
export function listingPool(network: NetworkSettings | undefined, platform: string): string[] | null {
return exitPool(network ?? settingsNetwork(), platform, "listing");
}
diff --git a/common/lib/networkCredentials-server.test.ts b/common/lib/networkCredentials-server.test.ts
@@ -0,0 +1,51 @@
+import { test, after } from "node:test";
+import assert from "node:assert/strict";
+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { readExitCredentials } from "./networkCredentials-server";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/networkCredentials-server.test.ts
+//
+// THE KEY-FILE CONVENTION (as archive.org's S3 keys, lib/waybackPages/
+// savePageNow-server.ts): the environment first, else a mode-600 file whose
+// PATH is a setting. Temp files only.
+
+const DIR = mkdtempSync(path.join(os.tmpdir(), "net-creds-"));
+after(() => rmSync(DIR, { recursive: true, force: true }));
+const exitA = { id: "exit-a", label: "A", scheme: "socks5h" as const, host: "a.example.test", port: 1080, credentials: true, enabled: true };
+
+function keyFile(text: string, mode = 0o600): string {
+ const f = path.join(DIR, `keys-${Math.random().toString(36).slice(2)}.env`);
+ writeFileSync(f, text);
+ chmodSync(f, mode);
+ return f;
+}
+
+test("an exit without credentials reads nothing", () => {
+ assert.deepEqual(readExitCredentials({ ...exitA, credentials: false }, { file: "/nonexistent", env: {} }), { ok: true, creds: null });
+});
+
+test("the environment first, then the mode-600 file", () => {
+ const f = keyFile("NETWORK_EXIT_EXIT_A=from-file:pw%21\n");
+ const env = readExitCredentials(exitA, { file: f, env: { NETWORK_EXIT_EXIT_A: "from-env:pw" } });
+ assert.ok(env.ok && env.creds?.username === "from-env");
+ const file = readExitCredentials(exitA, { file: f, env: {} });
+ assert.ok(file.ok);
+ assert.deepEqual(file.creds, { username: "from-file", password: "pw!", encoded: "from-file:pw%21" });
+});
+
+test("a file others can read, a missing file or line, or a raw password is refused, never echoing it", () => {
+ const open = readExitCredentials(exitA, { file: keyFile("NETWORK_EXIT_EXIT_A=u:secret-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: {} });
+ assert.equal(raw.ok, false);
+ assert.match((raw as { reason: string }).reason, /percent-encode/);
+ assert.ok(!(raw as { reason: string }).reason.includes("ss-two"));
+});
diff --git a/common/lib/networkCredentials-server.ts b/common/lib/networkCredentials-server.ts
@@ -0,0 +1,60 @@
+// 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.
+
+import { readFileSync, statSync } from "node:fs";
+import os from "node:os";
+import {
+ DEFAULT_NETWORK_CREDENTIALS_FILE,
+ credentialsEnvKey,
+ parseCredentials,
+ type ExitCredentials,
+ type NetworkExit,
+} from "./networkExits";
+
+export type ExitCredentialsRead = { ok: true; creds: ExitCredentials | null } | { ok: false; reason: string };
+
+const expandHome = (p: string) => (p === "~" || p.startsWith("~/") ? os.homedir() + p.slice(1) : p);
+const unquote = (v: string) => v.trim().replace(/^(["'])(.*)\1$/, "$2").trim();
+
+export function readExitCredentials(
+ exit: Pick<NetworkExit, "id" | "credentials">,
+ o: { file?: string; env?: Readonly<Record<string, string | undefined>> } = {},
+): ExitCredentialsRead {
+ if (!exit.credentials) return { ok: true, creds: null };
+ const key = credentialsEnvKey(exit.id);
+ const keyFile = o.file?.trim() || DEFAULT_NETWORK_CREDENTIALS_FILE;
+ const parsed = (value: string, from: string): ExitCredentialsRead => {
+ const c = parseCredentials(value);
+ return "error" in c ? { ok: false, reason: `exit "${exit.id}": ${key} in ${from}: ${c.error}` } : { ok: true, creds: c };
+ };
+ const envValue = (o.env ?? process.env)[key]?.trim();
+ if (envValue) return parsed(envValue, "the environment");
+ const file = expandHome(keyFile);
+ let mode: number;
+ try {
+ mode = statSync(file).mode;
+ } 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");
+ } catch {
+ return { ok: false, reason: `${keyFile} could not be read; exit "${exit.id}" is off.` };
+ }
+ for (const raw of text.split("\n")) {
+ const line = raw.trim().replace(/^export\s+/, "");
+ if (line.startsWith(`${key}=`)) return parsed(unquote(line.slice(key.length + 1)), keyFile);
+ }
+ return { ok: false, reason: `${keyFile} has no ${key}= line; exit "${exit.id}" needs credentials.` };
+}
diff --git a/common/lib/networkExits.test.ts b/common/lib/networkExits.test.ts
@@ -4,184 +4,174 @@ import {
DIRECT_EXIT,
NetworkRequestError,
applyNetworkRequest,
+ credentialsEnvKey,
+ exitDisplay,
exitPool,
jarExitChangeRefusal,
- maskProxyUrl,
- maskedNetwork,
networkSettingsProblems,
- parseProxyUrl,
- proxyDisplay,
- proxySecretFragments,
+ parseCredentials,
+ parseProxyInput,
+ proxyUrlOf,
redactFragments,
- redactUrlUserinfo,
requestJar,
sanitizeNetwork,
+ secretFragmentsOf,
stableHash,
stickyExitFor,
- unmaskProxy,
type NetworkSettings,
} from "./networkExits";
// Run with:
// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/networkExits.test.ts
-
-const CRED = "socks5h://user-one:s3cr%23et@proxy-a.example.test:1080";
+//
+// REVIEW 1 (finding 1): a proxy's credentials are never a setting and never
+// masked by pattern. The settings hold the exit's id, scheme, host, port and
+// whether it has credentials; the secret lives in the key file
+// (lib/networkCredentials-server.ts). Every answer is built from that form.
+
+function exit(id: string, extra: Record<string, unknown> = {}) {
+ return { id, label: id.toUpperCase(), scheme: "socks5h", host: `${id}.example.test`, port: 1080, credentials: false, enabled: true, ...extra };
+}
function net(extra: Partial<NetworkSettings> = {}): NetworkSettings {
- return {
- exits: [
- { id: "exit-a", label: "A", proxy: CRED, enabled: true },
- { id: "exit-b", label: "B", proxy: "socks5://127.0.0.1:1081", enabled: true },
- ],
- platforms: { rumble: { exits: ["exit-a", "exit-b"], mode: "sticky", kinds: ["listing"] } },
- jars: {},
- echoUrl: "",
+ return sanitizeNetwork({
+ exits: [exit("exit-a", { credentials: true }), exit("exit-b")],
+ platforms: { rumble: { exits: ["exit-a", "exit-b"], mode: "sticky" } },
...extra,
- };
+ });
}
-test("a policy for rumble or twitch listings is accepted", () => {
- assert.deepEqual(networkSettingsProblems(net()), []);
- assert.deepEqual(
- networkSettingsProblems({ ...net(), platforms: { twitch: { exits: ["direct", "exit-b"], mode: "sticky" } } }),
- [],
- );
+test("the stored form has no secret: id, scheme, host, port, credentials yes/no", () => {
+ const n = net();
+ assert.deepEqual(n.exits[0], { id: "exit-a", label: "EXIT-A", scheme: "socks5h", host: "exit-a.example.test", port: 1080, credentials: true, enabled: true });
+ assert.equal(exitDisplay(n.exits[0]!), "socks5h://exit-a.example.test:1080 (credentials)");
+ assert.equal(exitDisplay(n.exits[1]!), "socks5h://exit-b.example.test:1080");
+ assert.equal(n.credentialsFile, "~/.config/archilyzer/network-exits.env");
+ assert.equal(n.startupProbe, true);
+ assert.deepEqual(networkSettingsProblems(n), []);
});
-test("validation refuses a platform outside the trial, with the trial's sentence", () => {
- const p = networkSettingsProblems({ ...net(), platforms: { youtube: { exits: ["exit-a"], mode: "sticky" } } });
- assert.equal(p.length, 1);
- assert.match(p[0]!, /^network\.platforms\.youtube: refused — the network-exit trial routes only the listing requests of rumble and twitch/);
- // A direct-only policy elsewhere is a no-op, not a widening.
- assert.deepEqual(networkSettingsProblems({ ...net(), platforms: { youtube: { exits: ["direct"] } } }), []);
+test("a proxy URL with credentials is refused at save; raw special characters get the encoding sentence", () => {
+ for (const pw of ["pa'ss", 'pa"ss', "pa ss", "pa<ss", "p@ss", "pa\\ss", "pa%zz"]) {
+ const r = parseProxyInput(`socks5h://user:${pw}@h.example.test:1080`);
+ assert.ok("error" in r, pw);
+ assert.match(r.error, /percent-encode/, pw);
+ assert.ok(!r.error.includes(pw), `the refusal echoes ${pw}`);
+ }
+ const enc = parseProxyInput("socks5h://user:pa%27ss@h.example.test:1080");
+ assert.ok("error" in enc);
+ assert.match(enc.error, /credentials are not a setting .* NETWORK_EXIT_<ID>=user:password/);
+ assert.ok(!enc.error.includes("pa%27ss"));
+ assert.deepEqual(parseProxyInput("socks5h://h.example.test:1080"), { scheme: "socks5h", host: "h.example.test", port: 1080 });
+ assert.deepEqual(parseProxyInput("HTTP://127.0.0.1:3128"), { scheme: "http", host: "127.0.0.1", port: 3128 });
+ for (const bad of ["socks4://h:1", "socks5h://h:1/path", "socks5h://h", "socks5h://h\t:1", "socks5h://<redacted>@h:1"]) {
+ assert.ok("error" in parseProxyInput(bad), bad);
+ }
});
-test("validation refuses a request kind outside the trial", () => {
- for (const kind of ["download", "clip", "metadata"]) {
- const p = networkSettingsProblems({ ...net(), platforms: { rumble: { exits: ["exit-a"], kinds: ["listing", kind] } } });
- assert.equal(p.length, 1, kind);
- assert.match(p[0]!, new RegExp(`kinds: "${kind}" refused — the network-exit trial routes only the listing`));
+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" });
+ for (const raw of ["user:pa'ss", "user:p@ss", "user:pa ss", "user:pa\\ss", "nouser", "user:pa%zz"]) {
+ const r = parseCredentials(raw);
+ assert.ok("error" in r, raw);
+ assert.match(r.error, /percent-encode/);
+ assert.ok(!r.error.includes(raw.split(":")[1] ?? raw));
}
+ assert.equal(credentialsEnvKey("nl-ams-1"), "NETWORK_EXIT_NL_AMS_1");
});
-test("validation refuses any jar assignment in the trial, and a non-sticky mode", () => {
- const p = networkSettingsProblems({ ...net(), jars: { "browser:firefox": "exit-a" } });
- assert.equal(p.length, 1);
- assert.match(p[0]!, /network\.jars\.browser:firefox: refused — a request that carries a login .* is never moved to another address/);
- assert.deepEqual(networkSettingsProblems({ ...net(), jars: { "browser:firefox": "direct" } }), []);
- const m = networkSettingsProblems({ ...net(), platforms: { rumble: { exits: ["exit-a"], mode: "random" } } });
- assert.match(m[0]!, /mode: "sticky" is the only mode/);
+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");
+ 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[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";
+ const red = redactFragments(line, frags);
+ assert.ok(!red.includes("s3cr") && !red.includes("user-one"), red);
+ // Exact values, no pattern: text without them is untouched.
+ assert.equal(redactFragments("https://example.org?mail=a@b.example", frags), "https://example.org?mail=a@b.example");
});
-test("validation refuses an unknown exit, a redefined direct, a bad proxy — never echoing the proxy", () => {
- const p = networkSettingsProblems({
- exits: [
- { id: "direct", proxy: "socks5h://h:1" },
- { id: "x", proxy: "ftp://user:hunter2@h:1" },
- { id: "y", proxy: "socks5h://user:hunter2@h" },
- ],
- platforms: { rumble: { exits: ["nope"] } },
- });
- assert.ok(p.some((s) => /exits\[0\]\.id: "direct" is the built-in exit/.test(s)));
- assert.ok(p.some((s) => /exits\[1\]\.proxy: the proxy URL's scheme must be/.test(s)));
- assert.ok(p.some((s) => /exits\[2\]\.proxy: the proxy URL must name its port/.test(s)));
- assert.ok(p.some((s) => /platforms\.rumble\.exits: "nope" is not a defined exit/.test(s)));
- assert.ok(p.every((s) => !s.includes("hunter2")));
+test("a policy for rumble or twitch listings is accepted; another platform, kind or a jar is refused", () => {
+ assert.deepEqual(networkSettingsProblems(net({ platforms: { twitch: { exits: ["direct", "exit-b"], mode: "sticky", kinds: ["listing"] } } })), []);
+ const yt = networkSettingsProblems({ ...net(), platforms: { youtube: { exits: ["exit-a"], mode: "sticky" } } });
+ assert.match(yt[0]!, /^network\.platforms\.youtube: refused — the network-exit trial routes only the listing requests of rumble and twitch/);
+ const kind = networkSettingsProblems({ ...net(), platforms: { rumble: { exits: ["exit-a"], kinds: ["listing", "download"] } } });
+ assert.match(kind[0]!, /kinds: "download" refused/);
+ const jar = networkSettingsProblems({ ...net(), jars: { "browser:firefox": "exit-a" } });
+ assert.match(jar[0]!, /network\.jars\.browser:firefox: refused — a request that carries a login/);
+ const mode = networkSettingsProblems({ ...net(), platforms: { rumble: { exits: ["exit-a"], mode: "random" } } });
+ assert.match(mode[0]!, /mode: "sticky" is the only mode/);
+ const keyFile = networkSettingsProblems({ ...net(), credentialsFile: "FAKE-TEST-VALUE" });
+ assert.match(keyFile[0]!, /credentialsFile: the PATH of the mode-600 file/);
+ assert.ok(!keyFile[0]!.includes("hunter2"));
+ const oldShape = networkSettingsProblems({ exits: [{ id: "x", proxy: "socks5h://u:p@h:1" }] });
+ assert.ok(oldShape.some((p) => /exits\[0\]\.proxy: not an exit key/.test(p)));
+ assert.ok(oldShape.every((p) => !p.includes("u:p")));
});
test("the sticky choice is a stable hash of the slug over the pool, never random", () => {
- // FNV-1a 32: pinned, so a release cannot reshuffle every channel.
- assert.equal(stableHash("demo-rumble"), stableHash("demo-rumble"));
assert.equal(stableHash(""), 0x811c9dc5);
const pool = ["exit-a", "exit-b", "direct"];
const first = stickyExitFor("demo-rumble", pool);
for (let i = 0; i < 50; i++) assert.equal(stickyExitFor("demo-rumble", pool), first);
- // Spread: 60 slugs land on every exit of a three-exit pool.
const seen = new Set(Array.from({ length: 60 }, (_, i) => stickyExitFor(`channel-${i}`, pool)));
assert.deepEqual([...seen].sort(), [...pool].sort());
assert.equal(stickyExitFor("x", []), DIRECT_EXIT);
});
-test("the pool skips disabled exits; no policy or an out-of-scope one is null", () => {
+test("the pool skips disabled exits; out-of-scope is null", () => {
const n = net();
assert.deepEqual(exitPool(n, "rumble", "listing"), ["exit-a", "exit-b"]);
n.exits[0]!.enabled = false;
assert.deepEqual(exitPool(n, "rumble", "listing"), ["exit-b"]);
assert.equal(exitPool(n, "rumble", "download"), null);
- assert.equal(exitPool(n, "twitch", "listing"), null);
- // A hand-edited youtube policy is ignored at use time.
- const hand = sanitizeNetwork({ ...net(), platforms: { youtube: { exits: ["exit-a"] } } });
- assert.ok(hand.platforms.youtube);
- assert.equal(exitPool(hand, "youtube", "listing"), null);
+ assert.equal(exitPool(sanitizeNetwork({ ...net(), platforms: { youtube: { exits: ["exit-a"] } } }), "youtube", "listing"), null);
});
-test("requestJar: a request carrying cookies or a login is pinned; a logged-out one is not", () => {
- const base = ["--flat-playlist", "--skip-download", "--print", "url", "--impersonate", "chrome"];
+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"];
assert.equal(requestJar(base), null);
- assert.equal(requestJar([...base, "--cookies-from-browser", "firefox"]), "browser:firefox");
- assert.equal(requestJar(["--cookies=/tmp/jar.txt"]), "file:/tmp/jar.txt");
- assert.equal(requestJar(["--add-headers", "Cookie: a=b"]), "header:cookie");
- assert.equal(requestJar(["--add-header=Authorization: Bearer t"]), "header:authorization");
- assert.equal(requestJar(["--username", "u", "--password", "p"]), "login:username");
- assert.equal(requestJar(["--netrc"]), "login:netrc");
- assert.equal(requestJar(["--extractor-args", "twitch:auth-token=x"]), "login:extractor-args");
- // After `--` is the URL, not an option.
+ const pinned: Array<[string[], string]> = [
+ [["--cookies-from-browser", "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"],
+ [["--netrc-cmd", "x"], "login:--netrc-cmd"],
+ [["--config-locations", "/etc/x.conf"], "config"],
+ [["--config-location=/etc/x.conf"], "config"],
+ [["--extractor-args", "twitch:client_id=x"], "login:--extractor-args"],
+ ];
+ for (const [extra, jar] of pinned) assert.equal(requestJar([...base, ...extra]), jar, extra.join(" "));
assert.equal(requestJar(["--", "--cookies-from-browser"]), null);
});
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 })!,
- /refused — the jar is fresh .* an account seen from two addresses invites a lock/,
- );
- assert.equal(jarExitChangeRefusal({ jar: "browser:firefox", from: "direct", to: "exit-a", jarFresh: false }), null);
-});
-
-test("masking: credentials are redacted everywhere, the host stays readable", () => {
- assert.equal(maskProxyUrl(CRED), "socks5h://<redacted>@proxy-a.example.test:1080");
- assert.equal(maskProxyUrl("socks5://127.0.0.1:1081"), "socks5://127.0.0.1:1081");
- assert.equal(proxyDisplay(CRED), "socks5h://proxy-a.example.test:1080");
- assert.equal(
- redactUrlUserinfo(`error via ${CRED} and http://a:b@h:3128 done`),
- "error via socks5h://<redacted>@proxy-a.example.test:1080 and http://<redacted>@h:3128 done",
- );
- const frags = proxySecretFragments(CRED);
- assert.ok(frags.includes("s3cr#et") && frags.includes("s3cr%23et"));
- const line = "[debug] | Stdin config: ['--proxy', 'socks5h://user-one:s3cr%23et@proxy-a.example.test:1080'] pw=s3cr#et";
- const red = redactFragments(line, frags);
- assert.ok(!red.includes("s3cr"), red);
- assert.ok(!JSON.stringify(maskedNetwork(net())).includes("s3cr"));
+ assert.match(jarExitChangeRefusal({ jar: "browser:firefox", from: "direct", to: "exit-a", jarFresh: true })!, /invites a lock/);
});
-test("a masked proxy sent back keeps the stored credentials; a new one replaces them", () => {
- assert.equal(unmaskProxy(maskProxyUrl(CRED), CRED), CRED);
- assert.equal(unmaskProxy("socks5h://<redacted>@other.example.test:1080", CRED), "socks5h://<redacted>@other.example.test:1080");
- assert.equal(unmaskProxy("socks5h://new:pw@h:1", CRED), "socks5h://new:pw@h:1");
-});
-
-test("applyNetworkRequest: upsert, remove (out of every policy), platforms merge, masked round trip", () => {
+test("applyNetworkRequest: a proxy URL fills the fields; credentials only as yes/no; remove leaves policies", () => {
const cur = net();
- const back = applyNetworkRequest(cur, { exits: maskedNetwork(cur).exits });
- assert.equal((back.exits as Array<{ proxy: string }>)[0]!.proxy, CRED);
- const up = applyNetworkRequest(cur, { upsertExit: { id: "exit-a", enabled: false } });
- assert.deepEqual((up.exits as Array<{ enabled: boolean; proxy: string }>)[0], { id: "exit-a", label: "A", proxy: CRED, enabled: false });
+ 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/);
+ const off = applyNetworkRequest(cur, { upsertExit: { id: "exit-a", enabled: false } });
+ assert.equal((off.exits as Array<{ enabled: boolean; host: string }>)[0]!.enabled, false);
+ assert.equal((off.exits as Array<{ host: string }>)[0]!.host, "exit-a.example.test");
const rm = applyNetworkRequest(cur, { removeExit: "exit-a" });
assert.deepEqual((rm.platforms as Record<string, { exits: string[] }>).rumble!.exits, ["exit-b"]);
- const rm2 = applyNetworkRequest(sanitizeNetwork(rm), { removeExit: "exit-b" });
- assert.deepEqual(rm2.platforms, {});
- const pl = applyNetworkRequest(cur, { platforms: { rumble: null, twitch: { exits: ["exit-b"] } } });
- assert.deepEqual(Object.keys(pl.platforms as object), ["twitch"]);
assert.throws(() => applyNetworkRequest(cur, { bogus: 1 }), NetworkRequestError);
- assert.throws(() => applyNetworkRequest(cur, { upsertExit: { id: "new" } }), /needs its proxy URL/);
-});
-
-test("parseProxyUrl reads each scheme, credentials decoded", () => {
- const p = parseProxyUrl(CRED);
- assert.ok(!("error" in p));
- assert.deepEqual(p, { scheme: "socks5h", host: "proxy-a.example.test", port: 1080, username: "user-one", password: "s3cr#et" });
- assert.ok(!("error" in parseProxyUrl("http://127.0.0.1:3128")));
- assert.ok(!("error" in parseProxyUrl("https://[::1]:3129")));
- assert.ok("error" in parseProxyUrl("socks4://h:1"));
- assert.ok("error" in parseProxyUrl("socks5h://h:1/path"));
+ assert.throws(() => applyNetworkRequest(cur, { upsertExit: { id: "new" } }), /needs its proxy/);
+ const probeOff = applyNetworkRequest(cur, { startupProbe: false });
+ assert.equal(probeOff.startupProbe, false);
});
diff --git a/common/lib/networkExits.ts b/common/lib/networkExits.ts
@@ -2,8 +2,9 @@
// leave through, chosen per channel and kept, for the platforms and request
// kinds the operator routes. Pure and client-safe: the types, the sanitizer,
// the validator the writers refuse with, the sticky choice, the cookie-jar
-// classifier and the masking. State and the proxy client live in
-// controller/networkExits.ts and lib/networkProxy-server.ts.
+// classifier. State and the proxy client live in controller/networkExits.ts
+// and lib/networkProxy-server.ts; the credentials in
+// lib/networkCredentials-server.ts.
//
// WHAT IT IS FOR, AND WHAT IT IS NOT. It spreads logged-out listing load over
// several addresses, and lets the archive list a site that does not answer the
@@ -19,12 +20,16 @@
// answers direct for it even when settings.json was edited by hand.
// - 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: `network.jars.<jar>` or
-// direct, never the platform's pool (requestJar). The trial refuses every
-// jar assignment.
-// - A proxy URL may hold credentials. They are a secret: maskProxyUrl /
-// redactUrlUserinfo everywhere a URL could be shown, the exit id in every
-// record.
+// - A request that carries a login is pinned direct (requestJar). The trial
+// refuses every jar assignment.
+// - CREDENTIALS ARE NEVER A SETTING (review 1, finding 1). An exit is stored
+// as id, scheme, host, port and `credentials: true|false`; the user and
+// password live where the repo keeps every other secret — the environment,
+// else a mode-600 key file whose PATH is `network.credentialsFile`
+// (lib/networkCredentials-server.ts, the archive.org S3 keys' convention).
+// A proxy URL carrying credentials is refused at save. Every answer, log
+// line and record is built from the stored form, so there is nothing to
+// mask; a child's own output is scrubbed of the exact secret values.
import type { FieldDocs } from "./fieldDocs";
@@ -46,10 +51,17 @@ export type NetworkRequestKind = (typeof NETWORK_REQUEST_KINDS)[number];
export const NETWORK_POLICY_MODES = ["sticky"] as const;
export type NetworkPolicyMode = (typeof NETWORK_POLICY_MODES)[number];
+export const PROXY_SCHEMES = ["socks5h", "socks5", "http", "https"] as const;
+export type ProxyScheme = (typeof PROXY_SCHEMES)[number];
+
export type NetworkExit = {
id: string;
label: string;
- proxy: string;
+ scheme: ProxyScheme;
+ host: string;
+ port: number;
+ // Whether the proxy needs a user and password — kept in the key file.
+ credentials: boolean;
enabled: boolean;
};
@@ -64,8 +76,12 @@ export type NetworkSettings = {
platforms: Record<string, NetworkPlatformPolicy>;
jars: Record<string, string>;
echoUrl: string;
+ credentialsFile: string;
+ startupProbe: boolean;
};
+export const DEFAULT_NETWORK_CREDENTIALS_FILE = "~/.config/archilyzer/network-exits.env";
+
// THE TRIAL'S SCOPE — the one place it is widened, deliberately, later.
export const TRIAL_SCOPE: Readonly<Record<string, readonly NetworkRequestKind[]>> = Object.freeze({
rumble: Object.freeze(["listing"] as NetworkRequestKind[]),
@@ -86,50 +102,64 @@ export function isRoutable(platform: string, kind: NetworkRequestKind): boolean
export const NETWORK_SETTINGS_FIELD_DOCS: FieldDocs<NetworkSettings> = {
exits:
- "NAMED NETWORK EXITS: proxies a fetch may leave through, `[{id, label, proxy, 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 " +
+ "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 by a stable hash of its slug over " +
- "the platform's enabled exits and recorded in `channels/<slug>/network-exit.json`; it changes only when that " +
- "exit is removed or disabled, or by `pnpm ops network-exit`. 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 the platform cools down as before. A proxy " +
- "that does not answer fails the listing naming the exit — never a fallback to direct.",
+ "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.",
jars:
"A cookie jar's one fixed exit, keyed by jar id (`browser:<spec>`, `file:<path>`, `login:<option>`, " +
- "`header:<name>`). A request that carries a login is pinned: this exit, else direct — never the platform's " +
+ "`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 (a Rumble channel listing with its Firefox clearance jar stays direct).",
+ "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 `pnpm ops get " +
- "network --probe` fetches through each exit to show the address it presents. Blank (the default) = the probe " +
- "only checks that each proxy answers, and nothing else is requested.",
+ "An address-echo URL (`http(s)://…`, answering the caller's public address as text) that the operator's " +
+ "`pnpm ops get network --probe` fetches through each exit to show the address it presents. Never fetched by " +
+ "the startup probe. Blank (the default) = no echo request at all.",
+ credentialsFile:
+ "The PATH of the mode-600 file holding the exits' credentials, one line per exit with `credentials: true`: " +
+ "`NETWORK_EXIT_<ID>=user:password` (ID upper-cased, `-` as `_`; each part percent-encoded: `my pass#1` is " +
+ "`my%20pass%231`). The environment variable of the same name wins. Never the credentials themselves — a value that is " +
+ "not a path is refused. A file the group or others can read is refused.",
+ startupProbe:
+ "A minute after the editor boots, check that each enabled exit's proxy accepts a TCP connection (no SOCKS " +
+ "greeting, no destination, no echo). One line per exit in the server log. false = no connection at boot.",
};
export const NETWORK_EXIT_FIELD_DOCS: FieldDocs<NetworkExit> = {
id:
"The exit's name in policies, records and `pnpm ops`: lowercase letters, digits and `-`, up to 40, not " +
- "`direct`. Records store this, never the proxy URL.",
+ "`direct`. Records store this, never the proxy.",
label: "A display name (defaults to the id).",
- proxy:
- "The proxy URL with its port: `socks5h://host:port` (the hostname is resolved by the proxy), " +
- "`socks5://host:port` (resolved here), `http://host:port` or `https://host:port`. Credentials " +
- "(`socks5h://user:pass@host:port`) are a SECRET: never logged, never in an argv echo, a record or an ops " +
- "answer — shown as `<redacted>@`. The URL reaches yt-dlp on its stdin, not its command line.",
+ scheme:
+ "`socks5h` (the hostname is resolved by the proxy), `socks5` (resolved here), `http` or `https`. `pnpm ops " +
+ "network` also takes the whole as `proxy: \"socks5h://host:port\"`.",
+ host: "The proxy's hostname or IP address (letters, digits, `.`, `-`; an IPv6 address in brackets).",
+ port: "The proxy's port, 1–65535.",
+ credentials:
+ "Whether the proxy needs a user and password. They are read from `network.credentialsFile` (or its " +
+ "environment variable), never from settings.json; an exit that needs them and has none fails its listings.",
enabled:
- "Off = the exit is out of every pool; channels recorded on it are re-chosen over the remaining exits on " +
- "their next listing.",
+ "Off = the exit is out of every pool; a channel already recorded on it fails its listings until `pnpm ops " +
+ "network-exit` moves it.",
};
export const NETWORK_PLATFORM_POLICY_FIELD_DOCS: FieldDocs<NetworkPlatformPolicy> = {
@@ -139,141 +169,148 @@ export const NETWORK_PLATFORM_POLICY_FIELD_DOCS: FieldDocs<NetworkPlatformPolicy
};
export function defaultNetworkSettings(): NetworkSettings {
- return { exits: [], platforms: {}, jars: {}, echoUrl: "" };
+ return { exits: [], platforms: {}, jars: {}, echoUrl: "", credentialsFile: DEFAULT_NETWORK_CREDENTIALS_FILE, startupProbe: true };
}
const EXIT_ID_RE = /^[a-z0-9][a-z0-9-]{0,39}$/;
const PLATFORM_KEY_RE = /^[a-z0-9][a-z0-9.-]{0,99}$/;
-const PROXY_SCHEMES = ["socks5h", "socks5", "http", "https"] as const;
-export type ProxyScheme = (typeof PROXY_SCHEMES)[number];
+const HOST_RE = /^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,62})(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,62}))*|\[[0-9A-Fa-f:.]+\])$/;
+// Unreserved characters and %XX, nothing else (RFC 3986): what the key file's
+// user and password may hold, so no parser — ours, yt-dlp's, a config line's —
+// can read them differently.
+const ENCODED_PART_RE = /^(?:[A-Za-z0-9\-._~]|%[0-9A-Fa-f]{2})+$/;
+
+export const PERCENT_ENCODE_SENTENCE =
+ "percent-encode the user and the password (every character but letters, digits and - . _ ~ — for example " +
+ "`my pass#1` is `my%20pass%231`; encodeURIComponent does it)";
function isObject(v: unknown): v is Record<string, unknown> {
return typeof v === "object" && v !== null && !Array.isArray(v);
}
-export type ParsedProxy = {
- scheme: ProxyScheme;
- host: string;
- port: number;
- username: string;
- password: string;
-};
+function hostOk(h: unknown): h is string {
+ return typeof h === "string" && h.length <= 253 && HOST_RE.test(h);
+}
-// A proxy URL read, or the sentence why not. Never echoes the URL (it may
-// hold a password).
-export function parseProxyUrl(raw: unknown): ParsedProxy | { error: string } {
+function portOk(p: unknown): p is number {
+ return typeof p === "number" && Number.isInteger(p) && p >= 1 && p <= 65535;
+}
+
+function schemeOf(s: unknown): ProxyScheme | null {
+ return typeof s === "string" && (PROXY_SCHEMES as readonly string[]).includes(s) ? (s as ProxyScheme) : null;
+}
+
+// A PROXY URL TYPED BY THE OPERATOR, read into its stored parts — never its
+// credentials. Parsed by hand (no WHATWG URL normalising one thing while
+// yt-dlp reads another), and a URL that carries userinfo is refused: with the
+// encoding sentence when it is not percent-encoded, always with where the
+// credentials go instead. Never echoes the input.
+export function parseProxyInput(raw: unknown): { scheme: ProxyScheme; host: string; port: number } | { error: string } {
if (typeof raw !== "string" || raw.trim() === "") return { error: "no proxy URL" };
const s = raw.trim();
- const scheme = /^([a-z0-9+.-]+):\/\//i.exec(s)?.[1]?.toLowerCase();
- if (!scheme || !(PROXY_SCHEMES as readonly string[]).includes(scheme)) {
- return { error: "the proxy URL's scheme must be socks5h://, socks5://, http:// or https://" };
+ const m = /^([A-Za-z0-9+.-]+):\/\/(.*)$/s.exec(s);
+ const scheme = schemeOf(m?.[1]?.toLowerCase());
+ if (!m || !scheme) return { error: "the proxy URL's scheme must be socks5h://, socks5://, http:// or https://" };
+ let rest = m[2]!;
+ if (!rest.includes("@") && /[/?#]/.test(rest.replace(/\/$/, ""))) {
+ return { error: "the proxy URL is scheme://host:port, with no path, query or fragment" };
}
- let u: URL;
- try {
- u = new URL(s);
- } catch {
- return { error: "the proxy URL does not parse" };
+ rest = rest.replace(/\/$/, "");
+ const at = rest.lastIndexOf("@");
+ // eslint-disable-next-line no-control-regex
+ if (at < 0 && /[\s\u0000-\u001f\u007f]/.test(rest)) return { error: "the proxy URL holds whitespace or a control character" };
+ if (at >= 0) {
+ const info = rest.slice(0, at);
+ const encoded = info.split(":").every((p) => p === "" || ENCODED_PART_RE.test(p)) && info.split(":").length <= 2;
+ return {
+ error:
+ (encoded ? "" : `the proxy URL's credentials are not percent-encoded — ${PERCENT_ENCODE_SENTENCE}. `) +
+ "Proxy credentials are not a setting — give the exit `credentials: true` and put " +
+ "NETWORK_EXIT_<ID>=user:password (percent-encoded) in the mode-600 file network.credentialsFile names",
+ };
}
- const host = u.hostname.replace(/^\[|\]$/g, "");
- if (!host) return { error: "the proxy URL names no host" };
- if (!u.port) return { error: "the proxy URL must name its port (socks5h://host:1080)" };
- if ((u.pathname && u.pathname !== "/") || u.search || u.hash) {
- return { error: "the proxy URL is scheme://[user:pass@]host:port, with no path, query or fragment" };
+ const hp = /^(\[[^\]]*\]|[^:]*):(\d{1,5})$/.exec(rest);
+ if (!hp) return { error: "the proxy URL must name its host and port (socks5h://host:1080)" };
+ const host = hp[1]!;
+ const port = Number(hp[2]);
+ if (!hostOk(host)) return { error: "the proxy URL's host is not a hostname or an IP address" };
+ if (!portOk(port)) return { error: "the proxy URL's port is not 1–65535" };
+ return { scheme, host, port };
+}
+
+export type ExitCredentials = { username: string; password: string; encoded: string };
+
+// A key-file value, `user:password`, each part percent-encoded. Never echoes it.
+export function parseCredentials(raw: string): ExitCredentials | { error: string } {
+ const v = raw.trim();
+ const i = v.indexOf(":");
+ if (i <= 0 || i === v.length - 1) return { error: `the credentials are not user:password — ${PERCENT_ENCODE_SENTENCE}` };
+ const user = v.slice(0, i);
+ const pass = v.slice(i + 1);
+ if (!ENCODED_PART_RE.test(user) || !ENCODED_PART_RE.test(pass)) {
+ return { error: `the credentials hold characters that are not percent-encoded — ${PERCENT_ENCODE_SENTENCE}` };
}
- let username = "";
- let password = "";
try {
- username = decodeURIComponent(u.username);
- password = decodeURIComponent(u.password);
+ return { username: decodeURIComponent(user), password: decodeURIComponent(pass), encoded: `${user}:${pass}` };
} catch {
- return { error: "the proxy URL's credentials are not valid percent-encoding" };
+ return { error: `the credentials are not valid percent-encoding — ${PERCENT_ENCODE_SENTENCE}` };
}
- return { scheme: scheme as ProxyScheme, host, port: Number(u.port), username, password };
-}
-
-const USERINFO_IN_URL = /\b([a-z][a-z0-9+.-]*:\/\/)([^\s/@'"<>]*)@/gi;
-
-// Every `scheme://userinfo@` in `text` with the userinfo replaced — for any
-// string that might carry a proxy URL (an ops answer, a log line).
-export function redactUrlUserinfo(text: string): string {
- return text.replace(USERINFO_IN_URL, (_m, scheme: string, info: string) =>
- info === "" || info === "<redacted>" ? `${scheme}${info}@` : `${scheme}<redacted>@`,
- );
}
-// The proxy URL to show: credentials replaced with `<redacted>`.
-export function maskProxyUrl(raw: string): string {
- return redactUrlUserinfo(raw);
+export function credentialsEnvKey(id: string): string {
+ return `NETWORK_EXIT_${id.toUpperCase().replace(/-/g, "_")}`;
}
-// scheme://host:port and nothing else — for a log line.
-export function proxyDisplay(raw: string): string {
- const p = parseProxyUrl(raw);
- if ("error" in p) return "(an invalid proxy URL)";
- const host = p.host.includes(":") ? `[${p.host}]` : p.host;
- return `${p.scheme}://${host}:${p.port}`;
+// What to show for an exit anywhere: built from the stored parts, so it has
+// no secret in it to mask.
+export function exitDisplay(e: Pick<NetworkExit, "scheme" | "host" | "port" | "credentials">): string {
+ return `${e.scheme}://${e.host}:${e.port}${e.credentials ? " (credentials)" : ""}`;
}
-export function proxyHasCredentials(raw: string): boolean {
- const p = parseProxyUrl(raw);
- return !("error" in p) && (p.username !== "" || p.password !== "");
+// THE PROXY URL A CHILD IS GIVEN (internal only — stdin, the proxy client).
+export function proxyUrlOf(e: Pick<NetworkExit, "scheme" | "host" | "port">, creds: ExitCredentials | null): string {
+ return `${e.scheme}://${creds ? `${creds.encoded}@` : ""}${e.host}:${e.port}`;
}
-// The strings a log must never carry for `raw`: the URL itself, its userinfo,
-// the password (raw and decoded). Longest first.
-export function proxySecretFragments(raw: string): string[] {
- const out = new Set<string>();
- const s = raw.trim();
- if (proxyHasCredentials(s)) {
- out.add(s);
- const m = /^[a-z0-9+.-]+:\/\/([^@/]*)@/i.exec(s);
- if (m?.[1]) {
- out.add(m[1]);
- const pass = m[1].includes(":") ? m[1].slice(m[1].indexOf(":") + 1) : "";
- if (pass) {
- out.add(pass);
- try {
- out.add(decodeURIComponent(pass));
- } catch {
- /* kept raw */
- }
- }
- }
- }
+// The exact strings a child's output must never carry into a log: the
+// encoded userinfo, the user, the password encoded, decoded and as a Python
+// repr (yt-dlp -v prints the config as one). Values, never a pattern.
+export function secretFragmentsOf(creds: ExitCredentials | null): string[] {
+ if (!creds) return [];
+ const [user, pass] = [creds.encoded.slice(0, creds.encoded.indexOf(":")), creds.encoded.slice(creds.encoded.indexOf(":") + 1)];
+ const repr = (s: string) => s.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
+ const out = new Set([creds.encoded, user, pass, creds.username, creds.password, repr(creds.password), repr(creds.username)]);
return [...out].filter((f) => f.length > 0).sort((a, b) => b.length - a.length);
}
export function redactFragments(text: string, fragments: readonly string[]): string {
let out = text;
for (const f of fragments) out = out.split(f).join("<redacted>");
- return redactUrlUserinfo(out);
+ return out;
}
-// A MASKED PROXY SENT BACK KEEPS THE STORED ONE. A form or an ops caller
-// shows `socks5h://<redacted>@host:port`; sending that back unchanged means
-// "keep the credentials" and must not save the mask as a password.
-export function unmaskProxy(submitted: string, stored: string | undefined): string {
- if (stored === undefined || !submitted.includes("<redacted>@")) return submitted;
- return maskProxyUrl(stored) === submitted.trim() ? stored : submitted;
+function exitFromRaw(e: Record<string, unknown>): NetworkExit | null {
+ const id = typeof e.id === "string" ? e.id.trim() : "";
+ const scheme = schemeOf(e.scheme);
+ if (!EXIT_ID_RE.test(id) || id === DIRECT_EXIT || !scheme || !hostOk(e.host) || !portOk(e.port)) return null;
+ const label = typeof e.label === "string" && e.label.trim() ? e.label.trim().slice(0, 80) : id;
+ return { id, label, scheme, host: e.host, port: e.port, credentials: e.credentials === true, enabled: e.enabled !== false };
}
// THE TOTAL READER (the settings schema's coercion). Keeps every structurally
-// valid entry — an out-of-scope policy included, so `get network` can say it
-// is ignored — and drops what is not. The STRICT check is
-// networkSettingsProblems, which the writers refuse with.
+// valid entry and drops what is not. It never decides a route: the listing
+// reads the file strictly (controller/networkExits.ts loadNetworkStrict) and
+// FAILS on anything networkSettingsProblems refuses.
export function sanitizeNetwork(v: unknown): NetworkSettings {
const r = isObject(v) ? v : {};
const exits: NetworkExit[] = [];
const seen = new Set<string>();
for (const e of Array.isArray(r.exits) ? r.exits : []) {
if (!isObject(e)) continue;
- const id = typeof e.id === "string" ? e.id.trim() : "";
- if (!EXIT_ID_RE.test(id) || id === DIRECT_EXIT || seen.has(id)) continue;
- const proxy = typeof e.proxy === "string" ? e.proxy.trim() : "";
- if ("error" in parseProxyUrl(proxy)) continue;
- seen.add(id);
- const label = typeof e.label === "string" && e.label.trim() ? e.label.trim().slice(0, 80) : id;
- exits.push({ id, label, proxy, enabled: e.enabled !== false });
+ const x = exitFromRaw(e);
+ if (!x || seen.has(x.id)) continue;
+ seen.add(x.id);
+ exits.push(x);
}
const platforms: Record<string, NetworkPlatformPolicy> = {};
if (isObject(r.platforms)) {
@@ -298,7 +335,14 @@ export function sanitizeNetwork(v: unknown): NetworkSettings {
}
}
const echoUrl = typeof r.echoUrl === "string" && validEchoUrl(r.echoUrl.trim()) ? r.echoUrl.trim() : "";
- return { exits, platforms, jars, echoUrl };
+ const credentialsFile =
+ typeof r.credentialsFile === "string" && looksLikePath(r.credentialsFile) ? r.credentialsFile.trim() : DEFAULT_NETWORK_CREDENTIALS_FILE;
+ return { exits, platforms, jars, echoUrl, credentialsFile, startupProbe: r.startupProbe !== false };
+}
+
+function looksLikePath(v: string): boolean {
+ const s = v.trim();
+ return s.length > 0 && (s.includes("/") || s.startsWith("~"));
}
function validEchoUrl(s: string): boolean {
@@ -311,35 +355,42 @@ function validEchoUrl(s: string): boolean {
}
}
-// THE STRICT CHECK every writer refuses with: one sentence per problem, each
-// naming its path. Never echoes a proxy URL.
+const NETWORK_KEYS = ["exits", "platforms", "jars", "echoUrl", "credentialsFile", "startupProbe"];
+const EXIT_KEYS = ["id", "label", "scheme", "host", "port", "credentials", "enabled"];
+
+// THE STRICT CHECK every writer refuses with — and the listing fails on: one
+// sentence per problem, each naming its path. Never echoes a value that could
+// be a secret.
export function networkSettingsProblems(v: unknown): string[] {
const problems: string[] = [];
- if (!isObject(v)) return ["network: must be an object {exits, platforms, jars, echoUrl}"];
+ if (!isObject(v)) return ["network: must be an object {exits, platforms, jars, echoUrl, credentialsFile, startupProbe}"];
for (const k of Object.keys(v)) {
- if (!["exits", "platforms", "jars", "echoUrl"].includes(k)) problems.push(`network.${k}: not a network key (exits, platforms, jars, echoUrl)`);
+ if (!NETWORK_KEYS.includes(k)) problems.push(`network.${k}: not a network key (${NETWORK_KEYS.join(", ")})`);
}
const ids = new Set<string>();
- const enabled = new Set<string>();
if (v.exits !== undefined && !Array.isArray(v.exits)) problems.push("network.exits: must be a list");
(Array.isArray(v.exits) ? v.exits : []).forEach((e, i) => {
const at = `network.exits[${i}]`;
- if (!isObject(e)) return problems.push(`${at}: must be {id, label, proxy, enabled}`);
+ if (!isObject(e)) return problems.push(`${at}: must be {${EXIT_KEYS.join(", ")}}`);
for (const k of Object.keys(e)) {
- if (!["id", "label", "proxy", "enabled"].includes(k)) problems.push(`${at}.${k}: not an exit key (id, label, proxy, enabled)`);
+ if (!EXIT_KEYS.includes(k)) {
+ problems.push(
+ `${at}.${k}: not an exit key (${EXIT_KEYS.join(", ")})` +
+ (k === "proxy" ? " — an exit is stored as scheme, host and port; its credentials live in network.credentialsFile" : ""),
+ );
+ }
}
const id = typeof e.id === "string" ? e.id : "";
if (id === DIRECT_EXIT) problems.push(`${at}.id: "direct" is the built-in exit with no proxy and cannot be redefined`);
else if (!EXIT_ID_RE.test(id)) problems.push(`${at}.id: lowercase letters, digits and "-", up to 40 characters`);
else if (ids.has(id)) problems.push(`${at}.id: "${id}" is defined twice`);
- else {
- ids.add(id);
- if (e.enabled !== false) enabled.add(id);
- }
+ else ids.add(id);
+ if (!schemeOf(e.scheme)) problems.push(`${at}.scheme: socks5h, socks5, http or https`);
+ if (!hostOk(e.host)) problems.push(`${at}.host: a hostname or an IP address (no credentials, no spaces)`);
+ if (!portOk(e.port)) problems.push(`${at}.port: a whole number 1–65535`);
if (e.label !== undefined && typeof e.label !== "string") problems.push(`${at}.label: must be a string`);
if (e.enabled !== undefined && typeof e.enabled !== "boolean") problems.push(`${at}.enabled: must be true or false`);
- const p = parseProxyUrl(e.proxy);
- if ("error" in p) problems.push(`${at}.proxy: ${p.error}`);
+ if (e.credentials !== undefined && typeof e.credentials !== "boolean") problems.push(`${at}.credentials: must be true or false`);
});
if (v.platforms !== undefined && !isObject(v.platforms)) problems.push("network.platforms: must be an object keyed by platform");
for (const [platform, raw] of Object.entries(isObject(v.platforms) ? v.platforms : {})) {
@@ -391,6 +442,13 @@ export function networkSettingsProblems(v: unknown): string[] {
if (v.echoUrl !== undefined && (typeof v.echoUrl !== "string" || !validEchoUrl(v.echoUrl.trim()))) {
problems.push("network.echoUrl: blank, or an http(s) URL with no credentials");
}
+ if (v.credentialsFile !== undefined && (typeof v.credentialsFile !== "string" || !looksLikePath(v.credentialsFile))) {
+ problems.push(
+ "network.credentialsFile: the PATH of the mode-600 file that holds the exits' credentials — the value sent is " +
+ "not a path; refused, not stored",
+ );
+ }
+ if (v.startupProbe !== undefined && typeof v.startupProbe !== "boolean") problems.push("network.startupProbe: true or false");
return problems;
}
@@ -411,8 +469,8 @@ export function stickyExitFor(slug: string, pool: readonly string[]): string {
}
// The platform's pool for `kind`: its policy's exits that are enabled (direct
-// always is), in policy order; null = no policy (direct, no state read), and
-// for a platform or kind outside the trial's scope.
+// always is), in policy order; null = no policy (direct), and for a platform
+// or kind outside the trial's scope.
export function exitPool(
network: NetworkSettings | undefined,
platform: string,
@@ -428,9 +486,45 @@ 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",
+ "--username",
+ "--password",
+ "--twofactor",
+ "--video-password",
+ "--netrc",
+ "--netrc-location",
+ "--netrc-cmd",
+ "--ap-mso",
+ "--ap-username",
+ "--ap-password",
+ "--client-certificate",
+ "--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));
+}
+
// THE LOGIN A REQUEST CARRIES, read off its final argv (`--` ends options):
-// the jar id, or null for a logged-out request. Conservative: anything that
-// looks like an account or a clearance makes the request pinned.
+// 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]!;
@@ -444,17 +538,12 @@ export function requestJar(argv: readonly string[]): string | null {
const browser = valueOf(i, "--cookies-from-browser");
if (browser !== undefined) return `browser:${browser}`;
const file = valueOf(i, "--cookies");
- if (file !== undefined && file !== "" && file.toLowerCase() !== "none") return `file:${file}`;
- for (const opt of ["--username", "-u", "--password", "-p", "--video-password", "--netrc", "--netrc-location", "--netrc-cmd", "--ap-mso", "--ap-username", "--ap-password", "--client-certificate"]) {
- if (a === opt || a.startsWith(`${opt}=`)) return `login:${opt.replace(/^-+/, "")}`;
- }
- for (const opt of ["--add-headers", "--add-header"]) {
- const h = valueOf(i, opt);
- const name = h !== undefined ? /^\s*([A-Za-z-]+)\s*:/.exec(h)?.[1]?.toLowerCase() : undefined;
- if (name === "cookie" || name === "authorization") return `header:${name}`;
- }
- const xa = valueOf(i, "--extractor-args");
- if (xa !== undefined && /token|cookie|auth|password|login/i.test(xa)) return "login:extractor-args";
+ 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}`;
}
return null;
}
@@ -477,18 +566,40 @@ export function jarExitChangeRefusal(args: {
);
}
+// A listing that could not be sent through its network exit — the proxy did
+// not answer, the settings could not be read, the recorded exit is gone, the
+// credentials are missing, or yt-dlp's output did not show the proxy. Never
+// retried direct.
+export class NetworkExitError extends Error {
+ readonly exit: string;
+ constructor(exit: string, message: string) {
+ super(message);
+ this.name = "NetworkExitError";
+ this.exit = exit;
+ }
+}
+
// ---------------------------------------------------------------------------
// ONE WRITE OF THE BLOCK — what `pnpm ops network` and the /settings section
// both send, applied to the stored block. Pure; the writers then refuse the
// result with networkSettingsProblems and save it through saveSettings.
//
-// exits: [...] the whole list (a masked proxy keeps the stored one)
-// upsertExit: {id, label?, proxy?, enabled?} one exit added or changed
+// exits: [...] the whole list (stored form)
+// upsertExit: {id, label?, proxy? | scheme?/host?/port?, credentials?, enabled?}
// removeExit: "<id>" one exit gone — and out of every policy
// platforms: {<p>: policy | null} merged per platform; null removes
// jars: {...} the whole map (refused in the trial unless every value is direct)
-// echoUrl: "<url>" | ""
-export const NETWORK_REQUEST_KEYS = ["exits", "upsertExit", "removeExit", "platforms", "jars", "echoUrl"] as const;
+// echoUrl, credentialsFile, startupProbe
+export const NETWORK_REQUEST_KEYS = [
+ "exits",
+ "upsertExit",
+ "removeExit",
+ "platforms",
+ "jars",
+ "echoUrl",
+ "credentialsFile",
+ "startupProbe",
+] as const;
export class NetworkRequestError extends Error {}
@@ -498,29 +609,40 @@ export function applyNetworkRequest(current: NetworkSettings, body: Record<strin
throw new NetworkRequestError(`unknown key(s): ${unknown.join(", ")} — accepted: ${NETWORK_REQUEST_KEYS.join(", ")}`);
}
if (Object.keys(body).length === 0) throw new NetworkRequestError("nothing to change");
- const stored = new Map(current.exits.map((e) => [e.id, e]));
let exits: unknown[] = current.exits.map((e) => ({ ...e }));
let platforms: Record<string, unknown> = Object.fromEntries(
Object.entries(current.platforms).map(([p, v]) => [p, { ...v, exits: [...v.exits], kinds: [...v.kinds] }]),
);
if (body.exits !== undefined) {
if (!Array.isArray(body.exits)) throw new NetworkRequestError("exits: must be a list");
- exits = body.exits.map((e) => {
- if (!isObject(e)) return e;
- const id = typeof e.id === "string" ? e.id : "";
- return typeof e.proxy === "string" ? { ...e, proxy: unmaskProxy(e.proxy, stored.get(id)?.proxy) } : e;
- });
+ exits = body.exits;
}
if (body.upsertExit !== undefined) {
const u = body.upsertExit;
- if (!isObject(u) || typeof u.id !== "string") throw new NetworkRequestError("upsertExit: must be {id, label?, proxy?, enabled?}");
+ if (!isObject(u) || typeof u.id !== "string") {
+ throw new NetworkRequestError("upsertExit: must be {id, label?, proxy?, credentials?, enabled?}");
+ }
const i = exits.findIndex((e) => isObject(e) && e.id === u.id);
const prev = i >= 0 ? (exits[i] as Record<string, unknown>) : undefined;
- if (!prev && u.proxy === undefined) throw new NetworkRequestError(`upsertExit: a new exit "${u.id}" needs its proxy URL`);
- const merged: Record<string, unknown> = { id: u.id, label: u.label ?? prev?.label ?? u.id, proxy: prev?.proxy, enabled: u.enabled ?? prev?.enabled ?? true };
- if (typeof u.proxy === "string") merged.proxy = unmaskProxy(u.proxy, stored.get(u.id)?.proxy);
- else if (u.proxy !== undefined) merged.proxy = u.proxy;
- for (const k of Object.keys(u)) if (!["id", "label", "proxy", "enabled"].includes(k)) merged[k] = u[k];
+ let parts: Record<string, unknown> = {};
+ if (u.proxy !== undefined) {
+ const p = parseProxyInput(u.proxy);
+ if ("error" in p) throw new NetworkRequestError(`upsertExit.proxy: ${p.error}`);
+ parts = p;
+ } else {
+ for (const k of ["scheme", "host", "port"]) if (u[k] !== undefined) parts[k] = u[k];
+ }
+ if (!prev && parts.host === undefined) throw new NetworkRequestError(`upsertExit: a new exit "${u.id}" needs its proxy (scheme://host:port)`);
+ const merged: Record<string, unknown> = {
+ id: u.id,
+ label: u.label ?? prev?.label ?? u.id,
+ scheme: parts.scheme ?? prev?.scheme,
+ host: parts.host ?? prev?.host,
+ port: parts.port ?? prev?.port,
+ credentials: u.credentials ?? prev?.credentials ?? false,
+ enabled: u.enabled ?? prev?.enabled ?? true,
+ };
+ for (const k of Object.keys(u)) if (![...EXIT_KEYS, "proxy"].includes(k)) merged[k] = u[k];
if (i >= 0) exits[i] = merged;
else exits.push(merged);
}
@@ -550,10 +672,7 @@ export function applyNetworkRequest(current: NetworkSettings, body: Record<strin
platforms,
jars: body.jars !== undefined ? body.jars : { ...current.jars },
echoUrl: body.echoUrl !== undefined ? body.echoUrl : current.echoUrl,
+ credentialsFile: body.credentialsFile !== undefined ? body.credentialsFile : current.credentialsFile,
+ startupProbe: body.startupProbe !== undefined ? body.startupProbe : current.startupProbe,
};
}
-
-// The view a page or an ops answer may show: every proxy masked.
-export function maskedNetwork(n: NetworkSettings): NetworkSettings {
- return { ...n, exits: n.exits.map((e) => ({ ...e, proxy: maskProxyUrl(e.proxy) })) };
-}
diff --git a/common/lib/networkProxy-server.ts b/common/lib/networkProxy-server.ts
@@ -12,7 +12,27 @@
import net from "node:net";
import tls from "node:tls";
import dns from "node:dns/promises";
-import { parseProxyUrl, type ParsedProxy } from "./networkExits";
+import { PROXY_SCHEMES, type ProxyScheme } from "./networkExits";
+
+// The URL here is one this repo built (lib/networkExits.ts proxyUrlOf) from a
+// validated exit and its key-file credentials — never one taken from input.
+type ParsedProxy = { scheme: ProxyScheme; host: string; port: number; username: string; password: string };
+
+function parseProxyUrl(raw: string): ParsedProxy | { error: string } {
+ const m = /^([a-z0-9]+):\/\/(?:([^:@/]*):([^@/]*)@)?(\[[^\]]+\]|[^:/@]+):(\d+)$/.exec(raw);
+ if (!m || !(PROXY_SCHEMES as readonly string[]).includes(m[1]!)) return { error: "the exit's proxy is not scheme://host:port" };
+ try {
+ return {
+ scheme: m[1] as ProxyScheme,
+ username: m[2] ? decodeURIComponent(m[2]) : "",
+ password: m[3] ? decodeURIComponent(m[3]) : "",
+ host: m[4]!.replace(/^\[|\]$/g, ""),
+ port: Number(m[5]),
+ };
+ } catch {
+ return { error: "the exit's credentials are not valid percent-encoding" };
+ }
+}
export const PROXY_TIMEOUT_MS = 8_000;
@@ -249,9 +269,12 @@ export async function openTunnel(
// THE PREFLIGHT: the proxy answers (TCP, or TLS for https://) and, for a
// SOCKS proxy, accepts the greeting and the exit's login. Nothing is asked of
// any destination.
+// `connectOnly` (the startup probe): the TCP or TLS connect alone — no
+// greeting, no login.
export async function preflightProxy(
proxyUrl: string,
timeoutMs = PROXY_TIMEOUT_MS,
+ opts: { connectOnly?: boolean } = {},
): Promise<{ ok: true; ms: number } | ProxyFailure> {
const p = parseProxyUrl(proxyUrl);
if ("error" in p) return { ok: false, reason: p.error };
@@ -261,7 +284,7 @@ export async function preflightProxy(
await withTimeout(
(async () => {
sock = await connectToProxy(p);
- if (p.scheme === "socks5" || p.scheme === "socks5h") {
+ if (!opts.connectOnly && (p.scheme === "socks5" || p.scheme === "socks5h")) {
const r = reader(sock);
await socksGreeting(sock, r, p);
r.release();
diff --git a/common/testing/fakeProxy.ts b/common/testing/fakeProxy.ts
@@ -38,10 +38,13 @@ export async function startFakeSocks5(opts: {
connects: ConnectSeen[];
greetings: number;
authFailures: number;
+ // TCP connections accepted, greeting or not (a connect-only probe).
+ connections: number;
close: () => Promise<void>;
}> {
- const state = { connects: [] as ConnectSeen[], greetings: 0, authFailures: 0 };
+ const state = { connects: [] as ConnectSeen[], greetings: 0, authFailures: 0, connections: 0 };
const server = net.createServer((sock) => {
+ state.connections++;
let buf = Buffer.alloc(0);
let stage: "greet" | "auth" | "connect" | "piped" = "greet";
sock.on("error", () => {});
@@ -130,6 +133,9 @@ export async function startFakeSocks5(opts: {
get authFailures() {
return state.authFailures;
},
+ get connections() {
+ return state.connections;
+ },
close: () => closeServer(server, sockets),
};
}
diff --git a/common/ytdlp/networkExitListing.test.ts b/common/ytdlp/networkExitListing.test.ts
@@ -8,9 +8,12 @@ import path from "node:path";
// pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/networkExitListing.test.ts
//
// THE LISTING THROUGH NAMED NETWORK EXITS (lane network-exits), end to end
-// below yt-dlp: a stand-in yt-dlp records its argv and its stdin, and the
-// exits are in-process fake SOCKS5 proxies on loopback. No request leaves
-// 127.0.0.1. getPaths() memoizes, so the env is set before anything imports it.
+// below yt-dlp: a stand-in yt-dlp records its argv, stdin and proxy
+// environment and behaves like yt-dlp about proxies (the stdin `--proxy`,
+// else the environment's ALL_PROXY, else DIRECT — to a listening trap socket,
+// so a fall-back to direct is SEEN). The exits are in-process fake SOCKS5
+// proxies on loopback. ytdlp/networkExitRealYtdlp.test.ts runs the real
+// binary. getPaths() memoizes, so the env is set before anything imports it.
const ROOT = mkdtempSync(path.join(os.tmpdir(), "network-exits-"));
process.env.TRANSCRIPTS_DIR = ROOT;
process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
@@ -24,68 +27,88 @@ const { stickyExitFor } = await import("../lib/networkExits");
const NE = await import("../controller/networkExits");
const { downloadQueueKey } = await import("../lib/queueKeys");
const { waitForQueueGap, noteQueueJobEnd, clearQueueGaps } = await import("../jobs/queueGap");
-const { closedPort, startCountingServer, startFakeSocks5 } = await import("../testing/fakeProxy");
+const { withRumbleDefaults } = await import("../lib/rumbleDefaults");
+const { closedPort, startCountingServer, startEchoServer, startFakeSocks5 } = await import("../testing/fakeProxy");
const SECRET = "hunter2-very-secret";
-const target = await startCountingServer();
-// The fakes tunnel nowhere: a listing's stand-in yt-dlp never really uses them.
+const trap = await startCountingServer();
const proxyA = await startFakeSocks5({ username: "user-a", password: SECRET, route: () => null });
const proxyB = await startFakeSocks5({ route: () => null });
after(async () => {
- await Promise.all([target.close(), proxyA.close(), proxyB.close()]);
+ await Promise.all([trap.close(), proxyA.close(), proxyB.close()]);
rmSync(ROOT, { recursive: true, force: true });
});
-const PROXY_A = `socks5h://user-a:${SECRET}@127.0.0.1:${proxyA.port}`;
-const PROXY_B = `socks5h://127.0.0.1:${proxyB.port}`;
+// 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`);
+chmodSync(KEYS, 0o600);
+
+const PROXY_A_URL = `socks5h://user-a:${SECRET}@127.0.0.1:${proxyA.port}`;
-// A stand-in yt-dlp: appends {argv, stdin} to $FAKE_RECORD, then answers per $FAKE_MODE.
const RECORD = path.join(ROOT, "spawns.jsonl");
const BIN = path.join(ROOT, "fake-listing.mjs");
writeFileSync(
BIN,
`#!/usr/bin/env node
import { appendFileSync, readFileSync } from "node:fs";
+import net from "node:net";
const argv = process.argv.slice(2);
-const stdin = argv.includes("--config-locations") ? readFileSync(0, "utf8") : null;
-appendFileSync(process.env.FAKE_RECORD, JSON.stringify({ argv, stdin }) + "\\n");
const mode = process.env.FAKE_MODE ?? "ok";
-if (mode === "verbose") process.stderr.write("[debug] | Stdin config: " + JSON.stringify(stdin) + "\\n");
-if (mode === "429") {
- process.stdout.write("https://rumble.com/v1-a.html\\n");
- process.stderr.write("[RumbleChannel] x: Downloading page 2\\nERROR: [RumbleChannel] x: Unable to download webpage: HTTP Error 429: Too Many Requests\\n");
- process.exit(1);
+const ci = argv.indexOf("--config-locations");
+const stdin = ci >= 0 && argv[ci + 1] === "-" && mode !== "ignore-stdin" ? readFileSync(0, "utf8") : null;
+const envProxy = {};
+for (const k of ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "all_proxy", "no_proxy"]) if (process.env[k] !== undefined) envProxy[k] = process.env[k];
+appendFileSync(process.env.FAKE_RECORD, JSON.stringify({ argv, stdin, envProxy }) + "\\n");
+const stdinProxy = stdin ? /--proxy '([^']*)'/.exec(stdin)?.[1] : undefined;
+const proxy = stdinProxy ?? process.env.ALL_PROXY ?? process.env.all_proxy;
+if (argv.includes("-v")) process.stderr.write("[debug] | Stdin config: " + JSON.stringify(stdin) + "\\n");
+if (argv.includes("-v") && proxy && mode !== "no-map") process.stderr.write("[debug] Proxy map: {'all': '" + proxy + "'}\\n");
+const finish = () => {
+ if (mode === "429") {
+ process.stdout.write("https://rumble.com/v1-a.html\\n");
+ process.stderr.write("[RumbleChannel] x: Downloading page 2\\nERROR: [RumbleChannel] x: Unable to download webpage: HTTP Error 429: Too Many Requests\\n");
+ process.exit(1);
+ }
+ process.stdout.write("https://rumble.com/v1-a.html\\nhttps://rumble.com/v2-b.html\\n");
+};
+if (stdinProxy) finish();
+else {
+ // No stdin proxy: like yt-dlp, the environment's proxy, else DIRECT.
+ const port = proxy ? Number(new URL(proxy).port) : Number(process.env.FAKE_TRAP_PORT);
+ const s = net.connect(port, "127.0.0.1", () => { s.destroy(); finish(); });
+ s.on("error", () => { process.stderr.write("ERROR: Unable to connect\\n"); process.exit(1); });
}
-process.stdout.write("https://rumble.com/v1-a.html\\nhttps://rumble.com/v2-b.html\\n");
`,
);
chmodSync(BIN, 0o755);
process.env.FAKE_RECORD = RECORD;
+process.env.FAKE_TRAP_PORT = String(trap.port);
+
+function exitRow(id: string, port: number, extra: Record<string, unknown> = {}) {
+ return { id, label: id.toUpperCase(), scheme: "socks5h", host: "127.0.0.1", port, credentials: false, enabled: true, ...extra };
+}
+const EXITS = [exitRow("exit-a", proxyA.port, { credentials: true }), exitRow("exit-b", proxyB.port)];
+const RUMBLE_POLICY = { exits: EXITS, platforms: { rumble: { exits: ["exit-a", "exit-b"], mode: "sticky" } }, credentialsFile: KEYS };
-function settings(network?: unknown) {
+function settings(network?: unknown, extra: Record<string, unknown> = {}) {
writeFileSync(
process.env.SETTINGS_FILE!,
- JSON.stringify({ pacing: { jitter: 0 }, ...(network ? { network } : {}) }) + "\n",
+ JSON.stringify({ pacing: { jitter: 0 }, ...extra, ...(network ? { network } : {}) }) + "\n",
);
}
-const EXITS = [
- { id: "exit-a", label: "A", proxy: PROXY_A, enabled: true },
- { id: "exit-b", label: "B", proxy: PROXY_B, enabled: true },
-];
-const RUMBLE_POLICY = { exits: EXITS, platforms: { rumble: { exits: ["exit-a", "exit-b"], mode: "sticky" } } };
-
-// Two slugs, one on each exit of [exit-a, exit-b].
const SLUGS = Array.from({ length: 40 }, (_, i) => `demo-rumble-${i}`);
const ON_A = SLUGS.find((s) => stickyExitFor(s, ["exit-a", "exit-b"]) === "exit-a")!;
const ON_B = SLUGS.find((s) => stickyExitFor(s, ["exit-a", "exit-b"]) === "exit-b")!;
-function spawns(): Array<{ argv: string[]; stdin: string | null }> {
+type Spawn = { argv: string[]; stdin: string | null; envProxy: Record<string, string> };
+function spawns(): Spawn[] {
if (!existsSync(RECORD)) return [];
return readFileSync(RECORD, "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l));
}
-async function list(slug: string, config: Record<string, unknown> = {}, log: string[] = []) {
+async function list(slug: string, config: Record<string, unknown> = {}, log: string[] = [], holder?: object) {
mkdirSync(path.join(ROOT, "channels", slug), { recursive: true });
writeFileSync(
path.join(ROOT, "channels", slug, "config.json"),
@@ -95,13 +118,16 @@ async function list(slug: string, config: Record<string, unknown> = {}, log: str
channelConfig: { handling: "transcribe", url: "https://rumble.com/c/demo", ...config } as never,
paths: { ...getPaths(), ytdlpBin: BIN },
channelSlug: slug,
- onLog: (s) => log.push(s),
+ onLog: (s: string) => log.push(s),
signal: new AbortController().signal,
- });
+ ...(holder ? { listingRoute: holder } : {}),
+ } as never);
}
// Today's rumble listing argv (main a0ef2b1ae), pacing jitter off.
const MAIN_ARGV = ["--flat-playlist", "--skip-download", "--print", "url", "--impersonate", "chrome", "--sleep-requests", "1", "https://rumble.com/c/demo"];
+const ROUTED_PREFIX = ["--ignore-config", "--config-locations", "-", "-v"];
+const PROXY_VARS = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "all_proxy", "no_proxy"];
beforeEach(() => {
rmSync(RECORD, { force: true });
@@ -110,169 +136,205 @@ beforeEach(() => {
for (const d of existsSync(path.join(ROOT, "channels")) ? readdirSync(path.join(ROOT, "channels")) : []) {
rmSync(path.join(ROOT, "channels", d, "network-exit.json"), { force: true });
}
+ for (const k of PROXY_VARS) delete process.env[k];
process.env.FAKE_MODE = "ok";
});
-test("no policy: the argv, the echo and the files are today's, byte for byte", async () => {
+test("no policy: the argv, the echo, the environment and the files are today's", async () => {
settings();
+ process.env.HTTPS_PROXY = "http://127.0.0.1:2";
const log: string[] = [];
assert.deepEqual(await list(ON_A, {}, log), ["https://rumble.com/v1-a.html", "https://rumble.com/v2-b.html"]);
- assert.deepEqual(spawns(), [{ argv: MAIN_ARGV, stdin: null }]);
+ assert.deepEqual(spawns(), [{ argv: MAIN_ARGV, stdin: null, envProxy: { HTTPS_PROXY: "http://127.0.0.1:2" } }]);
assert.deepEqual(log, [`$ ${BIN} ${MAIN_ARGV.join(" ")}\n`]);
assert.ok(!existsSync(path.join(ROOT, ".network")));
assert.ok(!existsSync(NE.channelExitPath(getPaths(), ON_A)));
- // A policy for ANOTHER platform changes nothing here either.
- settings({ exits: EXITS, platforms: { twitch: { exits: ["exit-a"] } } });
- rmSync(RECORD, { force: true });
- await list(ON_A);
- assert.deepEqual(spawns(), [{ argv: MAIN_ARGV, stdin: null }]);
});
-test("through an exit: the proxy reaches yt-dlp on stdin only; the rest of the argv is unchanged", async () => {
+test("through an exit: --ignore-config, the proxy on stdin only, every proxy variable dead or gone (findings 2-4)", async () => {
settings(RUMBLE_POLICY);
+ process.env.NO_PROXY = "*";
+ process.env.no_proxy = "*";
+ process.env.HTTPS_PROXY = "http://127.0.0.1:2";
const log: string[] = [];
await list(ON_A, {}, log);
const [s] = spawns();
- assert.deepEqual(s!.argv, ["--config-locations", "-", ...MAIN_ARGV]);
- assert.equal(s!.stdin, `--proxy '${PROXY_A}'\n`);
+ assert.deepEqual(s!.argv, [...ROUTED_PREFIX, ...MAIN_ARGV]);
+ assert.equal(s!.stdin, `--proxy '${PROXY_A_URL}'\n`);
+ // NO_PROXY gone; the proxy variables point at a loopback port that refuses.
+ assert.deepEqual(Object.keys(s!.envProxy).sort(), ["ALL_PROXY", "HTTPS_PROXY", "HTTP_PROXY", "all_proxy", "http_proxy", "https_proxy"]);
+ for (const v of Object.values(s!.envProxy)) assert.equal(v, "socks5h://127.0.0.1:1");
const text = log.join("");
- assert.ok(!text.includes(SECRET), text);
- assert.match(text, new RegExp(`Network exit: "exit-a" \\(socks5h://127\\.0\\.0\\.1:${proxyA.port}\\)`));
- assert.equal(proxyA.greetings > 0, true, "the proxy was preflighted");
+ assert.ok(!text.includes(SECRET) && !text.includes("user-a"), text);
+ assert.ok(!text.includes("[debug]"), "yt-dlp's debug lines stay out of the job log");
+ assert.match(text, new RegExp(`Network exit: "exit-a" \\(socks5h://127\\.0\\.0\\.1:${proxyA.port} \\(credentials\\)\\)`));
+ assert.match(text, /yt-dlp confirmed the listing's proxy is exit "exit-a"/);
+});
+
+test("a direct spawn under a policy has every inherited proxy variable removed (finding 2)", async () => {
+ settings(RUMBLE_POLICY);
+ process.env.HTTPS_PROXY = "http://127.0.0.1:2";
+ process.env.no_proxy = "*";
+ await list(ON_A, { cookiesFromBrowser: "firefox", cookieMode: "always" });
+ const [s] = spawns();
+ assert.ok(!s!.argv.includes("--config-locations"));
+ assert.deepEqual(s!.envProxy, {});
+});
+
+test("a child that ignores stdin meets the dead proxy, never the direct path (finding 3)", async () => {
+ settings(RUMBLE_POLICY);
+ process.env.FAKE_MODE = "ignore-stdin";
+ const before = trap.connections();
+ await assert.rejects(list(ON_B), /through network exit "exit-b"|did not show/);
+ assert.equal(trap.connections(), before, "nothing reached the direct path");
+});
+
+test("a listing whose output does not show the proxy is discarded and fails closed (finding 3)", async () => {
+ settings(RUMBLE_POLICY);
+ process.env.FAKE_MODE = "no-map";
+ await assert.rejects(list(ON_B), (err: unknown) => {
+ assert.ok(err instanceof NetworkExitError);
+ assert.match(err.message, /could not show that the rumble listing went through network exit "exit-b" — its result is discarded/);
+ return true;
+ });
});
-test("sticky: chosen once by the hash, recorded, and kept on every later listing", async () => {
+test("sticky: chosen once by the hash, recorded, kept; adding an exit moves no one", async () => {
settings(RUMBLE_POLICY);
await list(ON_B);
- const rec = await NE.readChannelExitRecord(getPaths(), ON_B);
- assert.equal(rec!.exit, "exit-b");
- assert.equal(rec!.by, "hash");
- for (let i = 0; i < 3; i++) await list(ON_B);
- assert.equal(spawns().every((s) => s.argv[0] === "--config-locations" && s.stdin!.includes(`:${proxyB.port}`)), true);
- // Adding an exit does not move a recorded channel.
- settings({ ...RUMBLE_POLICY, exits: [...EXITS, { id: "exit-c", proxy: PROXY_B }], platforms: { rumble: { exits: ["exit-c", "exit-a", "exit-b"] } } });
+ assert.equal((await NE.readChannelExitRecord(getPaths(), ON_B))!.exit, "exit-b");
+ settings({ ...RUMBLE_POLICY, exits: [...EXITS, exitRow("exit-c", proxyB.port)], platforms: { rumble: { exits: ["exit-c", "exit-a", "exit-b"] } } });
await list(ON_B);
assert.equal((await NE.readChannelExitRecord(getPaths(), ON_B))!.exit, "exit-b");
});
-test("a removed or disabled exit re-chooses the channel; nothing else moves it", async () => {
+test("a recorded exit disabled or removed FAILS the listing; nothing re-chooses it (finding 5)", async () => {
settings(RUMBLE_POLICY);
await list(ON_A);
- settings({ ...RUMBLE_POLICY, exits: [{ ...EXITS[0], enabled: false }, EXITS[1]] });
+ const n = spawns().length;
+ for (const net of [
+ { ...RUMBLE_POLICY, exits: [{ ...EXITS[0], enabled: false }, EXITS[1]] },
+ { ...RUMBLE_POLICY, exits: [EXITS[1]], platforms: { rumble: { exits: ["exit-b"] } } },
+ ]) {
+ settings(net);
+ await assert.rejects(list(ON_A), (err: unknown) => {
+ assert.ok(err instanceof NetworkExitError);
+ assert.match(err.message, /recorded network exit "exit-a" is no longer an enabled exit of rumble .* pnpm ops network-exit/);
+ return true;
+ });
+ }
+ assert.equal(spawns().length, n);
+ assert.equal((await NE.readChannelExitRecord(getPaths(), ON_A))!.exit, "exit-a");
+ // A policy taken away on purpose is direct again.
+ settings({ ...RUMBLE_POLICY, platforms: {} });
await list(ON_A);
- const rec = await NE.readChannelExitRecord(getPaths(), ON_A);
- assert.equal(rec!.exit, "exit-b");
- assert.equal(rec!.previous, "exit-a");
- assert.match(rec!.reason!, /no longer an enabled exit/);
+ assert.deepEqual(spawns().at(-1)!.argv, MAIN_ARGV);
+});
+
+test("unreadable settings, a broken network block, or missing credentials fail the listing, never direct (finding 5)", async () => {
+ settings(RUMBLE_POLICY);
+ await list(ON_A);
+ const n = spawns().length;
+ writeFileSync(process.env.SETTINGS_FILE!, "{ not json");
+ await assert.rejects(list(ON_A), /settings\.json could not be read .* the rumble listing was not sent/);
+ await assert.rejects(list(ON_B), /settings\.json could not be read/);
+ settings({ ...RUMBLE_POLICY, exits: [{ ...EXITS[0], host: "bad host" }, EXITS[1]] });
+ await assert.rejects(list(ON_A), /network settings do not validate: network\.exits\[0\]\.host/);
+ settings({ ...RUMBLE_POLICY, credentialsFile: path.join(ROOT, "absent.env") });
+ await assert.rejects(list(ON_A), /exit "exit-a" needs credentials/);
+ assert.equal(spawns().length, n);
});
test("reassign only by the action: network-exit {slug, exit}", async () => {
settings(RUMBLE_POLICY);
await list(ON_A);
- const r = await NE.assignChannelExit({ paths: getPaths(), slug: ON_A, exit: "exit-b" });
- assert.deepEqual(r, { slug: ON_A, platform: "rumble", exit: "exit-b", previous: "exit-a" });
+ assert.deepEqual(await NE.assignChannelExit({ paths: getPaths(), slug: ON_A, exit: "exit-b" }), { slug: ON_A, platform: "rumble", exit: "exit-b", previous: "exit-a" });
await list(ON_A);
assert.ok(spawns().at(-1)!.stdin!.includes(`:${proxyB.port}`));
await NE.assignChannelExit({ paths: getPaths(), slug: ON_A, exit: "direct" });
await list(ON_A);
- assert.deepEqual(spawns().at(-1), { argv: MAIN_ARGV, stdin: null });
+ assert.deepEqual(spawns().at(-1)!.argv, MAIN_ARGV);
await assert.rejects(NE.assignChannelExit({ paths: getPaths(), slug: ON_A, exit: "exit-z" }), /no exit "exit-z"/);
- await assert.rejects(NE.assignChannelExit({ paths: getPaths(), slug: "nope", exit: "exit-a" }), /not found/);
});
-test("a cookie-bearing listing never gets a non-direct exit", async () => {
- settings(RUMBLE_POLICY);
- for (const config of [
- { cookiesFromBrowser: "firefox", cookieMode: "always" },
- { ytdlpExtraArgs: ["--cookies", "/tmp/jar.txt"] },
- { ytdlpExtraArgs: ["--add-headers", "Cookie: cf_clearance=x"] },
- ]) {
+test("cookies supplied any way keep the listing direct (finding 4)", async () => {
+ const ways: Array<[string, Record<string, unknown>, Record<string, unknown>]> = [
+ ["global browser cookies, always", {}, { cookiesFromBrowser: "firefox", cookieMode: "always" }],
+ ["channel browser cookies, always", { cookiesFromBrowser: "firefox", cookieMode: "always" }, {}],
+ ["a cookie file", { ytdlpExtraArgs: ["--cookies", "/tmp/jar.txt"] }, {}],
+ ["an abbreviated option", { ytdlpExtraArgs: ["--cookies-from-b", "firefox"] }, {}],
+ ["a header", { ytdlpExtraArgs: ["--add-headers", "Cookie: cf_clearance=x"] }, {}],
+ ["a config file", { ytdlpExtraArgs: ["--config-locations", "/tmp/yt.conf"] }, {}],
+ ["netrc", { ytdlpExtraArgs: ["-n"] }, {}],
+ ["a Rumble channel made with the defaults", withRumbleDefaults({ handling: "transcribe", platform: "rumble", url: "https://rumble.com/c/demo" } as never) as never, {}],
+ ];
+ for (const [what, config, global] of ways) {
+ settings(RUMBLE_POLICY, global);
rmSync(RECORD, { force: true });
const log: string[] = [];
await list(ON_A, config, log);
const [s] = spawns();
- assert.ok(!s!.argv.includes("--config-locations"), JSON.stringify(config));
- assert.equal(s!.stdin, null);
- assert.match(log.join(""), /Network exit: direct \(this listing carries a login/);
+ assert.ok(!s!.argv.includes("--config-locations") || s!.argv.indexOf("--config-locations") > 3, what);
+ assert.equal(s!.stdin, null, what);
+ assert.match(log.join(""), /Network exit: direct \(this listing carries a login/, what);
}
- // Even a hand-edited jar assignment is not honoured in the trial.
- settings({ ...RUMBLE_POLICY, jars: { "browser:firefox": "exit-a" } });
- rmSync(RECORD, { force: true });
- await list(ON_A, { cookiesFromBrowser: "firefox", cookieMode: "always" });
- assert.ok(!spawns()[0]!.argv.includes("--config-locations"));
});
-test("a 429 through an exit rests that exit only; its channels wait, the other exit's do not", async () => {
+test("a 429 through an exit rests that exit only; its channels wait; when both rest the platform is due", async () => {
settings(RUMBLE_POLICY);
process.env.FAKE_MODE = "429";
await assert.rejects(list(ON_A), (err: unknown) => {
assert.ok(err instanceof EnumerationIncompleteError);
assert.equal(err.exit, "exit-a");
assert.equal(err.platformBackoffDue, false);
- assert.equal(err.pagesReached, 2);
return true;
});
- assert.equal(await platformCooldownRemainingMs("rumble", getPaths()), 0, "the platform is not cooled for one exit");
- assert.ok((await NE.exitRestUntil(getPaths(), "rumble", "exit-a"))! > Date.now());
- // The channel on the resting exit WAITS: deferred, nothing spawned, no hop.
+ assert.equal(await platformCooldownRemainingMs("rumble", getPaths()), 0);
process.env.FAKE_MODE = "ok";
const before = spawns().length;
- await assert.rejects(list(ON_A), (err: unknown) => {
- assert.ok(err instanceof JobDeferredError);
- assert.ok(err.until > Date.now());
- assert.match(err.message, /rumble exit "exit-a" rests until \d\d:\d\d .* never moves to another exit/);
- return true;
- });
- assert.equal(spawns().length, before);
- assert.equal((await NE.readChannelExitRecord(getPaths(), ON_A))!.exit, "exit-a");
- // The manual Sync gate says the same sentence.
- assert.match((await NE.listingRestRefusal(getPaths(), ON_A, "https://rumble.com/c/demo"))!.sentence, /rests until/);
- // A channel on the other exit lists.
+ await assert.rejects(list(ON_A), (err: unknown) => err instanceof JobDeferredError && /rests until/.test(err.message));
+ assert.equal(spawns().length, before, "no hop: nothing was sent");
assert.equal((await list(ON_B)).length, 2);
- // When the second exit rests too, the platform's own cooldown is due.
process.env.FAKE_MODE = "429";
- await assert.rejects(list(ON_B), (err: unknown) => {
- assert.ok(err instanceof EnumerationIncompleteError);
- assert.equal(err.platformBackoffDue, true);
- return true;
- });
- const usage = await NE.usageOver(getPaths(), 1);
- assert.equal(usage["rumble/exit-a"]!.rateLimits, 1);
- assert.equal(usage["rumble/exit-a"]!.rests, 1);
- assert.equal(usage["rumble/exit-b"]!.requests, 2);
+ await assert.rejects(list(ON_B), (err: unknown) => err instanceof EnumerationIncompleteError && err.platformBackoffDue === true);
});
-test("a clean listing through the exit ends its rest", async () => {
+test("one job, one exit: the route is pinned for every page; a rest mid-walk defers, never switches (finding 7)", async () => {
settings(RUMBLE_POLICY);
- await NE.restExit(getPaths(), "rumble", "exit-b", ["exit-a", "exit-b"], Date.now() - 31 * 60_000);
- assert.equal(await NE.exitRestUntil(getPaths(), "rumble", "exit-b"), null);
- await list(ON_B);
- const rests = readFileSync(path.join(ROOT, ".network", "rests.json"), "utf8");
- assert.ok(!rests.includes("rumble/exit-b"), rests);
+ const job = {};
+ await list(ON_A, {}, [], job);
+ // A reassignment and a policy change 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");
+ assert.ok(p2!.stdin!.includes(`:${proxyA.port}`));
+ // The next job takes the new assignment.
+ await list(ON_A);
+ assert.ok(spawns().at(-1)!.stdin!.includes(`:${proxyB.port}`));
+ // The pinned exit goes to rest mid-walk: the job defers.
+ await NE.restExit(getPaths(), "rumble", "exit-a", ["exit-a", "exit-b"]);
+ await assert.rejects(list(ON_A, {}, [], job), JobDeferredError);
});
-test("a dead proxy fails closed: named error, yt-dlp not spawned, no direct connection", async () => {
- const dead = `socks5h://user-a:${SECRET}@127.0.0.1:${await closedPort()}`;
- settings({ exits: [{ id: "exit-a", proxy: dead }], platforms: { rumble: { exits: ["exit-a"] } } });
- process.env.FAKE_DIRECT_PORT = String(target.port);
+test("a dead proxy fails closed: named error, nothing spawned, the direct trap untouched", async () => {
+ const dead = await closedPort();
+ const trapBefore = trap.connections();
+ settings({ ...RUMBLE_POLICY, exits: [exitRow("exit-a", dead, { credentials: true })], platforms: { rumble: { exits: ["exit-a"] } } });
await assert.rejects(list(ON_A), (err: unknown) => {
assert.ok(err instanceof NetworkExitError);
- assert.equal(err.exit, "exit-a");
- assert.match(err.message, /^network exit "exit-a" \(socks5h:\/\/127\.0\.0\.1:\d+\) did not answer: connection refused\. The rumble listing was not sent — a listing never falls back to direct\.$/);
- assert.ok(!err.message.includes(SECRET));
+ assert.match(err.message, /^network exit "exit-a" \(socks5h:\/\/127\.0\.0\.1:\d+ \(credentials\)\) did not answer: connection refused\. The rumble listing was not sent — a listing never falls back to direct\.$/);
return true;
});
assert.deepEqual(spawns(), []);
- assert.equal(target.connections(), 0);
- assert.equal((await NE.usageOver(getPaths(), 1))["rumble/exit-a"]!.proxyFailures, 1);
+ assert.equal(trap.connections(), trapBefore, "nothing reached the direct path");
});
-test("a credentialed proxy URL appears in no log, error, record or report", async () => {
- settings({ ...RUMBLE_POLICY, echoUrl: "" });
- process.env.FAKE_MODE = "verbose";
+test("the secret appears in no log, error, record, report or settings answer", async () => {
+ settings(RUMBLE_POLICY);
const log: string[] = [];
await list(ON_A, {}, log);
- assert.ok(log.join("").includes("Stdin config"), "the stand-in echoed its stdin like -v");
process.env.FAKE_MODE = "429";
let message = "";
await list(ON_A, {}, log).catch((e: Error) => (message = e.message));
@@ -283,82 +345,89 @@ test("a credentialed proxy URL appears in no log, error, record or report", asyn
for (const n of readdirSync(d)) {
const p = path.join(d, n);
if (statSync(p).isDirectory()) walk(p);
- else if (p !== process.env.SETTINGS_FILE && p !== RECORD) files.push(readFileSync(p, "utf8"));
+ else if (![KEYS, RECORD].includes(p)) files.push(readFileSync(p, "utf8"));
}
};
walk(ROOT);
- for (const [what, text] of [["log", log.join("")], ["error", message], ["report", report], ["files", files.join("\n")]] as const) {
+ 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.match(report, /socks5h:\/\/<redacted>@127\.0\.0\.1/);
});
-test("pacing is per platform: two exits make the same starts per hour as one", async () => {
- // The queue a listing waits on and the pace in its argv know no exit.
- settings(RUMBLE_POLICY);
- await list(ON_A);
- await list(ON_B);
- const [a, b] = spawns();
- assert.deepEqual(a!.argv.slice(2), MAIN_ARGV);
- assert.deepEqual(b!.argv.slice(2), MAIN_ARGV);
+test("pacing per platform: two exits make the same requests per hour as one, at main's pace", async () => {
const config = { handling: "transcribe", url: "https://rumble.com/c/demo" } as never;
- assert.equal(downloadQueueKey(config), "platform:rumble");
- // An hour of back-to-back listing jobs on rumble's queue, 5 s each, spread
- // over one exit or over two: the queue gap admits the same number.
- const startsPerHour = async (slugs: string[]) => {
+ const run = async (slugs: string[]) => {
+ rmSync(RECORD, { force: true });
clearQueueGaps();
let now = 1_000_000;
const clock = { now: () => now, sleep: async (ms: number) => void (now += ms) };
const pacing = () => ({ jobGapSeconds: { rumble: 120 }, jitter: 0 });
const jobsDir = mkdtempSync(path.join(ROOT, "jobs-"));
- let starts = 0;
- for (let i = 0; now < 1_000_000 + 3_600_000; i++) {
- const slug = slugs[i % slugs.length]!;
- void slug; // the exit a slug is on never enters the queue key
- await waitForQueueGap({ paths: { jobsDir }, queueKey: downloadQueueKey(config), pacing, clock });
+ for (let i = 0; ; i++) {
+ // The queue a listing waits on is named from its channel alone.
+ const queueKey = downloadQueueKey(config);
+ await waitForQueueGap({ paths: { jobsDir }, queueKey, pacing, clock });
if (now >= 1_000_000 + 3_600_000) break;
- starts++;
+ await list(slugs[i % slugs.length]!);
now += 5_000;
- await noteQueueJobEnd({ jobsDir }, downloadQueueKey(config), now);
+ await noteQueueJobEnd({ jobsDir }, queueKey, now);
}
- return starts;
+ return spawns();
};
- const one = await startsPerHour([ON_A]);
- const two = await startsPerHour([ON_A, ON_B]);
- assert.equal(two, one);
- assert.equal(one, 29);
+ settings({ ...RUMBLE_POLICY, platforms: { rumble: { exits: ["exit-a"] } } });
+ const one = await run([ON_A]);
+ settings(RUMBLE_POLICY);
+ const two = await run([ON_A, ON_B]);
+ assert.equal(one.length, 29);
+ assert.equal(two.length, one.length);
+ for (const s of [...one, ...two]) assert.deepEqual(s.argv.slice(ROUTED_PREFIX.length), MAIN_ARGV);
+ assert.deepEqual(new Set(two.map((s) => /127\.0\.0\.1:(\d+)/.exec(s.stdin!)![1])), new Set([String(proxyA.port), String(proxyB.port)]));
});
-test("the probe: each proxy answers or not; the echo URL is fetched only when set", async () => {
- const { startEchoServer } = await import("../testing/fakeProxy");
+test("the probe: connect-only at startup (no echo, can be off); the echo only when asked (finding 6)", async () => {
const echo = await startEchoServer("198.51.100.23\n");
const routed = await startFakeSocks5({ route: (host, port) => (host === "echo.exit.test" ? { host: "127.0.0.1", port } : null) });
try {
- const dead = `socks5h://user-a:${SECRET}@127.0.0.1:${await closedPort()}`;
- const exits = [
- { id: "exit-a", label: "A", proxy: `socks5h://127.0.0.1:${routed.port}`, enabled: true },
- { id: "exit-dead", label: "D", proxy: dead, enabled: true },
- { id: "exit-off", label: "O", proxy: dead, enabled: false },
- ];
- const net = { exits, platforms: {}, jars: {}, echoUrl: "" };
- const quiet = await NE.probeNetworkExits(getPaths(), net);
- assert.equal(echo.hits(), 0, "no echo URL, no request");
- assert.equal(quiet.exits["exit-a"]!.reachable, true);
- assert.equal(quiet.exits["exit-dead"]!.reachable, false);
- assert.equal(quiet.exits["exit-off"], undefined);
- const loud = await NE.probeNetworkExits(getPaths(), { ...net, echoUrl: `http://echo.exit.test:${echo.port}/` });
- assert.equal(loud.exits["exit-a"]!.address, "198.51.100.23");
- assert.equal(echo.hits(), 1);
- assert.ok(!readFileSync(path.join(ROOT, ".network", "probe.json"), "utf8").includes(SECRET));
- // The startup probe logs one line per enabled exit, no secret.
- settings({ exits, platforms: {} });
+ const exits = [exitRow("exit-a", routed.port), exitRow("exit-dead", await closedPort())];
+ const net = { exits, platforms: {}, credentialsFile: KEYS, echoUrl: `http://echo.exit.test:${echo.port}/` };
+ settings(net);
const lines: string[] = [];
NE.startupNetworkProbe({ log: (l) => lines.push(l), delayMs: 0, paths: getPaths() });
for (let i = 0; i < 100 && lines.length < 2; i++) await new Promise((r) => setTimeout(r, 20));
assert.deepEqual(lines.map((l) => l.split(":")[0]).sort(), ['network exit "exit-a"', 'network exit "exit-dead"']);
- assert.ok(lines.every((l) => !l.includes(SECRET)));
+ assert.equal(echo.hits(), 0, "the startup probe sends no echo request");
+ assert.equal(routed.greetings, 0, "and no SOCKS greeting: a connection only");
+ assert.ok(routed.connections > 0);
+ // Off: nothing at all.
+ settings({ ...net, startupProbe: false });
+ const before = routed.connections;
+ const quiet: string[] = [];
+ NE.startupNetworkProbe({ log: (l) => quiet.push(l), delayMs: 0, paths: getPaths() });
+ await new Promise((r) => setTimeout(r, 300));
+ assert.equal(routed.connections, before);
+ assert.deepEqual(quiet, []);
+ // The operator's explicit probe fetches the echo through the exit.
+ const loud = await NE.probeNetworkExits(getPaths(), undefined, new Date(), { explicit: true });
+ assert.equal(loud.exits["exit-a"]!.address, "198.51.100.23");
+ assert.equal(echo.hits(), 1);
} finally {
await Promise.all([echo.close(), routed.close()]);
}
});
+
+test("in scope in a synthetic corpus: cookie-free Rumble channels and Twitch channels", () => {
+ const rumble = (extra: Record<string, unknown>) => ({ handling: "transcribe", platform: "rumble", url: "https://rumble.com/c/x", ...extra });
+ const corpus = [
+ withRumbleDefaults(rumble({}) as never),
+ withRumbleDefaults(rumble({}) as never),
+ withRumbleDefaults(rumble({}) as never),
+ rumble({ cookieMode: "when-required", cookiesFromBrowser: "firefox", ytdlpExtraArgs: ["--impersonate", "firefox"] }),
+ rumble({ ytdlpExtraArgs: ["--impersonate", "chrome"] }),
+ { handling: "transcribe", url: "https://www.twitch.tv/x/videos" },
+ { handling: "transcribe", url: "https://www.twitch.tv/y/videos", cookiesFromBrowser: "firefox", cookieMode: "always" },
+ { handling: "youtube", url: "https://www.youtube.com/@x" },
+ ];
+ const inScope = corpus.filter((c) => NE.listingRoutable(c as never, { cookiesFromBrowser: "", cookieMode: "when-required" }));
+ assert.equal(inScope.length, 3);
+});
diff --git a/common/ytdlp/networkExitRealYtdlp.test.ts b/common/ytdlp/networkExitRealYtdlp.test.ts
@@ -0,0 +1,132 @@
+import { test, after } from "node:test";
+import assert from "node:assert/strict";
+import http from "node:http";
+import net from "node:net";
+import { execFileSync } from "node:child_process";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/networkExitRealYtdlp.test.ts
+//
+// THE REAL yt-dlp ON PATH, through the routed spawn (runYtdlp's
+// listThroughExit), against an in-process fake SOCKS5 proxy and a loopback
+// fake site (an RSS feed the generic extractor lists). Nothing leaves
+// 127.0.0.1: the listing URL names a TRAP port that only counts connections;
+// the proxy maps a CONNECT to that port onto the real site. So a listing that
+// arrives at the site came through the proxy, and one that went direct hits
+// the trap. Skipped when no yt-dlp is installed.
+
+const ROOT = mkdtempSync(path.join(os.tmpdir(), "net-real-ytdlp-"));
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+writeFileSync(process.env.SETTINGS_FILE, "{}\n");
+
+let haveYtdlp = true;
+try {
+ execFileSync("yt-dlp", ["--version"], { stdio: "ignore", timeout: 30_000 });
+} catch {
+ haveYtdlp = false;
+}
+
+const { listThroughExit } = await import("./runYtdlp");
+const { startCountingServer, startFakeSocks5 } = await import("../testing/fakeProxy");
+
+const RSS =
+ '<?xml version="1.0"?><rss version="2.0"><channel><title>t</title>' +
+ "<item><title>a</title><link>http://127.0.0.1:1/v1-a.html</link></item>" +
+ "<item><title>b</title><link>http://127.0.0.1:1/v2-b.html</link></item></channel></rss>";
+const seen: Array<Record<string, string | string[] | undefined>> = [];
+const site = http.createServer((req, res) => {
+ seen.push(req.headers);
+ res.writeHead(200, { "content-type": "application/rss+xml" });
+ res.end(RSS);
+});
+await new Promise<void>((r) => site.listen(0, "127.0.0.1", () => r()));
+const sitePort = (site.address() as net.AddressInfo).port;
+const trap = await startCountingServer();
+const SECRET = "real-ytdlp-secret";
+const proxy = await startFakeSocks5({
+ username: "user-r",
+ password: SECRET,
+ route: (_h, p) => (p === trap.port ? { host: "127.0.0.1", port: sitePort } : null),
+});
+const refusing = await startFakeSocks5({ route: () => null });
+after(async () => {
+ await Promise.all([trap.close(), proxy.close(), refusing.close(), new Promise((r) => site.close(r))]);
+ rmSync(ROOT, { recursive: true, force: true });
+});
+
+const FEED = `http://127.0.0.1:${trap.port}/feed.rss`;
+const PROXY_URL = `socks5h://user-r:${SECRET}@127.0.0.1:${proxy.port}`;
+
+async function routed(extra: string[], opts: { proxyUrl?: string; cwd?: string } = {}) {
+ const log: string[] = [];
+ const urls = await listThroughExit({
+ bin: "yt-dlp",
+ cwd: opts.cwd ?? ROOT,
+ args: ["--flat-playlist", "--skip-download", "--print", "url", ...extra, FEED],
+ exit: "exit-r",
+ platform: "rumble",
+ proxyUrl: opts.proxyUrl ?? PROXY_URL,
+ secrets: [SECRET, `user-r:${SECRET}`, "user-r"],
+ onLog: (s) => log.push(s),
+ signal: new AbortController().signal,
+ });
+ return { urls, log: log.join("") };
+}
+
+const skip = haveYtdlp ? false : "no yt-dlp on PATH";
+
+test("the listing arrives through the proxy, not directly — urllib and curl_cffi (impersonate)", { skip }, async () => {
+ for (const extra of [[], ["--impersonate", "chrome"]]) {
+ const before = { site: seen.length, connects: proxy.connects.length };
+ const r = await routed(extra);
+ assert.deepEqual(r.urls, ["http://127.0.0.1:1/v1-a.html", "http://127.0.0.1:1/v2-b.html"], extra.join(" "));
+ assert.equal(seen.length, before.site + 1);
+ assert.deepEqual(proxy.connects.slice(before.connects), [{ atyp: "ipv4", host: "127.0.0.1", port: trap.port }]);
+ assert.equal(trap.connections(), 0, "nothing went direct");
+ assert.ok(!r.log.includes(SECRET) && !r.log.includes("user-r"), r.log);
+ }
+});
+
+test("an inherited NO_PROXY=* and HTTP(S)_PROXY cannot send it direct (finding 2)", { skip }, async () => {
+ const saved = { ...process.env };
+ Object.assign(process.env, { NO_PROXY: "*", no_proxy: "*", HTTP_PROXY: `http://127.0.0.1:${trap.port}`, HTTPS_PROXY: `http://127.0.0.1:${trap.port}` });
+ try {
+ const before = proxy.connects.length;
+ const r = await routed(["--impersonate", "chrome"]);
+ assert.equal(r.urls.length, 2);
+ assert.equal(proxy.connects.length, before + 1);
+ assert.equal(trap.connections(), 0);
+ } finally {
+ for (const k of ["NO_PROXY", "no_proxy", "HTTP_PROXY", "HTTPS_PROXY"]) if (saved[k] === undefined) delete process.env[k];
+ }
+});
+
+test("a yt-dlp.conf in the channel directory is ignored (finding 4)", { skip }, async () => {
+ const cwd = mkdtempSync(path.join(ROOT, "chan-"));
+ writeFileSync(path.join(cwd, "yt-dlp.conf"), '--add-headers "X-Leak: from-config"\n');
+ const before = seen.length;
+ await routed([], { cwd });
+ assert.equal(seen[before]!["x-leak"], undefined);
+});
+
+test("a proxy that refuses the destination fails the listing naming the exit; the direct trap stays at 0", { skip }, async () => {
+ await assert.rejects(routed([], { proxyUrl: `socks5h://127.0.0.1:${refusing.port}` }), (err: unknown) => {
+ assert.ok(err instanceof Error);
+ assert.match(err.message, /network exit "exit-r"/);
+ return true;
+ });
+ assert.equal(trap.connections(), 0);
+});
+
+test("a dead proxy: yt-dlp fails, the direct trap stays at 0", { skip }, async () => {
+ const dead = net.createServer();
+ await new Promise<void>((r) => dead.listen(0, "127.0.0.1", () => r()));
+ const port = (dead.address() as net.AddressInfo).port;
+ await new Promise((r) => dead.close(r));
+ await assert.rejects(routed([], { proxyUrl: `socks5h://127.0.0.1:${port}` }), /network exit "exit-r"/);
+ assert.equal(trap.connections(), 0);
+});
diff --git a/common/ytdlp/runYtdlp.ts b/common/ytdlp/runYtdlp.ts
@@ -94,8 +94,8 @@ import {
import { hasSubtitleRateLimit, isBotCheck } from "../lib/availability";
import {
DIRECT_EXIT,
- proxyDisplay,
- proxySecretFragments,
+ NetworkExitError,
+ exitDisplay,
redactFragments,
} from "../lib/networkExits";
import { preflightProxy } from "../lib/networkProxy-server";
@@ -107,6 +107,7 @@ import {
resolveListingRoute,
restExit,
restingSentence,
+ type ListingRoute,
} from "../controller/networkExits";
import { JobDeferredError } from "../jobs/jobDeferred";
import { computeKeepWindow, type KeepWindow } from "../controller/keptVideos";
@@ -245,6 +246,10 @@ export type RunYtdlpOpts = {
// every `{...opts}` copy by reference; a run that asked nothing is not clean
// (release 17 re-review R3).
requestCounter?: { n: number };
+ // Internal: the network route of this JOB's listings (lane network-exits,
+ // review 1 finding 7), resolved on the first listing and shared by every
+ // `{...opts}` copy by reference — every page of a walk leaves by it.
+ listingRoute?: { route?: ListingRoute };
};
// The batch modes whose child writes media into `data/<id>/` — yt-dlp's own
@@ -263,7 +268,8 @@ const MEDIA_WRITING_MODES: ReadonlySet<RunYtdlpOpts["mode"]> = new Set([
// coarse timestamps rounds down, so the window opens this much earlier.
const TIER_SINCE_SLACK_MS = 2_000;
-export async function runYtdlp(opts: RunYtdlpOpts): Promise<void> {
+export async function runYtdlp(input: RunYtdlpOpts): Promise<void> {
+ const opts: RunYtdlpOpts = { ...input, listingRoute: input.listingRoute ?? {} };
if (!opts.channelConfig.url) {
throw new Error("Channel has no `url` configured");
}
@@ -540,16 +546,9 @@ export class EnumerationIncompleteError extends Error {
}
}
-// A listing that could not be sent through its network exit — the proxy did
-// not answer, refused, or could not be logged in to. Never retried direct.
-export class NetworkExitError extends Error {
- readonly exit: string;
- constructor(exit: string, message: string) {
- super(message);
- this.name = "NetworkExitError";
- this.exit = exit;
- }
-}
+// A listing that could not be sent through its network exit (lib/
+// networkExits.ts): never retried direct.
+export { NetworkExitError };
// The last `Downloading page N` an extractor logged — yt-dlp's paged channel
// extractors print `[RumbleChannel] <name>: Downloading page 155` per page.
@@ -581,9 +580,10 @@ async function enumeratePlaylistUrls(
// THE LISTING, ROUTED (lane network-exits). `exit` is the network exit it went
// through, or null when the platform has no network policy — and then the
-// request is today's, byte for byte: same argv, same echo, same handling
-// (spawnListing with no `via`). Under a policy, resolveListingRoute decides
-// direct or an exit (controller/networkExits.ts) and spawnListing carries it.
+// request is today's, byte for byte: same argv, same echo, same environment,
+// same handling (spawnListing with no `via`). Under a policy the route is
+// resolved ONCE PER JOB (review 1, finding 7: `opts.listingRoute`, shared by
+// every page of a walk) and every page leaves by it.
async function enumeratePlaylistListing(
opts: RunYtdlpOpts,
root: string,
@@ -608,12 +608,16 @@ async function enumeratePlaylistListing(
opts.channelConfig.url!,
);
const platform = cooldownPlatformKey(opts.channelConfig);
- const route = await resolveListingRoute({
- paths: opts.paths,
- slug: opts.channelSlug,
- platform,
- argv: args,
- });
+ let route = opts.listingRoute?.route;
+ if (!route) {
+ route = await resolveListingRoute({
+ paths: opts.paths,
+ slug: opts.channelSlug,
+ platform,
+ argv: args,
+ });
+ if (opts.listingRoute) opts.listingRoute.route = route;
+ }
if (route.kind === "none") {
return { urls: await spawnListing(opts, root, args), exit: null };
}
@@ -623,7 +627,7 @@ async function enumeratePlaylistListing(
opts.onLog(
`Network exit: direct (${
route.why === "jar"
- ? `this listing carries a login — the ${route.jar} cookie jar — and a login never leaves the home address`
+ ? `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"
@@ -631,24 +635,26 @@ async function enumeratePlaylistListing(
);
} else {
// A RESTING EXIT: the channel waits for it (the job ends deferred and the
- // scheduler comes back at its end); it never hops to another exit.
+ // scheduler comes back at its end); it never hops to another exit — not
+ // on the first page, not half way through a walk.
const restUntil = await exitRestUntil(opts.paths, platform, exit);
if (restUntil) throw new JobDeferredError(restingSentence(platform, exit, restUntil), restUntil);
// FAIL CLOSED: the proxy must answer before anything is sent through it,
// and nothing is ever sent direct instead.
- const pf = await preflightProxy(route.exit.proxy);
+ const pf = await preflightProxy(route.proxyUrl);
if (!pf.ok) {
await countNetworkUse(opts.paths, platform, exit, { proxyFailures: 1 }).catch(() => {});
throw new NetworkExitError(
exit,
- `network exit "${exit}" (${proxyDisplay(route.exit.proxy)}) did not answer: ${pf.reason}. ` +
+ `network exit "${exit}" (${exitDisplay(route.exit)}) did not answer: ${redactFragments(pf.reason, route.secrets)}. ` +
`The ${platform} listing was not sent — a listing never falls back to direct.`,
);
}
- via.proxy = route.exit.proxy;
+ via.proxyUrl = route.proxyUrl;
+ via.secrets = route.secrets;
opts.onLog(
- `Network exit: "${exit}" (${proxyDisplay(route.exit.proxy)}) for this ${platform} listing; ` +
- `the proxy is given to yt-dlp on its stdin.\n`,
+ `Network exit: "${exit}" (${exitDisplay(route.exit)}) for this ${platform} listing; ` +
+ `yt-dlp reads the proxy from its stdin, with --ignore-config.\n`,
);
}
return { urls: await spawnListing(opts, root, args, via), exit };
@@ -656,34 +662,144 @@ async function enumeratePlaylistListing(
// 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 — which reaches yt-dlp on stdin only.
-type ListingVia = { platform: string; exit: string; pool: string[]; proxy?: string };
+// exit, the proxy URL (stdin only) and the exact values to scrub.
+type ListingVia = { platform: string; exit: string; pool: string[]; proxyUrl?: string; secrets?: string[] };
// A yt-dlp config-file line is split shell-style (and `#` starts a comment),
-// so the URL goes in single quotes.
+// so the URL goes in single quotes. The URL is built from validated parts
+// (lib/networkExits.ts proxyUrlOf) and holds no quote.
function configQuote(s: string): string {
return `'${s.replace(/'/g, `'"'"'`)}'`;
}
-// Redact `fragments` from a stream of chunks, a line at a time (a secret is
-// never split across two writes of the log).
-function lineRedactor(onLog: (s: string) => void, fragments: readonly string[]) {
+// 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;
+}
+
+// Lines for the job log from a routed child's stderr, a line at a time (a
+// value is never split across two writes): yt-dlp's `[debug]` lines (-v,
+// which prints the stdin config) are dropped, and every other line has the
+// exit's exact secret values removed.
+function routedStderr(onLog: (s: string) => void, secrets: readonly string[]) {
let pending = "";
+ const emit = (text: string) => {
+ const kept = text.split(/(?<=\n)/).filter((l) => !l.startsWith("[debug]"));
+ if (kept.length) onLog(redactFragments(kept.join(""), secrets));
+ };
return {
push(chunk: string) {
pending += chunk;
const nl = pending.lastIndexOf("\n");
if (nl < 0) return;
- onLog(redactFragments(pending.slice(0, nl + 1), fragments));
+ emit(pending.slice(0, nl + 1));
pending = pending.slice(nl + 1);
},
flush() {
- if (pending) onLog(redactFragments(pending, fragments));
+ if (pending) emit(pending);
pending = "";
},
};
}
+// THE ROUTED SPAWN. `--ignore-config` (no user, cwd or system config rides
+// through the exit — finding 4), `--config-locations -` (the proxy on stdin,
+// never in argv or /proc/<pid>/cmdline), `-v` (so yt-dlp itself says which
+// proxy it used), an environment with every proxy variable pointing at a
+// dead loopback port (a child that ignored stdin fails instead of listing
+// direct — finding 3). `confirmed`: yt-dlp's own `Proxy map` line names
+// exactly this proxy as `all`.
+async function spawnThroughExit(o: {
+ bin: string;
+ cwd: string;
+ args: string[];
+ proxyUrl: string;
+ secrets: readonly string[];
+ onLog: (s: string) => void;
+ signal: AbortSignal;
+}): Promise<{ urls: string[]; exitCode: number | undefined; stderr: string; confirmed: boolean }> {
+ const argv = ["--ignore-config", "--config-locations", "-", "-v", ...o.args];
+ o.onLog(`$ ${o.bin} ${argv.join(" ")}\n`);
+ const child = execa(o.bin, argv, {
+ cwd: o.cwd,
+ cancelSignal: o.signal,
+ all: false,
+ buffer: true,
+ reject: false,
+ input: `--proxy ${configQuote(o.proxyUrl)}\n`,
+ env: routedEnv(),
+ extendEnv: false,
+ });
+ const log = routedStderr(o.onLog, o.secrets);
+ child.stderr?.on("data", (c: Buffer) => log.push(c.toString("utf8")));
+ const result = await child;
+ log.flush();
+ const raw = String(result.stderr ?? "");
+ const confirmed = raw.split("\n").some((l) => l.trim() === `[debug] Proxy map: {'all': '${o.proxyUrl}'}`);
+ const stderr = redactFragments(
+ raw
+ .split("\n")
+ .filter((l) => !l.startsWith("[debug]"))
+ .join("\n"),
+ o.secrets,
+ );
+ const urls = String(result.stdout ?? "")
+ .split("\n")
+ .map((s) => s.trim())
+ .filter(Boolean);
+ return { urls, exitCode: result.exitCode, stderr, confirmed };
+}
+
+function discardedError(platform: string, exit: string): NetworkExitError {
+ return new NetworkExitError(
+ exit,
+ `network exit "${exit}": yt-dlp's output could not show that the ${platform} listing went through network exit ` +
+ `"${exit}" — its result is discarded and the listing fails (it never counts as a direct listing).`,
+ );
+}
+
+// ONE LISTING THROUGH AN EXIT, for a caller with no channel (the real-yt-dlp
+// test): the routed spawn, its failure naming the exit, an unconfirmed
+// result discarded.
+export async function listThroughExit(o: {
+ bin: string;
+ cwd: string;
+ args: string[];
+ exit: string;
+ platform: string;
+ proxyUrl: string;
+ secrets: readonly string[];
+ onLog: (s: string) => void;
+ signal: AbortSignal;
+}): Promise<string[]> {
+ const r = await spawnThroughExit(o);
+ if (r.exitCode !== 0 && r.exitCode !== 101) {
+ throw new Error(`yt-dlp exited with code ${r.exitCode} through network exit "${o.exit}"`);
+ }
+ if (!r.confirmed) throw discardedError(o.platform, o.exit);
+ o.onLog(`yt-dlp confirmed the listing's proxy is exit "${o.exit}".\n`);
+ return r.urls;
+}
+
async function spawnListing(
opts: RunYtdlpOpts,
root: string,
@@ -691,31 +807,45 @@ async function spawnListing(
via?: ListingVia,
): Promise<string[]> {
// The fixed waits drawn once for this run (lib/jitter.mjs).
- const jittered = jitterYtdlpSleeps(args);
- // Through an exit, `--config-locations -` makes yt-dlp read `--proxy <url>`
- // from stdin: the URL (and any credentials in it) is never in the argv, the
- // echo below, or /proc/<pid>/cmdline.
- const spawned = via?.proxy ? ["--config-locations", "-", ...jittered] : jittered;
- opts.onLog(`$ ${opts.paths.ytdlpBin} ${spawned.join(" ")}\n`);
+ const spawned = jitterYtdlpSleeps(args);
if (opts.requestCounter) opts.requestCounter.n++;
if (via) await countNetworkUse(opts.paths, via.platform, via.exit, { requests: 1 }).catch(() => {});
+ if (via?.proxyUrl) {
+ const r = await spawnThroughExit({
+ bin: opts.paths.ytdlpBin,
+ cwd: root,
+ args: spawned,
+ proxyUrl: via.proxyUrl,
+ secrets: via.secrets ?? [],
+ onLog: opts.onLog,
+ signal: opts.signal,
+ });
+ if (opts.signal.aborted) return r.urls;
+ if (r.exitCode !== 0 && r.exitCode !== 101) {
+ await listingFailedVia(opts, via, r.exitCode, r.stderr, 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`);
+ if (r.exitCode === 101) opts.onLog(`yt-dlp stopped on existing entry (exit 101).\n`);
+ // A clean listing through an exit ends its rest and its escalation.
+ await clearExitRest(opts.paths, via.platform, via.exit).catch(() => {});
+ return r.urls;
+ }
+ opts.onLog(`$ ${opts.paths.ytdlpBin} ${spawned.join(" ")}\n`);
+ // Under a policy, a DIRECT listing's environment has every proxy variable
+ // removed (finding 2): an inherited proxy never carries it — or its cookies
+ // — somewhere unintended. Without a policy, today's environment.
const child = execa(opts.paths.ytdlpBin, spawned, {
cwd: root,
cancelSignal: opts.signal,
all: false,
buffer: true,
reject: false,
- ...(via?.proxy ? { input: `--proxy ${configQuote(via.proxy)}\n` } : {}),
+ ...(via ? { env: envWithoutProxies(), extendEnv: false } : {}),
});
- // yt-dlp's -v prints the stdin config; every stderr line is redacted.
- const fragments = via?.proxy ? proxySecretFragments(via.proxy) : [];
- const redactor = via?.proxy ? lineRedactor(opts.onLog, fragments) : null;
- child.stderr?.on("data", (c: Buffer) =>
- redactor ? redactor.push(c.toString("utf8")) : opts.onLog(c.toString("utf8")),
- );
+ child.stderr?.on("data", (c: Buffer) => opts.onLog(c.toString("utf8")));
const result = await child;
- redactor?.flush();
const urls = String(result.stdout ?? "")
.split("\n")
.map((s) => s.trim())
@@ -729,7 +859,7 @@ async function spawnListing(
result.exitCode !== 101 &&
!opts.signal.aborted
) {
- const stderr = via?.proxy ? redactFragments(String(result.stderr ?? ""), fragments) : String(result.stderr ?? "");
+ const stderr = String(result.stderr ?? "");
if (via) await listingFailedVia(opts, via, result.exitCode, stderr, urls.length);
// A bot check on the listing is the service's cookies (cookie refresh
// alerts, lib/serviceCookies.ts), whatever else it is.
@@ -750,10 +880,6 @@ async function spawnListing(
if (result.exitCode === 101) {
opts.onLog(`yt-dlp stopped on existing entry (exit 101).\n`);
}
- // A clean listing through an exit ends its rest and its escalation.
- if (via && via.exit !== DIRECT_EXIT && !opts.signal.aborted) {
- await clearExitRest(opts.paths, via.platform, via.exit).catch(() => {});
- }
return urls;
}
@@ -763,7 +889,8 @@ async function spawnListing(
// Through an exit it never returns: a rate limit or a bot check RESTS the
// exit for the platform (the cookie alert is not raised — the request carried
// no cookies, and the answer was to the exit's address); the platform's own
-// cooldown is due only when every exit of the pool now rests.
+// cooldown is due only when every exit of the pool rests after a RATE LIMIT
+// (a bot check records no platform cooldown, as on direct).
async function listingFailedVia(
opts: RunYtdlpOpts,
via: ListingVia,
@@ -787,7 +914,11 @@ async function listingFailedVia(
`Network exit "${via.exit}" rests for ${via.platform} until ${new Date(until).toISOString()} after ${
rateLimited ? "a rate limit" : "a bot check"
}; its channels wait for it` +
- (allRest ? ` — every exit of ${via.platform} now rests, so ${via.platform} cools down as before` : "") +
+ (allRest
+ ? rateLimited
+ ? ` — every exit of ${via.platform} now rests, so ${via.platform} cools down as before`
+ : ` — every exit of ${via.platform} now rests`
+ : "") +
`.\n`,
);
if (rateLimited) {
@@ -808,17 +939,19 @@ async function listingFailedVia(
// callers (e.g. the quick availability check) that only need a one-shot fresh
// flat-playlist fetch and shouldn't have to fabricate a full RunYtdlpOpts.
// enumeratePlaylistUrls only reads channelConfig, paths.ytdlpBin, onLog and
-// signal — never mode/tracker — so the cast is safe.
+// signal — never mode/tracker — so the cast is safe. `listingRoute` pins the
+// network route across several calls of one job (default: this call alone).
export async function fetchFlatPlaylistUrls(opts: {
channelConfig: ChannelConfig;
paths: Paths;
channelSlug: string;
onLog: (s: string) => void;
signal: AbortSignal;
+ listingRoute?: { route?: ListingRoute };
}): Promise<string[]> {
const root = path.join(opts.paths.channelsDir, opts.channelSlug);
return enumeratePlaylistUrls(
- { ...opts, mode: "store-playlist" } as RunYtdlpOpts,
+ { ...opts, mode: "store-playlist", listingRoute: opts.listingRoute ?? {} } as RunYtdlpOpts,
root,
);
}
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -2,18 +2,23 @@
## [Unreleased]
- **Network exits (trial): rumble and twitch listings through named proxies.**
- - New `settings.network`: exits `{id, label, proxy, enabled}` (`socks5h://`, `socks5://`, `http://`, `https://`), a
- policy per platform, and cookie-jar pins. Absent = every request direct, exactly as before.
+ - New `settings.network`: exits `{id, label, scheme, host, port, credentials, enabled}` (`socks5h`, `socks5`,
+ `http`, `https`), a policy per platform, cookie-jar pins, `credentialsFile` and `startupProbe`. Absent = every
+ request direct, exactly as before.
+ - Credentials are never a setting: they are read from `NETWORK_EXIT_<ID>` in the environment or the mode-600
+ `credentialsFile`, percent-encoded. A proxy URL with credentials in it is refused.
- The trial routes only the listing requests of rumble and twitch. Any other platform or request kind, and any cookie jar
- given an exit, is refused when saved.
- - A channel's exit is a stable hash of its slug, recorded in `channels/<slug>/network-exit.json`. It changes only when
- that exit is removed or disabled, or by `pnpm ops network-exit`. A listing that carries a login stays direct.
+ given an exit, is refused when saved. A listing that carries a login stays direct — so Rumble channels with the
+ browser clearance cookie (the default) stay direct.
+ - A channel's exit is a stable hash of its slug, recorded on its first listing. Only `pnpm ops network-exit` moves it;
+ a disabled or removed recorded exit fails the listing. One job keeps one exit for all its pages.
- Pacing is unchanged: gaps, pace, cooldowns and holds count every exit together. A 429 or bot check through an exit
rests that exit, and its channels wait (the sync ends deferred). The platform cools down only when every exit rests.
- - A proxy that does not answer fails the listing and names the exit. It never falls back to direct. Proxy credentials
- are never shown, logged or recorded; yt-dlp gets the URL on its stdin.
- - `pnpm ops network`, `pnpm ops network-exit`, `pnpm ops get network [--probe]`, and /settings → Network exits. Not a
- disguise: no fingerprint or user-agent changes.
+ - 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.
+ - `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.**
- A cut made from two recordings of one channel showed two names for it, the older record's uploader name and
the current one. Before, the only fix was to hand-edit `channelTitle` on every clip.
diff --git a/editor/app/api/ops/_read.ts b/editor/app/api/ops/_read.ts
@@ -1,7 +1,6 @@
import { NextResponse } from "next/server";
import { opsAuth, opsFail } from "./_lib";
import { withAttention } from "./_attention";
-import { redactUrlUserinfo } from "yt-dlp-transcript-common/lib/networkExits";
// THE READ SIDE'S DOOR (release 19, A3): `GET /api/ops/<noun>` routes that
// answer what an existing builder already builds for a page — settings, the
@@ -43,13 +42,8 @@ export async function readRoute(
// "<redacted>" ("" stays "", so "unset" still reads as unset).
const SECRET_KEY = /token|secret|password|passwd|api[-_]?key|credential/i;
-//
-// AND A URL'S CREDENTIALS, under any key (a network exit's `proxy`,
-// lib/networkExits.ts): `scheme://user:pass@host` answers as
-// `scheme://<redacted>@host`, so the host still reads.
export function redactSecrets<T>(value: T): T {
if (Array.isArray(value)) return value.map(redactSecrets) as T;
- if (typeof value === "string") return redactUrlUserinfo(value) as T;
if (typeof value !== "object" || value === null) return value;
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
diff --git a/editor/app/api/ops/network/route.ts b/editor/app/api/ops/network/route.ts
@@ -12,25 +12,29 @@ export const dynamic = "force-dynamic";
// NAMED NETWORK EXITS (lane network-exits; common/lib/networkExits.ts).
//
// GET /api/ops/network[?probe=1]
-// -> { ok, network: { limits, trialScope, exits: [{id, label, proxy (masked),
-// enabled, probe}], platforms: {<p>: {exits, mode, kinds, pool, allRest}
+// -> { ok, network: { limits, trialScope, exits: [{id, label, display, scheme,
+// host, port, credentials, enabled, probe, channels}], platforms: {<p>: {exits, mode, kinds, pool, allRest}
// | {…, ignored}}, jars, echoUrl, rests: [{platform, exit, until, fails}],
// usage: {"1d": {"<platform>/<exit>": {requests, rateLimits, botChecks,
// rests, proxyFailures}}, "7d": …}, lastProbeAt } }
-// Reads files only. `probe=1` first asks each enabled exit's proxy to answer
-// (connect + SOCKS greeting/login; no destination) and, only when
-// network.echoUrl is set, fetches it through each exit and once direct to
-// name the address each presents.
+// Reads files only; no field holds a secret (credentials live in
+// network.credentialsFile). `probe=1` — the operator's explicit probe —
+// first asks each enabled exit's proxy to answer (connect + SOCKS
+// greeting/login; no destination) and, only when network.echoUrl is set,
+// fetches it through each exit and once direct to name the address each
+// presents.
//
-// POST { exits? | upsertExit? | removeExit? | platforms? | jars? | echoUrl? }
-// -> { ok, network: <the saved block, proxies masked> }
+// POST { exits? | upsertExit? | removeExit? | platforms? | jars? | echoUrl? |
+// credentialsFile? | startupProbe? }
+// -> { ok, network: <the saved block> }
// One write through the network writer (settings/networkSave.ts): refused
// whole, every problem named, when it routes anything outside the trial
-// (rumble and twitch listings) or gives a cookie jar an exit.
+// (rumble and twitch listings), gives a cookie jar an exit, or sends a
+// proxy URL with credentials in it.
export async function GET(request: Request) {
return readRoute(request, ["probe"], async (q) => {
const paths = getPaths();
- if (q.get("probe") === "1") await probeNetworkExits(paths, undefined, new Date(), { getDirect: directEcho });
+ if (q.get("probe") === "1") await probeNetworkExits(paths, undefined, new Date(), { explicit: true, getDirect: directEcho });
return { network: redactSecrets(await networkReport(paths)) };
});
}
diff --git a/editor/app/settings/components/NetworkExitsSection.tsx b/editor/app/settings/components/NetworkExitsSection.tsx
@@ -6,9 +6,12 @@
// Remove network {"removeExit": "<id>"}
// a platform's Save / Clear network {"platforms": {"<p>": {...} | null}}
// Echo URL Save network {"echoUrl": "..."}
+// Startup probe on / off network {"startupProbe": true | false}
// Probe exits get network --probe
// Assign network-exit {"slug", "exit"}
-// Proxies arrive masked; a masked proxy saved back keeps its credentials.
+// No proxy credentials ever reach this page: an exit is scheme, host, port
+// and "credentials: yes/no"; the user and password live in the key file
+// network.credentialsFile names (one NETWORK_EXIT_<ID>=user:password line).
import { useState, useTransition } from "react";
import {
@@ -33,7 +36,7 @@ export function NetworkExitsSection({ initial }: { initial: NetworkReport }) {
const [report, setReport] = useState(initial);
const [error, setError] = useState<string | null>(null);
const [pending, start] = useTransition();
- const [draft, setDraft] = useState({ id: "", label: "", proxy: "" });
+ const [draft, setDraft] = useState({ id: "", label: "", proxy: "", credentials: false });
const [echoUrl, setEchoUrl] = useState(initial.echoUrl);
const [assign, setAssign] = useState({ slug: "", exit: "direct" });
const exits = report.exits.filter((e) => e.id !== "direct");
@@ -83,7 +86,10 @@ export function NetworkExitsSection({ initial }: { initial: NetworkReport }) {
{e.label !== e.id && <span className="text-muted-foreground"> {e.label}</span>}
{!e.enabled && <span className="text-muted-foreground"> (disabled)</span>}
</td>
- <td className="py-1 pr-3 font-mono text-xs break-all">{e.proxy ?? "none"}</td>
+ <td className="py-1 pr-3 font-mono text-xs break-all">
+ {e.display}
+ {e.channels > 0 && <span className="text-muted-foreground"> · {e.channels} channel{e.channels === 1 ? "" : "s"}</span>}
+ </td>
<td className="py-1 pr-3 text-xs">{probeText(e.probe)}</td>
<td className="py-1 whitespace-nowrap">
{e.id !== "direct" && (
@@ -100,7 +106,9 @@ export function NetworkExitsSection({ initial }: { initial: NetworkReport }) {
type="button"
className={BUTTON}
disabled={pending}
- onClick={() => setDraft({ id: e.id, label: e.label, proxy: e.proxy ?? "" })}
+ onClick={() =>
+ setDraft({ id: e.id, label: e.label, proxy: `${e.scheme}://${e.host}:${e.port}`, credentials: e.credentials })
+ }
>
Edit
</button>
@@ -119,7 +127,14 @@ export function NetworkExitsSection({ initial }: { initial: NetworkReport }) {
className="flex flex-wrap items-end gap-2"
onSubmit={(ev) => {
ev.preventDefault();
- save({ upsertExit: { id: draft.id.trim(), label: draft.label.trim() || draft.id.trim(), proxy: draft.proxy.trim() } });
+ save({
+ upsertExit: {
+ id: draft.id.trim(),
+ label: draft.label.trim() || draft.id.trim(),
+ proxy: draft.proxy.trim(),
+ credentials: draft.credentials,
+ },
+ });
}}
>
<label className="flex flex-col text-xs">
@@ -136,11 +151,19 @@ export function NetworkExitsSection({ initial }: { initial: NetworkReport }) {
className={`${INPUT} font-mono`}
value={draft.proxy}
onChange={(e) => setDraft({ ...draft, proxy: e.target.value })}
- placeholder="socks5h://host:1080"
+ placeholder="socks5h://host:1080 (no credentials)"
autoComplete="off"
spellCheck={false}
/>
</label>
+ <label className="flex items-center gap-1 text-xs">
+ <input
+ type="checkbox"
+ checked={draft.credentials}
+ onChange={(e) => setDraft({ ...draft, credentials: e.target.checked })}
+ />
+ Credentials (in the key file)
+ </label>
<button type="submit" className={BUTTON} disabled={pending || !draft.id.trim() || !draft.proxy.trim()}>
Save exit
</button>
@@ -210,7 +233,25 @@ export function NetworkExitsSection({ initial }: { initial: NetworkReport }) {
<button type="button" className={BUTTON} disabled={pending} onClick={() => run(() => probeNetworkAction())}>
Probe exits
</button>
+ <label className="flex items-center gap-1 text-xs">
+ <input
+ type="checkbox"
+ disabled={pending}
+ checked={report.startupProbe}
+ onChange={(e) => save({ startupProbe: e.target.checked })}
+ />
+ Connect to each proxy at startup
+ </label>
</div>
+ <p className="text-xs text-muted-foreground">
+ Credentials: <span className="font-mono">{report.credentialsFile}</span> (mode 600), one{" "}
+ <span className="font-mono">NETWORK_EXIT_<ID>=user:password</span> line per exit, percent-encoded.
+ </p>
+ {report.settingsProblem && (
+ <p role="alert" className="text-xs text-destructive">
+ {report.settingsProblem}
+ </p>
+ )}
{report.rests.length > 0 && (
<ul className="text-xs" aria-label="resting exits">
diff --git a/editor/app/settings/networkActions.ts b/editor/app/settings/networkActions.ts
@@ -2,7 +2,8 @@
// /settings → Network exits (lane network-exits). Each action is the twin of a
// `pnpm ops` call: save → `pnpm ops network`, assign → `pnpm ops network-exit`,
-// probe → `pnpm ops get network --probe`. Every answer is masked.
+// probe → `pnpm ops get network --probe`. No answer holds a secret: the
+// settings never do (credentials live in network.credentialsFile).
import { revalidatePath } from "next/cache";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
@@ -13,7 +14,6 @@ import {
probeNetworkExits,
type NetworkReportView,
} from "yt-dlp-transcript-common/controller/networkExits";
-import { redactUrlUserinfo } from "yt-dlp-transcript-common/lib/networkExits";
import { NetworkSaveError, saveNetworkRequest } from "./networkSave";
import { directEcho } from "./networkProbe";
@@ -21,12 +21,13 @@ export type NetworkReport = NetworkReportView;
type Answer = { ok: true; report: NetworkReport } | { ok: false; error: string };
async function report(): Promise<NetworkReport> {
- return JSON.parse(redactUrlUserinfo(JSON.stringify(await networkReport(getPaths())))) as NetworkReport;
+ // Built from the stored, secret-free form (controller/networkExits.ts).
+ return networkReport(getPaths());
}
function refusal(e: unknown): { ok: false; error: string } {
if (e instanceof NetworkSaveError || e instanceof NetworkInputError) return { ok: false, error: e.message };
- return { ok: false, error: redactUrlUserinfo((e as Error).message ?? String(e)) };
+ return { ok: false, error: (e as Error).message ?? String(e) };
}
export async function networkReportAction(): Promise<NetworkReport> {
@@ -54,7 +55,7 @@ export async function assignChannelExitAction(slug: string, exit: string): Promi
export async function probeNetworkAction(): Promise<Answer> {
try {
- await probeNetworkExits(getPaths(), undefined, new Date(), { getDirect: directEcho });
+ await probeNetworkExits(getPaths(), undefined, new Date(), { explicit: true, getDirect: directEcho });
return { ok: true, report: await report() };
} catch (e) {
return refusal(e);
diff --git a/editor/app/settings/networkSave.test.ts b/editor/app/settings/networkSave.test.ts
@@ -8,9 +8,11 @@ import assert from "node:assert/strict";
// Run with: pnpm -C editor exec tsx --test app/settings/networkSave.test.ts
//
// THE NETWORK EXITS' ONE WRITER (lane network-exits): what `pnpm ops network`
-// and /settings → Network exits save, what they refuse, and that a proxy's
-// credentials never come back out. getPaths() memoizes, so SETTINGS_FILE is
-// set before the module under test is imported.
+// and /settings → Network exits save and refuse. Review 1, finding 1: a
+// proxy's credentials are never a setting — a URL carrying them is refused
+// (with how to percent-encode, and where the key file is), and every answer
+// is built from the stored, secret-free form. getPaths() memoizes, so
+// SETTINGS_FILE is set before the module under test is imported.
const ROOT = mkdtempSync(path.join(os.tmpdir(), "network-save-"));
process.env.TRANSCRIPTS_DIR = ROOT;
@@ -26,24 +28,31 @@ const { settingsPatchProblem, OWNED_KEYS } = await import("../api/ops/settings/p
after(() => rm(ROOT, { recursive: true, force: true }));
const SECRET = "pw-not-for-logs";
-const PROXY = `socks5h://user-one:${SECRET}@exit-a.example.test:1080`;
-test("an exit and a rumble listing policy save; the answer is masked", async () => {
- const a = await saveNetworkRequest({ upsertExit: { id: "exit-a", proxy: PROXY } });
- assert.equal(a.exits[0]!.proxy, "socks5h://<redacted>@exit-a.example.test:1080");
+test("an exit and a rumble listing policy save; credentials are a yes/no", async () => {
+ const a = await saveNetworkRequest({ upsertExit: { id: "exit-a", proxy: "socks5h://exit-a.example.test:1080", credentials: true } });
+ assert.deepEqual(a.exits[0], { id: "exit-a", label: "exit-a", scheme: "socks5h", host: "exit-a.example.test", port: 1080, credentials: true, enabled: true });
await saveNetworkRequest({ upsertExit: { id: "exit-b", proxy: "socks5h://exit-b.example.test:1080" } });
const b = await saveNetworkRequest({ platforms: { rumble: { exits: ["direct", "exit-a", "exit-b"], mode: "sticky" } } });
assert.deepEqual(b.platforms.rumble, { exits: ["direct", "exit-a", "exit-b"], mode: "sticky", kinds: ["listing"] });
- // Stored whole (the file has the credentials; nothing else does).
- assert.equal(getSettings().network.exits[0]!.proxy, PROXY);
- assert.ok(!JSON.stringify(b).includes(SECRET));
});
-test("a masked proxy sent back keeps the stored credentials", async () => {
- const shown = (await saveNetworkRequest({ upsertExit: { id: "exit-a", label: "Amsterdam" } })).exits[0]!;
- await saveNetworkRequest({ exits: [{ ...shown }, ...getSettings().network.exits.slice(1)] });
- assert.equal(getSettings().network.exits[0]!.proxy, PROXY);
- assert.equal(getSettings().network.exits[0]!.label, "Amsterdam");
+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`,
+ ]) {
+ 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));
+ return true;
+ });
+ }
+ assert.equal(readFileSync(process.env.SETTINGS_FILE!, "utf8"), before, "nothing written");
+ assert.ok(!before.includes(SECRET));
});
test("out-of-scope platforms and kinds, and jar assignments, are refused whole with the trial's sentence", async () => {
@@ -53,12 +62,11 @@ 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/],
- [{ upsertExit: { id: "exit-c", proxy: `ftp://u:${SECRET}@h:1` } }, /scheme must be/],
+ [{ credentialsFile: "a-pasted-secret" }, /credentialsFile: the PATH of the mode-600 file/],
] as const) {
await assert.rejects(saveNetworkRequest(body as Record<string, unknown>), (e: unknown) => {
assert.ok(e instanceof NetworkSaveError);
assert.match(e.message, re);
- assert.ok(!e.message.includes(SECRET));
return true;
});
}
@@ -67,21 +75,21 @@ test("out-of-scope platforms and kinds, and jar assignments, are refused whole w
test("the settings writer's floor refuses a raw out-of-scope network block too", async () => {
await assert.rejects(
- saveSettings({ network: { exits: [], platforms: { youtube: { exits: ["direct", "x"], mode: "sticky", kinds: ["listing"] } }, jars: {}, echoUrl: "" } }),
+ saveSettings({ network: { ...getSettings().network, platforms: { youtube: { exits: ["direct", "x"], mode: "sticky", kinds: ["listing"] } } } }),
/network: not saved — network\.platforms\.youtube: refused/,
);
});
-test("`pnpm ops settings` refuses the network key as owned; every ops answer masks a URL's credentials", () => {
+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({ network: getSettings().network, note: `via ${PROXY}` });
- assert.ok(!JSON.stringify(red).includes(SECRET));
- assert.equal(red.note, "via socks5h://<redacted>@exit-a.example.test:1080");
+ 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>" });
});
-test("removing an exit takes it out of every policy", async () => {
+test("removing an exit takes it out of every policy; the startup probe can be turned off", async () => {
const r = await saveNetworkRequest({ removeExit: "exit-a" });
assert.deepEqual(r.platforms.rumble!.exits, ["direct", "exit-b"]);
- assert.equal(r.exits.length, 1);
+ const off = await saveNetworkRequest({ startupProbe: false });
+ assert.equal(off.startupProbe, false);
});
diff --git a/editor/app/settings/networkSave.ts b/editor/app/settings/networkSave.ts
@@ -2,7 +2,6 @@ import { getSettings } from "yt-dlp-transcript-common/lib/settings";
import {
NetworkRequestError,
applyNetworkRequest,
- maskedNetwork,
networkSettingsProblems,
sanitizeNetwork,
type NetworkSettings,
@@ -13,7 +12,9 @@ import { saveSettingsHeld, withSettingsLock } from "./saveSettings";
// /settings → Network exits both send a request here. Applied to the stored
// block (a masked proxy keeps its stored credentials), refused whole with
// every problem named when the result is outside the trial
-// (networkSettingsProblems), then saved. Answers the saved block MASKED.
+// (networkSettingsProblems), then saved. The block holds no secret (review 1,
+// finding 1: credentials live in network.credentialsFile), so the answer is
+// the saved block as it is.
//
// Not a "use server" module: the ops route and networkActions.ts call it.
export class NetworkSaveError extends Error {}
@@ -30,6 +31,6 @@ export async function saveNetworkRequest(body: Record<string, unknown>): Promise
const problems = networkSettingsProblems(next);
if (problems.length) throw new NetworkSaveError(`not saved — ${problems.join("; ")}`);
await saveSettingsHeld({ network: sanitizeNetwork(next) });
- return maskedNetwork(getSettings().network);
+ return getSettings().network;
});
}
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -71,6 +71,7 @@
// pnpm ops live-clip --json '{"slug":"demo-yt","id":"<videoId>","start":3605,"end":3660}' --wait
// pnpm ops network --json '{"upsertExit":{"id":"exit-a","proxy":"socks5h://nl-ams-wg-socks5-001.relays.mullvad.net:1080"}}'
// pnpm ops network --json '{"platforms":{"rumble":{"exits":["direct","exit-a","exit-b"],"mode":"sticky"}}}'
+// pnpm ops network --json '{"startupProbe":false}'
// pnpm ops network-exit --json '{"slug":"demo-rumble","exit":"exit-b"}'
// pnpm ops keep-videos --json '{"slug":"demo-rumble","ids":["v1abcde"],"note":"keep"}'
// pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","dryRun":true}'
@@ -1748,22 +1749,31 @@ export function usage() {
"",
'network writes the named network exits (settings.network) through their one',
' writer, as /settings → Network exits: {"upsertExit": {"id", "label"?,',
- ' "proxy"?, "enabled"?}}, {"removeExit": "<id>"} (also out of every policy),',
- ' {"exits": [...]} (the whole list), {"platforms": {"<platform>": {"exits":',
- ' [ids, "direct" allowed], "mode": "sticky"} | null}}, {"jars": {...}},',
- ' {"echoUrl": "<url>" | ""}. Proxy URLs: socks5h://, socks5://, http://,',
- ' https:// with a port; credentials are secrets, answered as <redacted>@,',
- ' and a masked proxy sent back keeps the stored one. 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 once; a listing that carries a login goes direct; a 429 or bot',
- ' check rests that exit (its channels wait); a proxy that does not answer',
- ' fails the listing naming the exit, never falling back to direct. Not a',
- ' disguise: no fingerprint or user-agent changes, and a login never moves.',
- ' get network [--probe] reports each exit, the rests and the 1- and 7-day',
- ' counts; --probe asks each proxy to answer (and fetches network.echoUrl',
- ' through it only when set).',
+ ' "proxy"?: "socks5h://host:port", "credentials"?: true|false, "enabled"?}},',
+ ' {"removeExit": "<id>"} (also out of every policy), {"exits": [...]} (the',
+ ' whole list, stored form {id, label, scheme, host, port, credentials,',
+ ' enabled}), {"platforms": {"<platform>": {"exits": [ids, "direct" allowed],',
+ ' "mode": "sticky"} | null}}, {"jars": {...}}, {"echoUrl": "<url>" | ""},',
+ ' {"credentialsFile": "<path>"}, {"startupProbe": true|false}. CREDENTIALS',
+ ' ARE NEVER A SETTING: a proxy URL with user:password in it is refused; give',
+ ' the exit "credentials": true and put NETWORK_EXIT_<ID>=user:password',
+ ' (percent-encoded) in the mode-600 file network.credentialsFile names',
+ ' (default ~/.config/archilyzer/network-exits.env), or in the environment.',
+ ' THE TRIAL routes only rumble and twitch LISTINGS: any other platform or',
+ ' request kind, and any cookie jar given an exit, is refused whole, every',
+ ' problem named. A channel\'s exit is a stable hash of its slug over the',
+ ' enabled exits, recorded on its first listing; a recorded exit that is',
+ ' disabled or removed FAILS that channel\'s listings until network-exit',
+ ' moves it. 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).',
"",
'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',
diff --git a/settings.json.example b/settings.json.example
@@ -31,7 +31,9 @@
"exits": [],
"platforms": {},
"jars": {},
- "echoUrl": ""
+ "echoUrl": "",
+ "credentialsFile": "~/.config/archilyzer/network-exits.env",
+ "startupProbe": true
},
"downloadFormat": "auto",
"sourceVideoQuality": "original",