commit 3be0f116f451b0977fcf0ff318f8a1476ba7dd7e
parent 25156ab10ca6c9fd32d7e8a54b00776a7bacd9cb
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 21 Nov 2026 13:00:46 -0500
common: named network exits — settings block, sticky choice, proxy client, listing routed through an exit
settings.network {exits, platforms, jars, echoUrl}: the trial routes only rumble and
twitch listings; a login is pinned direct. enumeratePlaylistUrls resolves the channel's
sticky exit (channels/<slug>/network-exit.json), refuses a resting exit as a deferral,
preflights the proxy (fail closed, never direct) and hands the URL to yt-dlp on stdin.
A rate limit through an exit rests that exit; the platform cools down only when every
exit rests. No policy = today's listing byte for byte.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
15 files changed, 2250 insertions(+), 26 deletions(-)
diff --git a/common/controller/networkExits.ts b/common/controller/networkExits.ts
@@ -0,0 +1,553 @@
+// NETWORK EXITS AT RUN TIME (lane network-exits): which exit a channel's
+// listing leaves through, the exits that rest after a rate limit, the counts
+// the trial is judged by, the operator's reassignment and `get network`.
+// The rules and the pure parts are lib/networkExits.ts; the proxy client is
+// lib/networkProxy-server.ts; the one caller that sends requests is the
+// listing in ytdlp/runYtdlp.ts.
+//
+// STATE, all small JSON:
+// channels/<slug>/network-exit.json the channel's sticky exit (who chose it, when)
+// <transcripts>/.network/rests.json per `<platform>/<exit>`: until, fails
+// <transcripts>/.network/usage.json per day per `<platform>/<exit>`: counts
+// <transcripts>/.network/probe.json the last probe's answer per exit
+// None of them ever holds a proxy URL — only exit ids.
+
+import path from "node:path";
+import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../lib/jsonFile-server";
+import type { Paths } from "../lib/paths";
+import { getSettings } from "../lib/settings";
+import { detectPlatform } from "../lib/platform";
+import {
+ DIRECT_EXIT,
+ TRIAL_SCOPE,
+ TRIAL_SCOPE_SENTENCE,
+ exitById,
+ exitPool,
+ isRoutable,
+ maskProxyUrl,
+ requestJar,
+ stickyExitFor,
+ type NetworkExit,
+ type NetworkSettings,
+} from "../lib/networkExits";
+import { getThroughProxy, addressInEcho, preflightProxy } from "../lib/networkProxy-server";
+import { nextBackoff, pruneExpired, type PlatformBackoffEntry } from "../jobs/platformBackoff";
+import { platformCooldownRemainingMs } from "../jobs/downloadBackoff";
+import { readChannelConfig } from "./channels";
+
+export const NETWORK_STATE_DIRNAME = ".network";
+export const CHANNEL_EXIT_FILENAME = "network-exit.json";
+
+export const NETWORK_LIMITS_SENTENCE =
+ "Network exits spread logged-out listing load across addresses and let the archive list a site that does " +
+ "not answer the home address. They are not a disguise: no fingerprint or user-agent spoofing is added, and " +
+ "a login is never moved between addresses.";
+
+export function networkStateDir(paths: Paths): string {
+ return path.join(paths.transcriptsDir, NETWORK_STATE_DIRNAME);
+}
+
+function stateFile(paths: Paths, name: string): string {
+ return path.join(networkStateDir(paths), name);
+}
+
+export function channelExitPath(paths: Paths, slug: string): string {
+ return path.join(paths.channelsDir, slug, CHANNEL_EXIT_FILENAME);
+}
+
+function settingsNetwork(): NetworkSettings | undefined {
+ try {
+ return getSettings().network;
+ } catch {
+ return undefined;
+ }
+}
+
+function isObject(v: unknown): v is Record<string, unknown> {
+ return typeof v === "object" && v !== null && !Array.isArray(v);
+}
+
+const key = (platform: string, exit: string) => `${platform}/${exit}`;
+
+// ---------------------------------------------------------------------------
+// THE CHANNEL'S STICKY EXIT
+
+export type ChannelExitRecord = {
+ platform: string;
+ exit: string;
+ // "hash": stickyExitFor chose it; "operator": `pnpm ops network-exit`.
+ by: "hash" | "operator";
+ at: string;
+ previous?: string;
+ reason?: string;
+};
+
+export async function readChannelExitRecord(
+ paths: Paths,
+ slug: string,
+): Promise<ChannelExitRecord | null> {
+ const r = await readJsonFile(channelExitPath(paths, slug));
+ if (!r.ok || !isObject(r.value)) return null;
+ const v = r.value;
+ if (typeof v.platform !== "string" || typeof v.exit !== "string") return null;
+ return {
+ platform: v.platform,
+ exit: v.exit,
+ by: v.by === "operator" ? "operator" : "hash",
+ at: typeof v.at === "string" ? v.at : "",
+ ...(typeof v.previous === "string" ? { previous: v.previous } : {}),
+ ...(typeof v.reason === "string" ? { reason: v.reason } : {}),
+ };
+}
+
+// The 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.
+async function stickyChannelExit(
+ paths: Paths,
+ slug: string,
+ platform: string,
+ pool: readonly string[],
+ now: Date,
+): Promise<string> {
+ const file = channelExitPath(paths, slug);
+ return withJsonFileLock(file, async () => {
+ const rec = await readChannelExitRecord(paths, slug);
+ if (rec && rec.platform === platform) {
+ if (pool.includes(rec.exit)) return rec.exit;
+ if (rec.by === "operator" && rec.exit === DIRECT_EXIT) return rec.exit;
+ }
+ const exit = stickyExitFor(slug, pool);
+ const next: ChannelExitRecord = {
+ platform,
+ 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}`,
+ }
+ : {}),
+ };
+ await writeJsonAtomic(file, next, { mkdir: true });
+ return exit;
+ });
+}
+
+// ---------------------------------------------------------------------------
+// THE ROUTE OF ONE LISTING
+
+export type ListingRoute =
+ // No policy for the platform (or the kind is outside the trial, or the
+ // channel's own args carry a --proxy): today's request, untouched.
+ | { kind: "none" }
+ // Under a policy, and direct: a login is pinned, 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 };
+
+function hasOwnProxy(argv: readonly string[]): boolean {
+ for (const a of argv) {
+ if (a === "--") break;
+ if (a === "--proxy" || a.startsWith("--proxy=")) return true;
+ }
+ return false;
+}
+
+// THE JAR'S EXIT. The trial never routes a login: whatever settings.json
+// says (the writers refuse an assignment; a hand edit is ignored here), a
+// request carrying one goes direct. Widening this is one deliberate change.
+export const JAR_ROUTING_ALLOWED = false;
+export function jarExit(network: NetworkSettings | undefined, jar: string): string {
+ if (!JAR_ROUTING_ALLOWED) return DIRECT_EXIT;
+ return network?.jars[jar] ?? DIRECT_EXIT;
+}
+
+export async function resolveListingRoute(args: {
+ paths: Paths;
+ slug: string;
+ platform: string;
+ argv: readonly string[];
+ network?: NetworkSettings;
+ now?: Date;
+}): Promise<ListingRoute> {
+ const network = args.network ?? settingsNetwork();
+ 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 (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" };
+}
+
+// ---------------------------------------------------------------------------
+// RESTS
+
+type RestState = Record<string, PlatformBackoffEntry & { since: number }>;
+
+async function readRests(paths: Paths): Promise<RestState> {
+ const r = await readJsonFile(stateFile(paths, "rests.json"));
+ const out: RestState = {};
+ if (!r.ok || !isObject(r.value)) return out;
+ for (const [k, v] of Object.entries(r.value)) {
+ if (!isObject(v)) continue;
+ const until = Number(v.until);
+ const fails = Number(v.fails);
+ if (!Number.isFinite(until) || !Number.isFinite(fails)) continue;
+ out[k] = { until, fails, since: Number.isFinite(Number(v.since)) ? Number(v.since) : until };
+ }
+ return out;
+}
+
+export async function exitRestUntil(
+ paths: Paths,
+ platform: string,
+ exit: string,
+ now: number = Date.now(),
+): Promise<number | null> {
+ if (exit === DIRECT_EXIT) return null;
+ const e = (await readRests(paths))[key(platform, exit)];
+ return e && e.until > now ? e.until : null;
+}
+
+// A RATE LIMIT OR BOT CHECK THROUGH AN EXIT RESTS THAT EXIT for the
+// platform, on the platform cooldown's own curve (jobs/platformBackoff.ts
+// nextBackoff: 1 min doubling to 30, jittered). `allRest` — every exit of
+// the pool now rests (direct counting as resting while the platform cools
+// down) — is when the caller records the platform's own backoff, as today.
+export async function restExit(
+ paths: Paths,
+ platform: string,
+ exit: string,
+ pool: readonly string[],
+ now: number = Date.now(),
+ rand?: () => number,
+): Promise<{ until: number; allRest: boolean }> {
+ const file = stateFile(paths, "rests.json");
+ const until = await withJsonFileLock(file, async () => {
+ const rests = await readRests(paths);
+ pruneExpired(rests, now);
+ const prev = rests[key(platform, exit)];
+ const next = nextBackoff(prev, now, rand);
+ rests[key(platform, exit)] = { ...next, since: prev && prev.until > now ? prev.since : now };
+ await writeJsonAtomic(file, rests, { mkdir: true });
+ return next.until;
+ });
+ return { until, allRest: await allExitsRest(paths, platform, pool, now) };
+}
+
+export async function allExitsRest(
+ paths: Paths,
+ platform: string,
+ pool: readonly string[],
+ now: number = Date.now(),
+): Promise<boolean> {
+ if (pool.length === 0) return false;
+ const rests = await readRests(paths);
+ for (const exit of pool) {
+ if (exit === DIRECT_EXIT) {
+ const ms = await platformCooldownRemainingMs(platform, paths).catch(() => 0);
+ if (ms <= 0) return false;
+ continue;
+ }
+ const e = rests[key(platform, exit)];
+ if (!e || e.until <= now) return false;
+ }
+ return true;
+}
+
+// A clean listing through the exit forgets its rest (and its escalation).
+export async function clearExitRest(
+ paths: Paths,
+ platform: string,
+ exit: string,
+): Promise<void> {
+ const file = stateFile(paths, "rests.json");
+ await withJsonFileLock(file, async () => {
+ const rests = await readRests(paths);
+ if (!rests[key(platform, exit)]) return;
+ delete rests[key(platform, exit)];
+ await writeJsonAtomic(file, rests, { mkdir: true });
+ });
+}
+
+function clock(ms: number): string {
+ const d = new Date(ms);
+ return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
+}
+
+export function restingSentence(platform: string, exit: string, until: number): string {
+ return (
+ `${platform} exit "${exit}" rests until ${clock(until)} after a rate limit; this channel's listing waits ` +
+ `for it (a channel never moves to another exit on a failure).`
+ );
+}
+
+// The manual Sync gate's notice: the channel's recorded exit rests. Reads
+// only — never chooses or writes an exit.
+export async function listingRestRefusal(
+ paths: Paths,
+ slug: string,
+ url: string | undefined,
+ network: NetworkSettings | undefined = settingsNetwork(),
+ now: number = Date.now(),
+): Promise<{ sentence: string; until: number } | null> {
+ const platform = detectPlatform(url) ?? "unknown";
+ const pool = exitPool(network, platform, "listing");
+ if (!pool) return null;
+ const rec = await readChannelExitRecord(paths, slug);
+ if (!rec || rec.platform !== platform || rec.exit === DIRECT_EXIT || !pool.includes(rec.exit)) return null;
+ const until = await exitRestUntil(paths, platform, rec.exit, now);
+ return until ? { sentence: restingSentence(platform, rec.exit, until), until } : null;
+}
+
+// ---------------------------------------------------------------------------
+// USAGE — the numbers the trial compares against `direct`
+
+export type NetworkUsageCounts = {
+ requests: number;
+ rateLimits: number;
+ botChecks: number;
+ rests: number;
+ proxyFailures: number;
+};
+const COUNT_KEYS: readonly (keyof NetworkUsageCounts)[] = ["requests", "rateLimits", "botChecks", "rests", "proxyFailures"];
+const USAGE_KEEP_DAYS = 8;
+
+function zero(): NetworkUsageCounts {
+ return { requests: 0, rateLimits: 0, botChecks: 0, rests: 0, proxyFailures: 0 };
+}
+
+function dayOf(ms: number): string {
+ return new Date(ms).toISOString().slice(0, 10);
+}
+
+type UsageFile = { days: Record<string, Record<string, NetworkUsageCounts>> };
+
+async function readUsage(paths: Paths): Promise<UsageFile> {
+ const r = await readJsonFile(stateFile(paths, "usage.json"));
+ const out: UsageFile = { days: {} };
+ if (!r.ok || !isObject(r.value) || !isObject(r.value.days)) return out;
+ for (const [day, rows] of Object.entries(r.value.days)) {
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(day) || !isObject(rows)) continue;
+ out.days[day] = {};
+ for (const [k, v] of Object.entries(rows)) {
+ if (!isObject(v)) continue;
+ const c = zero();
+ for (const f of COUNT_KEYS) c[f] = Math.max(0, Math.floor(Number(v[f]) || 0));
+ out.days[day]![k] = c;
+ }
+ }
+ return out;
+}
+
+export async function countNetworkUse(
+ paths: Paths,
+ platform: string,
+ exit: string,
+ delta: Partial<NetworkUsageCounts>,
+ now: number = Date.now(),
+): Promise<void> {
+ const file = stateFile(paths, "usage.json");
+ await withJsonFileLock(file, async () => {
+ const usage = await readUsage(paths);
+ const day = dayOf(now);
+ const row = ((usage.days[day] ??= {})[key(platform, exit)] ??= zero());
+ for (const f of COUNT_KEYS) row[f] += delta[f] ?? 0;
+ const keep = new Set(Array.from({ length: USAGE_KEEP_DAYS }, (_, i) => dayOf(now - i * 86_400_000)));
+ for (const d of Object.keys(usage.days)) if (!keep.has(d)) delete usage.days[d];
+ await writeJsonAtomic(file, usage, { mkdir: true });
+ });
+}
+
+export async function usageOver(
+ paths: Paths,
+ days: number,
+ now: number = Date.now(),
+): Promise<Record<string, NetworkUsageCounts>> {
+ const usage = await readUsage(paths);
+ const out: Record<string, NetworkUsageCounts> = {};
+ for (let i = 0; i < days; i++) {
+ for (const [k, c] of Object.entries(usage.days[dayOf(now - i * 86_400_000)] ?? {})) {
+ const row = (out[k] ??= zero());
+ for (const f of COUNT_KEYS) row[f] += c[f];
+ }
+ }
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// THE OPERATOR'S REASSIGNMENT — `pnpm ops network-exit {slug, exit}`
+
+export class NetworkInputError extends Error {}
+
+export async function assignChannelExit(args: {
+ paths: Paths;
+ slug: string;
+ exit: string;
+ network?: NetworkSettings;
+ now?: Date;
+}): Promise<{ slug: string; platform: string; exit: string; previous: string | null }> {
+ const network = args.network ?? settingsNetwork();
+ const config = await readChannelConfig(args.paths, args.slug);
+ if (!config) throw new NetworkInputError(`Channel "${args.slug}" not found`);
+ const platform = detectPlatform(config.url) ?? config.platform ?? "unknown";
+ const pool = exitPool(network, platform, "listing");
+ if (pool === null) {
+ throw new NetworkInputError(
+ `"${args.slug}" is a ${platform} channel, and ${platform} has no network policy` +
+ (isRoutable(platform, "listing") ? " — set network.platforms." + platform + " first" : ` — ${TRIAL_SCOPE_SENTENCE}`),
+ );
+ }
+ if (args.exit !== DIRECT_EXIT && !pool.includes(args.exit)) {
+ const known = exitById(network, args.exit);
+ throw new NetworkInputError(
+ known
+ ? `exit "${args.exit}" is ${known.enabled ? `not in ${platform}'s policy` : "disabled"} — ${platform}'s enabled exits: ${pool.join(", ") || "none"}`
+ : `no exit "${args.exit}" — ${platform}'s enabled exits: ${pool.join(", ") || "none"} (and "direct")`,
+ );
+ }
+ const file = channelExitPath(args.paths, args.slug);
+ return withJsonFileLock(file, async () => {
+ const rec = await readChannelExitRecord(args.paths, args.slug);
+ const next: ChannelExitRecord = {
+ platform,
+ exit: args.exit,
+ by: "operator",
+ at: (args.now ?? new Date()).toISOString(),
+ ...(rec && rec.exit !== args.exit ? { previous: rec.exit, reason: "reassigned by the operator" } : {}),
+ };
+ await writeJsonAtomic(file, next, { mkdir: true });
+ return { slug: args.slug, platform, exit: args.exit, previous: rec?.exit ?? null };
+ });
+}
+
+// ---------------------------------------------------------------------------
+// THE PROBE AND THE REPORT — `pnpm ops get network [--probe]`
+
+export type ExitProbe = {
+ at: string;
+ reachable: boolean;
+ reason?: string;
+ ms?: number;
+ // The address the echo URL saw through this exit (only with echoUrl set).
+ address?: string | null;
+ echoError?: string;
+};
+
+type ProbeFile = { at: string; exits: Record<string, ExitProbe> };
+
+async function readProbe(paths: Paths): Promise<ProbeFile | null> {
+ const r = await readJsonFile(stateFile(paths, "probe.json"));
+ if (!r.ok || !isObject(r.value) || !isObject(r.value.exits)) return null;
+ return r.value as unknown as ProbeFile;
+}
+
+// EACH ENABLED EXIT'S PROXY is asked to answer (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.
+export async function probeNetworkExits(
+ paths: Paths,
+ network: NetworkSettings | undefined = settingsNetwork(),
+ now: Date = new Date(),
+ deps: {
+ preflight?: typeof preflightProxy;
+ get?: typeof getThroughProxy;
+ getDirect?: (url: string) => Promise<{ ok: true; body: string } | { ok: false; reason: string }>;
+ } = {},
+): Promise<ProbeFile> {
+ const preflight = deps.preflight ?? preflightProxy;
+ const get = deps.get ?? getThroughProxy;
+ const out: ProbeFile = { at: now.toISOString(), exits: {} };
+ for (const e of network?.exits ?? []) {
+ if (!e.enabled) continue;
+ const pf = await preflight(e.proxy);
+ 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 (r.ok) probe.address = addressInEcho(r.body);
+ else probe.echoError = r.reason;
+ }
+ out.exits[e.id] = probe;
+ }
+ if (network?.echoUrl && deps.getDirect) {
+ const r = await deps.getDirect(network.echoUrl);
+ out.exits[DIRECT_EXIT] = {
+ at: now.toISOString(),
+ reachable: true,
+ ...(r.ok ? { address: addressInEcho(r.body) } : { echoError: r.reason }),
+ };
+ }
+ await writeJsonAtomic(stateFile(paths, "probe.json"), out, { mkdir: true });
+ return out;
+}
+
+export async function networkReport(
+ paths: Paths,
+ network: NetworkSettings | undefined = settingsNetwork(),
+ now: number = Date.now(),
+): Promise<Record<string, unknown>> {
+ const rests = await readRests(paths);
+ const probe = await readProbe(paths);
+ const platforms: Record<string, unknown> = {};
+ for (const [platform, policy] of Object.entries(network?.platforms ?? {})) {
+ const pool = exitPool(network, platform, "listing");
+ platforms[platform] = {
+ ...policy,
+ ...(pool === null
+ ? { ignored: TRIAL_SCOPE_SENTENCE }
+ : { pool, allRest: await allExitsRest(paths, platform, pool, now) }),
+ };
+ }
+ 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 },
+ ...(network?.exits ?? []).map((e) => ({
+ id: e.id,
+ label: e.label,
+ proxy: maskProxyUrl(e.proxy),
+ enabled: e.enabled,
+ probe: probe?.exits[e.id] ?? null,
+ })),
+ ],
+ platforms,
+ jars: network?.jars ?? {},
+ echoUrl: network?.echoUrl ?? "",
+ rests: Object.entries(rests)
+ .filter(([, e]) => e.until > now)
+ .map(([k, e]) => {
+ const [platform, exit] = k.split("/");
+ return { platform, exit, until: new Date(e.until).toISOString(), fails: e.fails };
+ }),
+ usage: { "1d": await usageOver(paths, 1, now), "7d": await usageOver(paths, 7, now) },
+ lastProbeAt: probe?.at ?? null,
+ };
+}
+
+// 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.
+export function listingPool(network: NetworkSettings | undefined, platform: string): string[] | null {
+ return exitPool(network ?? settingsNetwork(), platform, "listing");
+}
+
+export { TRIAL_SCOPE };
diff --git a/common/controller/rosterStore.ts b/common/controller/rosterStore.ts
@@ -47,6 +47,9 @@ export type RosterSweep = {
at: string;
listedCount: number;
verdict: SweepVerdict;
+ // The network exit the listing went through (controller/networkExits.ts),
+ // written only when the platform has a network policy; never a proxy URL.
+ exit?: string;
};
export type RosterEntry = {
@@ -230,6 +233,9 @@ export function normalizeRoster(value: unknown): Roster {
at: rawSweep.at,
listedCount: Math.max(0, Math.floor(rawSweep.listedCount)),
verdict: rawSweep.verdict,
+ ...(typeof rawSweep.exit === "string" && /^[a-z0-9][a-z0-9-]{0,39}$/.test(rawSweep.exit)
+ ? { exit: rawSweep.exit }
+ : {}),
}
: null;
diff --git a/common/controller/verifyBeforeClean.ts b/common/controller/verifyBeforeClean.ts
@@ -170,10 +170,14 @@ export async function verifyBeforeClean({
// A 429 on the listing (runYtdlp's EnumerationIncompleteError) is a rate
// limit: the platform's cooldown is recorded, as Sync records it, so the
// downloads and the retry of this clean both stay away for it.
+ // Through a network exit the exit rests instead, and the platform's
+ // cooldown is due only once every exit rests (platformBackoffDue).
if (err instanceof EnumerationIncompleteError) {
- await (probes?.recordBackoff ?? ((pf: string) => recordDownloadBackoff(pf, paths, "rate_limit")))(
- err.platform,
- ).catch(() => {});
+ if (err.platformBackoffDue) {
+ await (probes?.recordBackoff ?? ((pf: string) => recordDownloadBackoff(pf, paths, "rate_limit")))(
+ err.platform,
+ ).catch(() => {});
+ }
verdicts.stopped = { kind: "rate-limit", platform: err.platform, message: reason };
} else if (!signal?.aborted) {
verdicts.stopped = { kind: "error", platform, message: reason };
diff --git a/common/jobs/jobDeferred.ts b/common/jobs/jobDeferred.ts
@@ -0,0 +1,16 @@
+// A job its queue started that may not run yet — X's job cap, an exit that
+// rests after a rate limit (controller/networkExits.ts): it ends `done`,
+// DEFERRED, not failed (JobRecord.deferred), with the sentence and the time it
+// may run. The sync scheduler re-queues a deferred channel at `until`.
+//
+// Its own module so code below the job funnel (a yt-dlp listing) can throw it
+// without importing streamCommand, which re-exports it.
+export class JobDeferredError extends Error {
+ constructor(
+ message: string,
+ readonly until: number,
+ ) {
+ super(message);
+ this.name = "JobDeferredError";
+ }
+}
diff --git a/common/jobs/streamCommand.ts b/common/jobs/streamCommand.ts
@@ -36,6 +36,7 @@ import { runInJobContext, type JobContext } from "../lib/jobContext";
import { serviceStoppedLine } from "../lib/serviceCookies";
import { configuredCookieBrowser } from "../lib/serviceCookies-server";
import { claimResumeTag } from "./resumeTag";
+import { JobDeferredError } from "./jobDeferred";
// Mark a job's channel report dirty so the debounced scheduler regenerates the
// snapshot — called both on each completed sub-operation and on the job's
@@ -422,17 +423,10 @@ async function refuseForUnreachableMedia(
}
}
-// A job its queue started that may not run yet (X's job cap): it ends
-// deferred, not failed (JobRecord.deferred).
-export class JobDeferredError extends Error {
- constructor(
- message: string,
- readonly until: number,
- ) {
- super(message);
- this.name = "JobDeferredError";
- }
-}
+// A job its queue started that may not run yet (X's job cap, a resting
+// network exit): it ends deferred, not failed (JobRecord.deferred). The class
+// lives in ./jobDeferred so a listing below the funnel can throw it.
+export { JobDeferredError };
export async function runManagedFunction(
opts: RunManagedFunctionOpts,
diff --git a/common/lib/networkExits.test.ts b/common/lib/networkExits.test.ts
@@ -0,0 +1,187 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ DIRECT_EXIT,
+ NetworkRequestError,
+ applyNetworkRequest,
+ exitPool,
+ jarExitChangeRefusal,
+ maskProxyUrl,
+ maskedNetwork,
+ networkSettingsProblems,
+ parseProxyUrl,
+ proxyDisplay,
+ proxySecretFragments,
+ redactFragments,
+ redactUrlUserinfo,
+ requestJar,
+ sanitizeNetwork,
+ 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";
+
+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: "",
+ ...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("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("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("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("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("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", () => {
+ 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);
+});
+
+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"];
+ 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.
+ 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"));
+});
+
+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", () => {
+ 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 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"));
+});
diff --git a/common/lib/networkExits.ts b/common/lib/networkExits.ts
@@ -0,0 +1,559 @@
+// NAMED NETWORK EXITS (lane network-exits, 21 Nov 2026): proxies a fetch may
+// leave through, chosen per channel and kept, for the platforms and request
+// kinds the operator routes. Pure and client-safe: the types, the sanitizer,
+// the validator the writers refuse with, the sticky choice, the cookie-jar
+// classifier and the masking. State and the proxy client live in
+// controller/networkExits.ts and lib/networkProxy-server.ts.
+//
+// WHAT IT IS FOR, AND WHAT IT IS NOT. It spreads logged-out listing load over
+// several addresses, and lets the archive list a site that does not answer the
+// home address. It is not a disguise: no fingerprint or user-agent spoofing is
+// added, and a login (a cookie jar, a browser's cookies, a token) never moves
+// between addresses.
+//
+// THE RULES, each enforced where its comment says:
+// - `direct` (no proxy) always exists and is reserved.
+// - A policy per platform queue, `network.platforms.<p>`; absent = direct.
+// THE TRIAL routes only TRIAL_SCOPE (rumble and twitch listings); the
+// writers refuse anything else with TRIAL_SCOPE_SENTENCE, and the resolver
+// 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.
+
+import type { FieldDocs } from "./fieldDocs";
+
+export const DIRECT_EXIT = "direct";
+
+// The request kinds a policy may name. Only `listing` is routable in the
+// trial; the others are named so a refusal can say what was asked.
+export const NETWORK_REQUEST_KINDS = [
+ "listing",
+ "download",
+ "metadata",
+ "subtitles",
+ "clip",
+ "live",
+ "posts",
+] as const;
+export type NetworkRequestKind = (typeof NETWORK_REQUEST_KINDS)[number];
+
+export const NETWORK_POLICY_MODES = ["sticky"] as const;
+export type NetworkPolicyMode = (typeof NETWORK_POLICY_MODES)[number];
+
+export type NetworkExit = {
+ id: string;
+ label: string;
+ proxy: string;
+ enabled: boolean;
+};
+
+export type NetworkPlatformPolicy = {
+ exits: string[];
+ mode: NetworkPolicyMode;
+ kinds: NetworkRequestKind[];
+};
+
+export type NetworkSettings = {
+ exits: NetworkExit[];
+ platforms: Record<string, NetworkPlatformPolicy>;
+ jars: Record<string, string>;
+ echoUrl: string;
+};
+
+// THE TRIAL'S SCOPE — the one place it is widened, deliberately, later.
+export const TRIAL_SCOPE: Readonly<Record<string, readonly NetworkRequestKind[]>> = Object.freeze({
+ rumble: Object.freeze(["listing"] as NetworkRequestKind[]),
+ twitch: Object.freeze(["listing"] as NetworkRequestKind[]),
+});
+
+export const TRIAL_SCOPE_SENTENCE =
+ "the network-exit trial routes only the listing requests of rumble and twitch; every other " +
+ "platform and request kind goes direct (TRIAL_SCOPE in common/lib/networkExits.ts)";
+
+export const JAR_TRIAL_SENTENCE =
+ "a request that carries a login (a cookie jar, a browser's cookies, a token) goes direct in the " +
+ "network-exit trial — a login is never moved to another address";
+
+export function isRoutable(platform: string, kind: NetworkRequestKind): boolean {
+ return (TRIAL_SCOPE[platform] ?? []).includes(kind);
+}
+
+export const NETWORK_SETTINGS_FIELD_DOCS: FieldDocs<NetworkSettings> = {
+ exits:
+ "NAMED NETWORK EXITS: proxies a fetch may leave through, `[{id, label, 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.",
+};
+
+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.",
+ 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.",
+};
+
+export const NETWORK_PLATFORM_POLICY_FIELD_DOCS: FieldDocs<NetworkPlatformPolicy> = {
+ exits: "The exit ids the platform's channels are spread over, `direct` allowed. Disabled exits are skipped.",
+ mode: "`sticky` (the only mode): a channel keeps its exit; never chosen per request, never moved on a failure.",
+ kinds: "The request kinds routed (default `[\"listing\"]`). The trial allows `listing` only.",
+};
+
+export function defaultNetworkSettings(): NetworkSettings {
+ return { exits: [], platforms: {}, jars: {}, echoUrl: "" };
+}
+
+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];
+
+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;
+};
+
+// 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 } {
+ 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://" };
+ }
+ let u: URL;
+ try {
+ u = new URL(s);
+ } catch {
+ return { error: "the proxy URL does not parse" };
+ }
+ 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" };
+ }
+ let username = "";
+ let password = "";
+ try {
+ username = decodeURIComponent(u.username);
+ password = decodeURIComponent(u.password);
+ } catch {
+ return { error: "the proxy URL's credentials are not valid percent-encoding" };
+ }
+ 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);
+}
+
+// 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}`;
+}
+
+export function proxyHasCredentials(raw: string): boolean {
+ const p = parseProxyUrl(raw);
+ return !("error" in p) && (p.username !== "" || p.password !== "");
+}
+
+// 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 */
+ }
+ }
+ }
+ }
+ 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);
+}
+
+// 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;
+}
+
+// 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.
+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 platforms: Record<string, NetworkPlatformPolicy> = {};
+ if (isObject(r.platforms)) {
+ for (const [p, raw] of Object.entries(r.platforms)) {
+ if (!PLATFORM_KEY_RE.test(p) || !isObject(raw)) continue;
+ const ids = (Array.isArray(raw.exits) ? raw.exits : []).filter(
+ (x): x is string => typeof x === "string" && (x === DIRECT_EXIT || EXIT_ID_RE.test(x)),
+ );
+ const kinds = (Array.isArray(raw.kinds) ? raw.kinds : ["listing"]).filter(
+ (k): k is NetworkRequestKind => (NETWORK_REQUEST_KINDS as readonly unknown[]).includes(k),
+ );
+ if (ids.length === 0) continue;
+ platforms[p] = { exits: [...new Set(ids)], mode: "sticky", kinds: kinds.length ? [...new Set(kinds)] : ["listing"] };
+ }
+ }
+ const jars: Record<string, string> = {};
+ if (isObject(r.jars)) {
+ for (const [jar, exit] of Object.entries(r.jars)) {
+ if (jar.length === 0 || jar.length > 300 || typeof exit !== "string") continue;
+ if (exit !== DIRECT_EXIT && !EXIT_ID_RE.test(exit)) continue;
+ jars[jar] = exit;
+ }
+ }
+ const echoUrl = typeof r.echoUrl === "string" && validEchoUrl(r.echoUrl.trim()) ? r.echoUrl.trim() : "";
+ return { exits, platforms, jars, echoUrl };
+}
+
+function validEchoUrl(s: string): boolean {
+ if (s === "") return true;
+ try {
+ const u = new URL(s);
+ return (u.protocol === "http:" || u.protocol === "https:") && !u.username && !u.password;
+ } catch {
+ return false;
+ }
+}
+
+// THE STRICT CHECK every writer refuses with: one sentence per problem, each
+// naming its path. Never echoes a proxy URL.
+export function networkSettingsProblems(v: unknown): string[] {
+ const problems: string[] = [];
+ if (!isObject(v)) return ["network: must be an object {exits, platforms, jars, echoUrl}"];
+ 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)`);
+ }
+ 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}`);
+ 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)`);
+ }
+ 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);
+ }
+ 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 (v.platforms !== undefined && !isObject(v.platforms)) problems.push("network.platforms: must be an object keyed by platform");
+ for (const [platform, raw] of Object.entries(isObject(v.platforms) ? v.platforms : {})) {
+ const at = `network.platforms.${platform}`;
+ if (!isObject(raw)) {
+ problems.push(`${at}: must be {exits, mode: "sticky", kinds}`);
+ continue;
+ }
+ for (const k of Object.keys(raw)) {
+ if (!["exits", "mode", "kinds"].includes(k)) problems.push(`${at}.${k}: not a policy key (exits, mode, kinds)`);
+ }
+ const exits = Array.isArray(raw.exits) ? raw.exits : null;
+ const nonDirect = (exits ?? []).some((x) => x !== DIRECT_EXIT);
+ if (!(platform in TRIAL_SCOPE)) {
+ if (nonDirect || exits === null) problems.push(`${at}: refused — ${TRIAL_SCOPE_SENTENCE}`);
+ continue;
+ }
+ const kinds = raw.kinds === undefined ? ["listing"] : raw.kinds;
+ if (!Array.isArray(kinds) || kinds.length === 0) problems.push(`${at}.kinds: a non-empty list of request kinds`);
+ else {
+ for (const k of kinds) {
+ if (!(NETWORK_REQUEST_KINDS as readonly unknown[]).includes(k)) {
+ problems.push(`${at}.kinds: "${String(k)}" is not a request kind (${NETWORK_REQUEST_KINDS.join(", ")})`);
+ } else if (!isRoutable(platform, k as NetworkRequestKind) && nonDirect) {
+ problems.push(`${at}.kinds: "${String(k)}" refused — ${TRIAL_SCOPE_SENTENCE}`);
+ }
+ }
+ }
+ if (raw.mode !== undefined && raw.mode !== "sticky") {
+ problems.push(`${at}.mode: "sticky" is the only mode — a channel keeps its exit; exits are never chosen per request or at random`);
+ }
+ if (exits === null || exits.length === 0) {
+ problems.push(`${at}.exits: a non-empty list of exit ids ("direct" allowed)`);
+ continue;
+ }
+ const seen = new Set<unknown>();
+ for (const x of exits) {
+ if (seen.has(x)) problems.push(`${at}.exits: "${String(x)}" is listed twice`);
+ seen.add(x);
+ if (x === DIRECT_EXIT) continue;
+ if (typeof x !== "string" || !ids.has(x)) problems.push(`${at}.exits: "${String(x)}" is not a defined exit`);
+ }
+ }
+ if (v.jars !== undefined && !isObject(v.jars)) problems.push("network.jars: must be an object keyed by jar id");
+ for (const [jar, exit] of Object.entries(isObject(v.jars) ? v.jars : {})) {
+ if (exit === DIRECT_EXIT) continue;
+ problems.push(`network.jars.${jar}: refused — ${JAR_TRIAL_SENTENCE}`);
+ }
+ if (v.echoUrl !== undefined && (typeof v.echoUrl !== "string" || !validEchoUrl(v.echoUrl.trim()))) {
+ problems.push("network.echoUrl: blank, or an http(s) URL with no credentials");
+ }
+ return problems;
+}
+
+// FNV-1a, 32 bits, over the UTF-8 bytes: stable across processes, releases
+// and machines (never Math.random, never a per-process seed).
+export function stableHash(s: string): number {
+ let h = 0x811c9dc5;
+ for (const b of new TextEncoder().encode(s)) {
+ h ^= b;
+ h = Math.imul(h, 0x01000193) >>> 0;
+ }
+ return h >>> 0;
+}
+
+export function stickyExitFor(slug: string, pool: readonly string[]): string {
+ if (pool.length === 0) return DIRECT_EXIT;
+ return pool[stableHash(slug) % pool.length]!;
+}
+
+// The platform's pool for `kind`: its policy's exits that are enabled (direct
+// always is), in policy order; null = no policy (direct, no state read), and
+// for a platform or kind outside the trial's scope.
+export function exitPool(
+ network: NetworkSettings | undefined,
+ platform: string,
+ kind: NetworkRequestKind,
+): string[] | null {
+ const policy = network?.platforms?.[platform];
+ if (!policy || !isRoutable(platform, kind) || !policy.kinds.includes(kind)) return null;
+ const enabled = new Set(network!.exits.filter((e) => e.enabled).map((e) => e.id));
+ return policy.exits.filter((id) => id === DIRECT_EXIT || enabled.has(id));
+}
+
+export function exitById(network: NetworkSettings | undefined, id: string): NetworkExit | undefined {
+ return network?.exits.find((e) => e.id === id);
+}
+
+// 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.
+export function requestJar(argv: readonly string[]): string | null {
+ const valueOf = (i: number, opt: string): string | undefined => {
+ const a = argv[i]!;
+ if (a === opt) return argv[i + 1];
+ if (a.startsWith(`${opt}=`)) return a.slice(opt.length + 1);
+ return undefined;
+ };
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i]!;
+ if (a === "--") break;
+ const browser = valueOf(i, "--cookies-from-browser");
+ if (browser !== undefined) return `browser:${browser}`;
+ const file = valueOf(i, "--cookies");
+ if (file !== undefined && 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";
+ }
+ return null;
+}
+
+// A JAR NEVER USES TWO EXITS: changing a jar's exit while the jar is fresh
+// is refused (an account seen from two addresses invites a lock). Unused in
+// the trial, where every assignment is refused earlier; built so a later
+// widening cannot rotate a login by accident.
+export function jarExitChangeRefusal(args: {
+ jar: string;
+ from: string | undefined;
+ to: string;
+ jarFresh: boolean;
+}): string | null {
+ const from = args.from ?? DIRECT_EXIT;
+ if (from === args.to || !args.jarFresh) return null;
+ return (
+ `network.jars.${args.jar}: refused — the jar is fresh and has been used from "${from}"; an account seen ` +
+ `from two addresses invites a lock. Let the login expire (or log out) before giving it "${args.to}".`
+ );
+}
+
+// ---------------------------------------------------------------------------
+// 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
+// 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;
+
+export class NetworkRequestError extends Error {}
+
+export function applyNetworkRequest(current: NetworkSettings, body: Record<string, unknown>): Record<string, unknown> {
+ const unknown = Object.keys(body).filter((k) => !(NETWORK_REQUEST_KEYS as readonly string[]).includes(k));
+ if (unknown.length) {
+ throw new NetworkRequestError(`unknown key(s): ${unknown.join(", ")} — accepted: ${NETWORK_REQUEST_KEYS.join(", ")}`);
+ }
+ if (Object.keys(body).length === 0) throw new NetworkRequestError("nothing to change");
+ 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;
+ });
+ }
+ 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?}");
+ 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];
+ if (i >= 0) exits[i] = merged;
+ else exits.push(merged);
+ }
+ if (body.removeExit !== undefined) {
+ const id = body.removeExit;
+ if (typeof id !== "string" || !exits.some((e) => isObject(e) && e.id === id)) {
+ throw new NetworkRequestError(`removeExit: no exit "${String(id)}"`);
+ }
+ exits = exits.filter((e) => !(isObject(e) && e.id === id));
+ for (const [p, v] of Object.entries(platforms)) {
+ if (!isObject(v) || !Array.isArray(v.exits)) continue;
+ const left = v.exits.filter((x) => x !== id);
+ if (left.length) platforms[p] = { ...v, exits: left };
+ else delete platforms[p];
+ }
+ }
+ if (body.platforms !== undefined) {
+ if (!isObject(body.platforms)) throw new NetworkRequestError("platforms: must be an object keyed by platform");
+ platforms = { ...platforms };
+ for (const [p, v] of Object.entries(body.platforms)) {
+ if (v === null) delete platforms[p];
+ else platforms[p] = v;
+ }
+ }
+ return {
+ exits,
+ platforms,
+ jars: body.jars !== undefined ? body.jars : { ...current.jars },
+ echoUrl: body.echoUrl !== undefined ? body.echoUrl : current.echoUrl,
+ };
+}
+
+// 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.test.ts b/common/lib/networkProxy-server.test.ts
@@ -0,0 +1,92 @@
+import { test, after } from "node:test";
+import assert from "node:assert/strict";
+import {
+ addressInEcho,
+ getThroughProxy,
+ openTunnel,
+ preflightProxy,
+} from "./networkProxy-server";
+import {
+ closedPort,
+ startCountingServer,
+ startEchoServer,
+ startFakeHttpProxy,
+ startFakeSocks5,
+} from "../testing/fakeProxy";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/networkProxy-server.test.ts
+//
+// Every server is in this process, on 127.0.0.1. The destination names
+// (`echo.exit.test`) are never resolved here: a socks5h proxy is handed the
+// name, and the fake maps it to the loopback echo server.
+
+const echo = await startEchoServer("203.0.113.7\n");
+const direct = await startCountingServer();
+// The fakes tunnel to the echo server only; anything else is refused.
+const routeEcho = (host: string, port: number) =>
+ ["echo.exit.test", "127.0.0.1", "::1"].includes(host) && port === echo.port ? { host: "127.0.0.1", port } : null;
+const socksAuth = await startFakeSocks5({ username: "user-one", password: "pa:ss#word", route: routeEcho });
+const socksOpen = await startFakeSocks5({ route: routeEcho });
+const httpProxy = await startFakeHttpProxy({ auth: "user-one:pw", route: routeEcho });
+
+after(async () => {
+ await Promise.all([echo.close(), direct.close(), socksAuth.close(), socksOpen.close(), httpProxy.close()]);
+});
+
+const authUrl = `socks5h://user-one:${encodeURIComponent("pa:ss#word")}@127.0.0.1:${socksAuth.port}`;
+
+test("preflight: a SOCKS5 proxy that accepts the exit's login answers", async () => {
+ const r = await preflightProxy(authUrl);
+ assert.equal(r.ok, true);
+ assert.equal(socksAuth.connects.length, 0, "a preflight asks no destination");
+});
+
+test("preflight: wrong credentials and a dead proxy fail, never naming the password", async () => {
+ const bad = await preflightProxy(`socks5h://user-one:wrong-secret@127.0.0.1:${socksAuth.port}`);
+ assert.equal(bad.ok, false);
+ assert.match((bad as { reason: string }).reason, /refused the exit's username and password/);
+ assert.ok(!(bad as { reason: string }).reason.includes("wrong-secret"));
+ const dead = await preflightProxy(`socks5h://u:dead-secret@127.0.0.1:${await closedPort()}`);
+ assert.equal(dead.ok, false);
+ assert.equal((dead as { reason: string }).reason, "connection refused");
+ const noCreds = await preflightProxy(`socks5h://127.0.0.1:${socksAuth.port}`);
+ assert.equal(noCreds.ok, false);
+});
+
+test("socks5h hands the NAME to the proxy (DNS through the proxy)", async () => {
+ const before = socksAuth.connects.length;
+ const r = await getThroughProxy(authUrl, `http://echo.exit.test:${echo.port}/`);
+ assert.deepEqual(r, { ok: true, status: 200, body: "203.0.113.7\n" });
+ assert.deepEqual(socksAuth.connects[before], { atyp: "domain", host: "echo.exit.test", port: echo.port });
+});
+
+test("socks5 resolves here and sends an address", async () => {
+ const r = await getThroughProxy(`socks5://127.0.0.1:${socksOpen.port}`, `http://localhost:${echo.port}/`);
+ assert.equal(r.ok, true);
+ assert.notEqual(socksOpen.connects.at(-1)!.atyp, "domain");
+ assert.ok(["127.0.0.1", "::1"].includes(socksOpen.connects.at(-1)!.host));
+});
+
+test("an HTTP CONNECT proxy with Basic auth tunnels; a 407 is a refusal", async () => {
+ const ok = await getThroughProxy(`http://user-one:pw@127.0.0.1:${httpProxy.port}`, `http://echo.exit.test:${echo.port}/`);
+ assert.equal(ok.ok, true);
+ assert.equal(addressInEcho((ok as { body: string }).body), "203.0.113.7");
+ const no = await openTunnel(`http://user-one:nope@127.0.0.1:${httpProxy.port}`, "echo.exit.test", echo.port);
+ assert.equal(no.ok, false);
+ assert.match((no as { reason: string }).reason, /HTTP 407/);
+});
+
+test("a destination the proxy will not reach fails through the proxy — never direct", async () => {
+ const r = await openTunnel(authUrl, "127.0.0.1", direct.port);
+ assert.equal(r.ok, false);
+ assert.match((r as { reason: string }).reason, /could not reach the destination/);
+ assert.equal(direct.connections(), 0);
+});
+
+test("addressInEcho reads plain and JSON echo bodies", () => {
+ assert.equal(addressInEcho("198.51.100.4"), "198.51.100.4");
+ assert.equal(addressInEcho('{"ip":"198.51.100.4"}'), "198.51.100.4");
+ assert.equal(addressInEcho("2001:db8::1\n"), "2001:db8::1");
+ assert.equal(addressInEcho("nothing"), null);
+});
diff --git a/common/lib/networkProxy-server.ts b/common/lib/networkProxy-server.ts
@@ -0,0 +1,360 @@
+// THE PROXY CLIENT behind network exits (lib/networkExits.ts): a preflight
+// that proves an exit's proxy answers before anything is sent through it, and
+// a tunnelled GET for the operator's address-echo probe. SOCKS5 (with and
+// without username/password, `socks5h` handing the hostname to the proxy,
+// `socks5` resolving it here) and HTTP CONNECT over a plain or TLS connection
+// to the proxy. No dependency: the handshakes are a few bytes each.
+//
+// FAIL CLOSED. Every function here either succeeds through the proxy or
+// answers why not; none of them ever opens a connection to the target itself.
+// No error text carries the proxy's credentials.
+
+import net from "node:net";
+import tls from "node:tls";
+import dns from "node:dns/promises";
+import { parseProxyUrl, type ParsedProxy } from "./networkExits";
+
+export const PROXY_TIMEOUT_MS = 8_000;
+
+export type ProxyFailure = { ok: false; reason: string };
+
+class ProxyError extends Error {}
+
+function errText(err: unknown): string {
+ const e = err as NodeJS.ErrnoException;
+ if (e?.code === "ECONNREFUSED") return "connection refused";
+ if (e?.code === "ENOTFOUND" || e?.code === "EAI_AGAIN") return "its host does not resolve";
+ if (e?.code === "ETIMEDOUT") return "timed out";
+ if (e?.code === "ECONNRESET") return "the connection was reset";
+ return e instanceof ProxyError ? e.message : (e?.code ?? (e?.message || String(err)));
+}
+
+// A buffered reader over a socket: `read(n)` resolves with exactly n bytes,
+// `readUntil(sep)` with everything through the separator.
+function reader(sock: net.Socket) {
+ let buf = Buffer.alloc(0);
+ let waiter: (() => void) | null = null;
+ let failed: Error | null = null;
+ const wake = () => {
+ const w = waiter;
+ waiter = null;
+ w?.();
+ };
+ const onData = (c: Buffer) => {
+ buf = Buffer.concat([buf, c]);
+ wake();
+ };
+ const onEnd = () => {
+ failed = failed ?? new ProxyError("the proxy closed the connection");
+ wake();
+ };
+ const onError = (e: Error) => {
+ failed = e;
+ wake();
+ };
+ sock.on("data", onData);
+ sock.on("end", onEnd);
+ sock.on("close", onEnd);
+ sock.on("error", onError);
+ const wait = () => new Promise<void>((r) => (waiter = r));
+ return {
+ async read(n: number): Promise<Buffer> {
+ while (buf.length < n) {
+ if (failed) throw failed;
+ await wait();
+ }
+ const out = buf.subarray(0, n);
+ buf = buf.subarray(n);
+ return out;
+ },
+ async readUntil(sep: string, max = 64 * 1024): Promise<Buffer> {
+ for (;;) {
+ const i = buf.indexOf(sep);
+ if (i >= 0) {
+ const out = buf.subarray(0, i + sep.length);
+ buf = buf.subarray(i + sep.length);
+ return out;
+ }
+ if (buf.length > max) throw new ProxyError("the proxy's answer is too long");
+ if (failed) throw failed;
+ await wait();
+ }
+ },
+ async readAll(max = 64 * 1024): Promise<Buffer> {
+ while (!failed && buf.length <= max) await wait();
+ return buf.subarray(0, max);
+ },
+ // Hand the socket over: stop listening, give back what was read ahead.
+ release(): Buffer {
+ sock.off("data", onData);
+ sock.off("end", onEnd);
+ sock.off("close", onEnd);
+ sock.off("error", onError);
+ return buf;
+ },
+ };
+}
+
+function withTimeout<T>(p: Promise<T>, ms: number, sock: () => net.Socket | null, what: string): Promise<T> {
+ let t: NodeJS.Timeout;
+ return Promise.race([
+ p,
+ new Promise<T>((_, reject) => {
+ t = setTimeout(() => {
+ sock()?.destroy();
+ reject(new ProxyError(`${what} timed out after ${Math.round(ms / 1000)} s`));
+ }, ms);
+ }),
+ ]).finally(() => clearTimeout(t));
+}
+
+// The TCP (or, for an https:// proxy, TLS) connection to the proxy itself.
+function connectToProxy(p: ParsedProxy): Promise<net.Socket> {
+ return new Promise((resolve, reject) => {
+ const onErr = (e: Error) => reject(e);
+ if (p.scheme === "https") {
+ const s = tls.connect({ host: p.host, port: p.port, servername: net.isIP(p.host) ? undefined : p.host }, () => {
+ s.off("error", onErr);
+ resolve(s);
+ });
+ s.once("error", onErr);
+ } else {
+ const s = net.connect({ host: p.host, port: p.port }, () => {
+ s.off("error", onErr);
+ resolve(s);
+ });
+ s.once("error", onErr);
+ }
+ });
+}
+
+const SOCKS_REPLIES: Record<number, string> = {
+ 1: "general failure",
+ 2: "connection not allowed by its rules",
+ 3: "network unreachable",
+ 4: "host unreachable",
+ 5: "connection refused by the destination",
+ 6: "TTL expired",
+ 7: "command not supported",
+ 8: "address type not supported",
+};
+
+async function socksGreeting(sock: net.Socket, r: ReturnType<typeof reader>, p: ParsedProxy): Promise<void> {
+ const creds = p.username !== "" || p.password !== "";
+ sock.write(Buffer.from(creds ? [5, 2, 0, 2] : [5, 1, 0]));
+ const [ver, method] = await r.read(2);
+ if (ver !== 5) throw new ProxyError("it does not speak SOCKS5");
+ if (method === 0xff) throw new ProxyError("it accepts none of the offered login methods");
+ if (method === 2) {
+ if (!creds) throw new ProxyError("it wants a username and password, and the exit has none");
+ const u = Buffer.from(p.username, "utf8");
+ const pw = Buffer.from(p.password, "utf8");
+ if (u.length > 255 || pw.length > 255) throw new ProxyError("the exit's username or password is too long for SOCKS5");
+ sock.write(Buffer.concat([Buffer.from([1, u.length]), u, Buffer.from([pw.length]), pw]));
+ const [, status] = await r.read(2);
+ if (status !== 0) throw new ProxyError("it refused the exit's username and password");
+ } else if (method !== 0) {
+ throw new ProxyError("it chose a login method this client does not speak");
+ }
+}
+
+async function socksConnect(
+ sock: net.Socket,
+ r: ReturnType<typeof reader>,
+ p: ParsedProxy,
+ host: string,
+ port: number,
+): Promise<void> {
+ let addr: Buffer;
+ let target = host;
+ // socks5: the name is resolved HERE; socks5h: the proxy resolves it.
+ if (p.scheme === "socks5" && net.isIP(host) === 0) target = (await dns.lookup(host)).address;
+ const v = net.isIP(target);
+ if (v === 4) addr = Buffer.from([1, ...target.split(".").map(Number)]);
+ else if (v === 6) {
+ const full = expandIpv6(target);
+ addr = Buffer.concat([Buffer.from([4]), full]);
+ } else {
+ const name = Buffer.from(target, "utf8");
+ if (name.length > 255) throw new ProxyError("the destination's name is too long for SOCKS5");
+ addr = Buffer.concat([Buffer.from([3, name.length]), name]);
+ }
+ const portBuf = Buffer.from([(port >> 8) & 0xff, port & 0xff]);
+ sock.write(Buffer.concat([Buffer.from([5, 1, 0]), addr, portBuf]));
+ const [ver, rep, , atyp] = await r.read(4);
+ if (ver !== 5) throw new ProxyError("it answered the connect in something other than SOCKS5");
+ if (rep !== 0) throw new ProxyError(`it could not reach the destination (${SOCKS_REPLIES[rep!] ?? `reply ${rep}`})`);
+ const len = atyp === 1 ? 4 : atyp === 4 ? 16 : (await r.read(1))[0]!;
+ await r.read(len + 2);
+}
+
+function expandIpv6(ip: string): Buffer {
+ const [head, tail] = ip.split("::");
+ const h = head ? head.split(":") : [];
+ const t = tail !== undefined && tail !== "" ? tail.split(":") : [];
+ const groups = [...h, ...Array(8 - h.length - t.length).fill("0"), ...t];
+ const out = Buffer.alloc(16);
+ groups.forEach((g, i) => out.writeUInt16BE(parseInt(g || "0", 16), i * 2));
+ return out;
+}
+
+function basicAuth(p: ParsedProxy): string {
+ if (p.username === "" && p.password === "") return "";
+ return `Proxy-Authorization: Basic ${Buffer.from(`${p.username}:${p.password}`).toString("base64")}\r\n`;
+}
+
+async function httpConnect(sock: net.Socket, r: ReturnType<typeof reader>, p: ParsedProxy, host: string, port: number): Promise<void> {
+ const authority = net.isIP(host) === 6 ? `[${host}]:${port}` : `${host}:${port}`;
+ sock.write(`CONNECT ${authority} HTTP/1.1\r\nHost: ${authority}\r\n${basicAuth(p)}\r\n`);
+ const head = (await r.readUntil("\r\n\r\n")).toString("latin1");
+ const status = Number(/^HTTP\/1\.[01] (\d{3})/.exec(head)?.[1] ?? 0);
+ if (status === 407) throw new ProxyError("it refused the exit's credentials (HTTP 407)");
+ if (status !== 200) throw new ProxyError(`it refused the tunnel (HTTP ${status || "?"})`);
+}
+
+// A TUNNEL through the exit's proxy to host:port, or why not.
+export async function openTunnel(
+ proxyUrl: string,
+ host: string,
+ port: number,
+ timeoutMs = PROXY_TIMEOUT_MS,
+): Promise<{ ok: true; socket: net.Socket; head: Buffer } | ProxyFailure> {
+ const p = parseProxyUrl(proxyUrl);
+ if ("error" in p) return { ok: false, reason: p.error };
+ let sock: net.Socket | null = null;
+ try {
+ return await withTimeout(
+ (async () => {
+ sock = await connectToProxy(p);
+ const r = reader(sock);
+ if (p.scheme === "socks5" || p.scheme === "socks5h") {
+ await socksGreeting(sock, r, p);
+ await socksConnect(sock, r, p, host, port);
+ } else {
+ await httpConnect(sock, r, p, host, port);
+ }
+ const head = r.release();
+ return { ok: true as const, socket: sock, head };
+ })(),
+ timeoutMs,
+ () => sock,
+ "the proxy",
+ );
+ } catch (err) {
+ (sock as net.Socket | null)?.destroy();
+ return { ok: false, reason: errText(err) };
+ }
+}
+
+// THE PREFLIGHT: the proxy answers (TCP, or TLS for https://) and, for a
+// SOCKS proxy, accepts the greeting and the exit's login. Nothing is asked of
+// any destination.
+export async function preflightProxy(
+ proxyUrl: string,
+ timeoutMs = PROXY_TIMEOUT_MS,
+): Promise<{ ok: true; ms: number } | ProxyFailure> {
+ const p = parseProxyUrl(proxyUrl);
+ if ("error" in p) return { ok: false, reason: p.error };
+ const t0 = Date.now();
+ let sock: net.Socket | null = null;
+ try {
+ await withTimeout(
+ (async () => {
+ sock = await connectToProxy(p);
+ if (p.scheme === "socks5" || p.scheme === "socks5h") {
+ const r = reader(sock);
+ await socksGreeting(sock, r, p);
+ r.release();
+ }
+ })(),
+ timeoutMs,
+ () => sock,
+ "the proxy",
+ );
+ return { ok: true, ms: Date.now() - t0 };
+ } catch (err) {
+ return { ok: false, reason: errText(err) };
+ } finally {
+ (sock as net.Socket | null)?.destroy();
+ }
+}
+
+// ONE GET THROUGH THE EXIT (the address-echo probe): status and the first
+// 4 KB of the body. http and https destinations; the TLS to an https
+// destination runs inside the tunnel.
+export async function getThroughProxy(
+ proxyUrl: string,
+ url: string,
+ timeoutMs = PROXY_TIMEOUT_MS,
+): Promise<{ ok: true; status: number; body: string } | ProxyFailure> {
+ let u: URL;
+ try {
+ u = new URL(url);
+ } catch {
+ return { ok: false, reason: "the echo URL does not parse" };
+ }
+ const secure = u.protocol === "https:";
+ const port = Number(u.port || (secure ? 443 : 80));
+ const host = u.hostname.replace(/^\[|\]$/g, "");
+ const t = await openTunnel(proxyUrl, host, port, timeoutMs);
+ if (!t.ok) return t;
+ let sock: net.Socket = t.socket;
+ try {
+ return await withTimeout(
+ (async () => {
+ if (secure) {
+ sock = await new Promise<net.Socket>((resolve, reject) => {
+ const s = tls.connect({ socket: t.socket, servername: net.isIP(host) ? undefined : host }, () => resolve(s));
+ s.once("error", reject);
+ });
+ } else if (t.head.length) {
+ sock.unshift(t.head);
+ }
+ const r = reader(sock);
+ sock.write(
+ `GET ${u.pathname || "/"}${u.search} HTTP/1.1\r\nHost: ${u.host}\r\nUser-Agent: archilyzer-network-probe\r\n` +
+ `Accept: text/plain, */*\r\nConnection: close\r\n\r\n`,
+ );
+ const head = (await r.readUntil("\r\n\r\n")).toString("latin1");
+ const status = Number(/^HTTP\/1\.[01] (\d{3})/.exec(head)?.[1] ?? 0);
+ const body = (await r.readAll(4096)).toString("utf8");
+ const chunked = /\r\ntransfer-encoding:\s*chunked/i.test(head);
+ return { ok: true as const, status, body: chunked ? dechunk(body) : body };
+ })(),
+ timeoutMs,
+ () => sock,
+ "the echo request",
+ );
+ } catch (err) {
+ return { ok: false, reason: errText(err) };
+ } finally {
+ sock.destroy();
+ }
+}
+
+function dechunk(s: string): string {
+ let out = "";
+ let rest = s;
+ for (;;) {
+ const m = /^([0-9a-f]+)[^\r\n]*\r\n/i.exec(rest);
+ if (!m) break;
+ const n = parseInt(m[1]!, 16);
+ if (n === 0) break;
+ out += rest.slice(m[0].length, m[0].length + n);
+ rest = rest.slice(m[0].length + n + 2);
+ }
+ return out;
+}
+
+// The public address an echo body names (the first IPv4/IPv6 literal in it),
+// or null.
+export function addressInEcho(body: string): string | null {
+ const t = body.trim();
+ if (net.isIP(t)) return t;
+ for (const m of t.matchAll(/[0-9a-fA-F:.]{3,}/g)) {
+ if (net.isIP(m[0])) return m[0];
+ const c = m[0].replace(/^[.]+|[:.]+$/g, "");
+ if (net.isIP(c)) return c;
+ }
+ return null;
+}
diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts
@@ -83,6 +83,11 @@ import {
import { APP_INSTANCE_CONFIG_FIELD_DOCS } from "./transcriptionApps";
import { DIGEST_APP_CONFIG_FIELD_DOCS } from "./digest";
import {
+ NETWORK_EXIT_FIELD_DOCS,
+ NETWORK_PLATFORM_POLICY_FIELD_DOCS,
+ NETWORK_SETTINGS_FIELD_DOCS,
+} from "./networkExits";
+import {
STORAGE_LOCATION_FIELD_DOCS,
STORAGE_SETTINGS_FIELD_DOCS,
STORAGE_VOLUME_FIELD_DOCS,
@@ -184,6 +189,15 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings,
defaults: fromObject(d.pacing),
},
],
+ network: [
+ {
+ path: "network",
+ docs: NETWORK_SETTINGS_FIELD_DOCS,
+ defaults: fromObject(d.network),
+ },
+ { path: "network.exits[]", docs: NETWORK_EXIT_FIELD_DOCS },
+ { path: "network.platforms.<platform>", docs: NETWORK_PLATFORM_POLICY_FIELD_DOCS },
+ ],
archiveStorage: [
{
path: "archiveStorage",
diff --git a/common/lib/settingsSchema.test.ts b/common/lib/settingsSchema.test.ts
@@ -43,6 +43,7 @@ import type { SourceGroup } from "./copies/settings";
import type { PrivacySettings } from "./privacySettings";
import type { VoiceSettings } from "./voiceSettings";
import type { GenerationSettings } from "./generationSettings";
+import type { NetworkSettings } from "./networkExits";
import type {
AttributionSettings,
BackfillSettings,
@@ -94,6 +95,8 @@ type PreSchemaSiteSettings = {
liveRecording: LiveRecordingSettingsBlock;
// Release 17 slice RL — the adaptive pace and the hold.
pacing: PacingSettingsBlock;
+ // Named network exits (lane network-exits).
+ network: NetworkSettings;
downloadFormat: DownloadFormatPreset;
// The source-video quality a full persist keeps.
sourceVideoQuality: SourceVideoQuality;
@@ -156,7 +159,7 @@ type PreSchemaSiteSettings = {
type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
const shapeUnchanged: Same<SiteSettings, PreSchemaSiteSettings> = true;
-test("SiteSettings keeps its 50 fields, in file order", () => {
+test("SiteSettings keeps its 51 fields, in file order", () => {
assert.equal(shapeUnchanged, true);
assert.deepEqual(Object.keys(siteSettingsSchema.shape), [
"adminTitle",
@@ -171,6 +174,7 @@ test("SiteSettings keeps its 50 fields, in file order", () => {
"livePreclip",
"liveRecording",
"pacing",
+ "network",
"downloadFormat",
"sourceVideoQuality",
"minFreeDiskGB",
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -155,6 +155,8 @@ import {
export type { Worker } from "./workers";
export type { SocialSettings, XSocialSettings, XenforoSocialSettings, InstagramSocialSettings } from "../social/xCookieSource";
import { sanitizeJobGapSeconds } from "./jobGap";
+import { sanitizeNetwork, type NetworkSettings } from "./networkExits";
+export type { NetworkSettings, NetworkExit, NetworkPlatformPolicy } from "./networkExits";
export { JOB_GAP_DEFAULT_SECONDS, JOB_GAP_MAX_SECONDS, jobGapSecondsFor } from "./jobGap";
// The `social` block (release 16 slice XL). The types and the coercion live
@@ -2000,6 +2002,9 @@ export const siteSettingsSchema = z.object({
pacing: settingsField((v): PacingSettingsBlock => sanitizePacing(v)).describe(
"How the download pace adapts to rate limits, per platform (release 17). Every yt-dlp spawn against a platform paces its requests (`--sleep-requests`) at the platform's adaptive pace, and the download lane waits sleepBetweenDownloadsSeconds plus the pace above its fixed value between units. A rate limit doubles the pace; clean units ease it back; a rate limit that outlasts the cooldown cap holds the platform to one probe at a time. The live pace, cooldowns and holds are in `.auto-queue/state.json`, shown on /operations/download. See common/jobs/platformBackoff.ts.",
),
+ network: settingsField((v): NetworkSettings => sanitizeNetwork(v)).describe(
+ "NAMED NETWORK EXITS (lane network-exits): proxies a listing may leave through, a policy per platform queue, and which exit a logged-in request (a cookie jar) is pinned to. Absent or empty = every request goes direct, exactly as before. The trial routes only the listing requests of rumble and twitch, and no cookie jar may leave direct. Written by `pnpm ops network` / `pnpm ops network-exit` and /settings → Network exits, never by `pnpm ops settings`; `pnpm ops get network` reports each exit, its rests and its counts. Proxy credentials are secrets: redacted in every answer, log and record. See common/lib/networkExits.ts and controller/networkExits.ts.",
+ ),
downloadFormat: settingsField((v): DownloadFormatPreset =>
isDownloadFormatPreset(v) ? v : "auto").describe(
"Default yt-dlp `-f` download format for every channel that doesn't set its own (ChannelConfig.downloadFormat). \"auto\" picks per-source: `original` for Odysee (whose HLS rungs are CDN-truncated), `bestaudio/worst` elsewhere. See common/ytdlp/downloadFormat.ts.",
diff --git a/common/testing/fakeProxy.ts b/common/testing/fakeProxy.ts
@@ -0,0 +1,212 @@
+// IN-PROCESS FAKE PROXIES for the network-exit tests: a SOCKS5 server (with
+// an optional username/password) and an HTTP CONNECT proxy, both on loopback,
+// that tunnel only to the loopback servers a test names — and an echo server
+// and a plain target server that count every connection they get. Nothing
+// here reaches beyond 127.0.0.1.
+
+import net from "node:net";
+import http from "node:http";
+
+export type Routed = { host: string; port: number };
+export type ConnectSeen = { atyp: "ipv4" | "domain" | "ipv6" | "http"; host: string; port: number };
+
+function listen(server: net.Server): Promise<number> {
+ return new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve((server.address() as net.AddressInfo).port)));
+}
+
+function closeServer(server: net.Server, sockets: Set<net.Socket>): Promise<void> {
+ for (const s of sockets) s.destroy();
+ return new Promise((resolve) => server.close(() => resolve()));
+}
+
+function track(server: net.Server): Set<net.Socket> {
+ const sockets = new Set<net.Socket>();
+ server.on("connection", (s) => {
+ sockets.add(s);
+ s.on("close", () => sockets.delete(s));
+ });
+ return sockets;
+}
+
+export async function startFakeSocks5(opts: {
+ username?: string;
+ password?: string;
+ // Where a CONNECT to host:port really goes; null refuses it (reply 2).
+ route: (host: string, port: number) => Routed | null;
+}): Promise<{
+ port: number;
+ connects: ConnectSeen[];
+ greetings: number;
+ authFailures: number;
+ close: () => Promise<void>;
+}> {
+ const state = { connects: [] as ConnectSeen[], greetings: 0, authFailures: 0 };
+ const server = net.createServer((sock) => {
+ let buf = Buffer.alloc(0);
+ let stage: "greet" | "auth" | "connect" | "piped" = "greet";
+ sock.on("error", () => {});
+ sock.on("data", (c) => {
+ if (stage === "piped") return;
+ buf = Buffer.concat([buf, c]);
+ for (;;) {
+ if (stage === "greet") {
+ if (buf.length < 2 || buf.length < 2 + buf[1]!) return;
+ const methods = [...buf.subarray(2, 2 + buf[1]!)];
+ buf = buf.subarray(2 + buf[1]!);
+ state.greetings++;
+ const wantAuth = opts.username !== undefined;
+ if (wantAuth && !methods.includes(2)) return void sock.end(Buffer.from([5, 0xff]));
+ sock.write(Buffer.from([5, wantAuth ? 2 : 0]));
+ stage = wantAuth ? "auth" : "connect";
+ continue;
+ }
+ if (stage === "auth") {
+ if (buf.length < 2) return;
+ const ul = buf[1]!;
+ if (buf.length < 3 + ul) return;
+ const pl = buf[2 + ul]!;
+ if (buf.length < 3 + ul + pl) return;
+ const u = buf.subarray(2, 2 + ul).toString();
+ const p = buf.subarray(3 + ul, 3 + ul + pl).toString();
+ buf = buf.subarray(3 + ul + pl);
+ if (u !== opts.username || p !== opts.password) {
+ state.authFailures++;
+ return void sock.end(Buffer.from([1, 1]));
+ }
+ sock.write(Buffer.from([1, 0]));
+ stage = "connect";
+ continue;
+ }
+ if (stage === "connect") {
+ if (buf.length < 5) return;
+ const atyp = buf[3]!;
+ let host: string;
+ let off: number;
+ if (atyp === 1) {
+ if (buf.length < 10) return;
+ host = [...buf.subarray(4, 8)].join(".");
+ off = 8;
+ } else if (atyp === 3) {
+ const n = buf[4]!;
+ if (buf.length < 5 + n + 2) return;
+ host = buf.subarray(5, 5 + n).toString();
+ off = 5 + n;
+ } else {
+ if (buf.length < 22) return;
+ const g: string[] = [];
+ for (let i = 0; i < 8; i++) g.push(buf.readUInt16BE(4 + i * 2).toString(16));
+ host = g.join(":").replace(/^(0:)+/, "::").replace(/^::(0:)*/, "::");
+ if (host === "::1" || /^(0:){7}1$/.test(g.join(":"))) host = "::1";
+ off = 20;
+ }
+ const port = buf.readUInt16BE(off);
+ buf = buf.subarray(off + 2);
+ state.connects.push({ atyp: atyp === 1 ? "ipv4" : atyp === 3 ? "domain" : "ipv6", host, port });
+ const to = opts.route(host, port);
+ if (!to) return void sock.end(Buffer.from([5, 2, 0, 1, 0, 0, 0, 0, 0, 0]));
+ const up = net.connect(to.port, to.host, () => {
+ sock.write(Buffer.from([5, 0, 0, 1, 127, 0, 0, 1, 0, 0]));
+ stage = "piped";
+ if (buf.length) up.write(buf);
+ sock.pipe(up).pipe(sock);
+ });
+ up.on("error", () => sock.destroy());
+ return;
+ }
+ return;
+ }
+ });
+ });
+ const sockets = track(server);
+ const port = await listen(server);
+ return {
+ port,
+ get connects() {
+ return state.connects;
+ },
+ get greetings() {
+ return state.greetings;
+ },
+ get authFailures() {
+ return state.authFailures;
+ },
+ close: () => closeServer(server, sockets),
+ };
+}
+
+export async function startFakeHttpProxy(opts: {
+ // The expected `Proxy-Authorization: Basic …` value's user:pass; absent = none needed.
+ auth?: string;
+ route: (host: string, port: number) => Routed | null;
+}): Promise<{ port: number; connects: ConnectSeen[]; close: () => Promise<void> }> {
+ const connects: ConnectSeen[] = [];
+ const server = net.createServer((sock) => {
+ let buf = Buffer.alloc(0);
+ sock.on("error", () => {});
+ const onData = (c: Buffer) => {
+ buf = Buffer.concat([buf, c]);
+ const i = buf.indexOf("\r\n\r\n");
+ if (i < 0) return;
+ sock.off("data", onData);
+ const head = buf.subarray(0, i).toString("latin1");
+ const rest = buf.subarray(i + 4);
+ const m = /^CONNECT ([^\s:]+|\[[^\]]+\]):(\d+) HTTP/.exec(head);
+ if (!m) return void sock.end("HTTP/1.1 400 Bad Request\r\n\r\n");
+ const host = m[1]!;
+ const port = Number(m[2]);
+ connects.push({ atyp: "http", host, port });
+ if (opts.auth !== undefined) {
+ const want = `Basic ${Buffer.from(opts.auth).toString("base64")}`;
+ if (!head.split("\r\n").some((l) => l.toLowerCase() === `proxy-authorization: ${want}`.toLowerCase())) {
+ return void sock.end("HTTP/1.1 407 Proxy Authentication Required\r\n\r\n");
+ }
+ }
+ const to = opts.route(host, port);
+ if (!to) return void sock.end("HTTP/1.1 403 Forbidden\r\n\r\n");
+ const up = net.connect(to.port, to.host, () => {
+ sock.write("HTTP/1.1 200 Connection established\r\n\r\n");
+ if (rest.length) up.write(rest);
+ sock.pipe(up).pipe(sock);
+ });
+ up.on("error", () => sock.destroy());
+ };
+ sock.on("data", onData);
+ });
+ const sockets = track(server);
+ const port = await listen(server);
+ return { port, connects, close: () => closeServer(server, sockets) };
+}
+
+// An address-echo server: answers every GET with `body`.
+export async function startEchoServer(body: string): Promise<{ port: number; hits: () => number; close: () => Promise<void> }> {
+ let hits = 0;
+ const server = http.createServer((_req, res) => {
+ hits++;
+ res.writeHead(200, { "content-type": "text/plain" });
+ res.end(body);
+ });
+ const sockets = track(server);
+ const port = await listen(server);
+ return { port, hits: () => hits, close: () => closeServer(server, sockets) };
+}
+
+// A server that only counts the connections it gets (the "direct" target a
+// fail-closed test proves was never contacted).
+export async function startCountingServer(): Promise<{ port: number; connections: () => number; close: () => Promise<void> }> {
+ let n = 0;
+ const server = net.createServer((s) => {
+ n++;
+ s.destroy();
+ });
+ const sockets = track(server);
+ const port = await listen(server);
+ return { port, connections: () => n, close: () => closeServer(server, sockets) };
+}
+
+// A loopback port with nothing listening on it.
+export async function closedPort(): Promise<number> {
+ const s = net.createServer();
+ const port = await listen(s);
+ await new Promise<void>((r) => s.close(() => r()));
+ return port;
+}
diff --git a/common/ytdlp/runYtdlp.ts b/common/ytdlp/runYtdlp.ts
@@ -91,7 +91,24 @@ import {
downloadGapMs,
isSubtitleDeferred,
} from "../jobs/platformBackoff";
-import { hasSubtitleRateLimit } from "../lib/availability";
+import { hasSubtitleRateLimit, isBotCheck } from "../lib/availability";
+import {
+ DIRECT_EXIT,
+ proxyDisplay,
+ proxySecretFragments,
+ redactFragments,
+} from "../lib/networkExits";
+import { preflightProxy } from "../lib/networkProxy-server";
+import {
+ clearExitRest,
+ countNetworkUse,
+ exitRestUntil,
+ listingPool,
+ resolveListingRoute,
+ restExit,
+ restingSentence,
+} from "../controller/networkExits";
+import { JobDeferredError } from "../jobs/jobDeferred";
import { computeKeepWindow, type KeepWindow } from "../controller/keptVideos";
import { writeCuesAfterDownload } from "../controller/normalizeTranscript";
import { downloadOneManaged } from "./downloadOneManaged";
@@ -486,25 +503,51 @@ export function dataDirIdForUrl(url: string): string | null {
// share (`detectPlatform(url) ?? "unknown"`); `pagesReached` is the last
// `Downloading page N` the extractor logged (null for an extractor that does
// not log pages); `count` is how many entries were printed before the cut.
+//
+// `exit` is the network exit the listing went through (controller/
+// networkExits.ts; "direct" without one). `platformBackoffDue` says whether
+// the caller records the PLATFORM's cooldown, as it always did: true through
+// direct; through an exit only when every exit of the platform now rests — a
+// rate limit through one exit rests that exit alone.
export class EnumerationIncompleteError extends Error {
readonly platform: string;
readonly pagesReached: number | null;
readonly count: number;
+ readonly exit: string;
+ readonly platformBackoffDue: boolean;
constructor(
exitCode: number | undefined,
platform: string,
pagesReached: number | null,
count: number,
+ via?: { exit: string; platformBackoffDue: boolean; restUntil?: number },
) {
super(
`yt-dlp exited with code ${exitCode} (rate-limited${
pagesReached !== null ? ` at page ${pagesReached}` : ""
- } of the listing, ${count} entries)`,
+ } of the listing, ${count} entries)` +
+ (via && via.exit !== DIRECT_EXIT
+ ? ` through network exit "${via.exit}"` +
+ (via.restUntil ? `, which rests until ${new Date(via.restUntil).toISOString()}` : "")
+ : ""),
);
this.name = "EnumerationIncompleteError";
this.platform = platform;
this.pagesReached = pagesReached;
this.count = count;
+ this.exit = via?.exit ?? DIRECT_EXIT;
+ this.platformBackoffDue = via?.platformBackoffDue ?? true;
+ }
+}
+
+// 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;
}
}
@@ -533,6 +576,19 @@ async function enumeratePlaylistUrls(
root: string,
range?: { start: number; end: number },
): Promise<string[]> {
+ return (await enumeratePlaylistListing(opts, root, range)).urls;
+}
+
+// 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, routeListing decides direct or
+// an exit (controller/networkExits.ts) and spawnListing carries it.
+async function enumeratePlaylistListing(
+ opts: RunYtdlpOpts,
+ root: string,
+ range?: { start: number; end: number },
+): Promise<{ urls: string[]; exit: string | null }> {
const args: string[] = [
"--flat-playlist",
"--skip-download",
@@ -551,10 +607,98 @@ async function enumeratePlaylistUrls(
),
opts.channelConfig.url!,
);
+ const platform = cooldownPlatformKey(opts.channelConfig);
+ const route = await resolveListingRoute({
+ paths: opts.paths,
+ slug: opts.channelSlug,
+ platform,
+ argv: args,
+ });
+ if (route.kind === "none") {
+ return { urls: await spawnListing(opts, root, args), exit: null };
+ }
+ const exit = route.kind === "exit" ? route.exit.id : DIRECT_EXIT;
+ const via: ListingVia = { platform, exit, pool: listingPool(undefined, platform) ?? [] };
+ if (route.kind === "direct") {
+ opts.onLog(
+ `Network exit: direct (${
+ route.why === "jar"
+ ? `this listing carries a login — the ${route.jar} cookie 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"
+ }).\n`,
+ );
+ } else {
+ // A RESTING EXIT: the channel waits for it (the job ends deferred and the
+ // scheduler comes back at its end); it never hops to another exit.
+ 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);
+ 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}. ` +
+ `The ${platform} listing was not sent — a listing never falls back to direct.`,
+ );
+ }
+ via.proxy = route.exit.proxy;
+ opts.onLog(
+ `Network exit: "${exit}" (${proxyDisplay(route.exit.proxy)}) for this ${platform} listing; ` +
+ `the proxy is given to yt-dlp on its stdin.\n`,
+ );
+ }
+ return { urls: await spawnListing(opts, root, args, via), exit };
+}
+
+// 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 };
+
+// A yt-dlp config-file line is split shell-style (and `#` starts a comment),
+// so the URL goes in single quotes.
+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[]) {
+ let pending = "";
+ return {
+ push(chunk: string) {
+ pending += chunk;
+ const nl = pending.lastIndexOf("\n");
+ if (nl < 0) return;
+ onLog(redactFragments(pending.slice(0, nl + 1), fragments));
+ pending = pending.slice(nl + 1);
+ },
+ flush() {
+ if (pending) onLog(redactFragments(pending, fragments));
+ pending = "";
+ },
+ };
+}
+
+async function spawnListing(
+ opts: RunYtdlpOpts,
+ root: string,
+ args: string[],
+ via?: ListingVia,
+): Promise<string[]> {
// The fixed waits drawn once for this run (lib/jitter.mjs).
- const spawned = jitterYtdlpSleeps(args);
+ 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`);
if (opts.requestCounter) opts.requestCounter.n++;
+ if (via) await countNetworkUse(opts.paths, via.platform, via.exit, { requests: 1 }).catch(() => {});
const child = execa(opts.paths.ytdlpBin, spawned, {
cwd: root,
@@ -562,9 +706,16 @@ async function enumeratePlaylistUrls(
all: false,
buffer: true,
reject: false,
+ ...(via?.proxy ? { input: `--proxy ${configQuote(via.proxy)}\n` } : {}),
});
- child.stderr?.on("data", (c: Buffer) => opts.onLog(c.toString("utf8")));
+ // 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")),
+ );
const result = await child;
+ redactor?.flush();
const urls = String(result.stdout ?? "")
.split("\n")
.map((s) => s.trim())
@@ -578,7 +729,8 @@ async function enumeratePlaylistUrls(
result.exitCode !== 101 &&
!opts.signal.aborted
) {
- const stderr = String(result.stderr ?? "");
+ const stderr = via?.proxy ? redactFragments(String(result.stderr ?? ""), fragments) : 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.
await observeStderrServiceSignal(opts.paths, stderr, {
@@ -598,10 +750,60 @@ async function enumeratePlaylistUrls(
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;
}
+// A FAILED LISTING UNDER A NETWORK POLICY. Counted for the trial. Through
+// direct, nothing else changes: the caller goes on to today's handling.
+// Through an exit it never returns: a rate limit or a bot check RESTS the
+// exit for the platform (the cookie alert is not raised — the request carried
+// no cookies, and the answer was to the exit's address); the platform's own
+// cooldown is due only when every exit of the pool now rests.
+async function listingFailedVia(
+ opts: RunYtdlpOpts,
+ via: ListingVia,
+ exitCode: number | undefined,
+ stderr: string,
+ count: number,
+): Promise<void> {
+ const rateLimited = classifyDownloadFailure(stderr, undefined) === "rate_limit";
+ const botCheck = isBotCheck(stderr);
+ const proxyFailed = via.exit !== DIRECT_EXIT && /proxy/i.test(stderr);
+ await countNetworkUse(opts.paths, via.platform, via.exit, {
+ ...(rateLimited ? { rateLimits: 1 } : {}),
+ ...(botCheck ? { botChecks: 1 } : {}),
+ ...(proxyFailed ? { proxyFailures: 1 } : {}),
+ ...((rateLimited || botCheck) && via.exit !== DIRECT_EXIT ? { rests: 1 } : {}),
+ }).catch(() => {});
+ if (via.exit === DIRECT_EXIT) return;
+ if (rateLimited || botCheck) {
+ const { until, allRest } = await restExit(opts.paths, via.platform, via.exit, via.pool);
+ opts.onLog(
+ `Network exit "${via.exit}" rests for ${via.platform} until ${new Date(until).toISOString()} after ${
+ rateLimited ? "a rate limit" : "a bot check"
+ }; its channels wait for it` +
+ (allRest ? ` — every exit of ${via.platform} now rests, so ${via.platform} cools down as before` : "") +
+ `.\n`,
+ );
+ if (rateLimited) {
+ throw new EnumerationIncompleteError(exitCode, via.platform, lastListingPage(stderr), count, {
+ exit: via.exit,
+ platformBackoffDue: allRest,
+ restUntil: until,
+ });
+ }
+ throw new Error(
+ `yt-dlp exited with code ${exitCode}: a bot check through network exit "${via.exit}", which rests until ${new Date(until).toISOString()}`,
+ );
+ }
+ throw new Error(`yt-dlp exited with code ${exitCode} through network exit "${via.exit}"`);
+}
+
// Thin exported wrapper over the module-private enumeratePlaylistUrls for
// callers (e.g. the quick availability check) that only need a one-shot fresh
// flat-playlist fetch and shouldn't have to fabricate a full RunYtdlpOpts.
@@ -725,6 +927,8 @@ async function acceptEnumeration(
opts: RunYtdlpOpts,
root: string,
urls: ReadonlyArray<string>,
+ // The listing's network exit (null: the platform has no network policy).
+ exit: string | null = null,
): Promise<{
decision: ListingDecision;
roster: Roster;
@@ -754,6 +958,7 @@ async function acceptEnumeration(
at: now,
listedCount: listedIds.size,
verdict: decision.verdict,
+ ...(exit !== null ? { exit } : {}),
});
await writeRoster(opts.paths, opts.channelSlug, roster);
@@ -763,8 +968,8 @@ async function acceptEnumeration(
async function storePlaylist(opts: RunYtdlpOpts): Promise<void> {
const root = channelRoot(opts);
await mkdir(root, { recursive: true });
- const urls = await enumeratePlaylistUrls(opts, root);
- const { decision } = await acceptEnumeration(opts, root, urls);
+ const { urls, exit } = await enumeratePlaylistListing(opts, root);
+ const { decision } = await acceptEnumeration(opts, root, urls, exit);
if (!decision.accept) {
opts.onLog(`Store playlist: ${decision.reason}.\n`);
return;
@@ -2152,8 +2357,9 @@ async function syncFullSweep(opts: RunYtdlpOpts): Promise<void> {
// the roster (additive, so this is safe unconditionally) and decide
// whether the listing itself may be acted on.
let urls: string[];
+ let listingExit: string | null;
try {
- urls = await enumeratePlaylistUrls(opts, root);
+ ({ urls, exit: listingExit } = await enumeratePlaylistListing(opts, root));
} catch (err) {
if (!(err instanceof EnumerationIncompleteError)) throw err;
// A 429 part-way through the listing: what was printed is a prefix, not a
@@ -2162,8 +2368,11 @@ async function syncFullSweep(opts: RunYtdlpOpts): Promise<void> {
// a download's 429 does, then do this sync's job the cheap way.
// Best-effort, as on the download path: a failed state write must not fail
// the sync this branch exists to rescue.
+ // Through a network exit the exit rests instead (controller/
+ // networkExits.ts), and the platform cools down only once every exit of
+ // it rests (platformBackoffDue).
try {
- await opts.onPlatformBackoff?.("rate_limit");
+ if (err.platformBackoffDue) await opts.onPlatformBackoff?.("rate_limit");
} catch (backoffErr) {
opts.onLog(
`Warning: could not record the ${err.platform} cooldown (${
@@ -2174,7 +2383,7 @@ async function syncFullSweep(opts: RunYtdlpOpts): Promise<void> {
opts.onLog(
`Full sweep incomplete: 429 at ${
err.pagesReached !== null ? `page ${err.pagesReached}` : "an unknown page"
- } of the listing, ${err.count} entries — not a listing. Ran the paged walk instead; syncs wait for the ${err.platform} cooldown, then the sweep is retried.\n`,
+ } of the listing, ${err.count} entries — not a listing. Ran the paged walk instead; syncs wait for ${err.exit !== DIRECT_EXIT && !err.platformBackoffDue ? `network exit "${err.exit}" to rest` : `the ${err.platform} cooldown`}, then the sweep is retried.\n`,
);
if (opts.signal.aborted) return;
return syncPaged(opts);
@@ -2185,6 +2394,7 @@ async function syncFullSweep(opts: RunYtdlpOpts): Promise<void> {
opts,
root,
urls,
+ listingExit,
);
opts.onLog(`Full sweep: ${decision.reason}.\n`);
diff --git a/editor/app/channels/[slug]/pipelineActions.ts b/editor/app/channels/[slug]/pipelineActions.ts
@@ -36,6 +36,7 @@ import {
runRemoteListing,
} from "yt-dlp-transcript-common/controller/remoteListing";
import { EnumerationIncompleteError } from "yt-dlp-transcript-common/ytdlp/runYtdlp";
+import { listingRestRefusal } from "yt-dlp-transcript-common/controller/networkExits";
import {
importPlatformSignal,
resolveBitchuteImportUrl,
@@ -225,6 +226,13 @@ async function runPipelineAction(
};
}
}
+ // A LISTING ON A RESTING NETWORK EXIT waits (controller/networkExits.ts):
+ // the channel's recorded exit drew a rate limit, and a channel never moves
+ // to another exit on a failure. Read only; the listing itself checks again.
+ if (mode === "sync" || mode === "store-playlist") {
+ const resting = await listingRestRefusal(paths, slug, channelConfig.url);
+ if (resting) return { ok: false, info: true, error: resting.sentence };
+ }
// store-playlist only fetches the video list (no media written), so it is not
// gated; every other mode downloads audio/subtitles into transcriptsDir.
if (mode !== "store-playlist") {
@@ -1033,7 +1041,7 @@ export async function remoteListingAction(slug: string): Promise<StreamActionRes
const result = await runRemoteListing({ paths, slug, channelConfig, platform, onLog, signal });
onLog(`${REMOTE_LISTING_RESULT_MARKER}${JSON.stringify(result)}\n`);
} catch (err) {
- if (err instanceof EnumerationIncompleteError) {
+ if (err instanceof EnumerationIncompleteError && err.platformBackoffDue) {
await recordDownloadBackoff(platform, paths, "rate_limit").catch(() => {});
}
throw err;