// NAMED NETWORK EXITS (lane network-exits, 21 Nov 2026): proxies a fetch may
// leave through, chosen per channel and kept, for the platforms and request
// kinds the operator routes. Pure and client-safe: the types, the sanitizer,
// the validator the writers refuse with, the sticky choice, the cookie-jar
// classifier. State and the proxy client live in controller/networkExits.ts
// and lib/networkProxy-server.ts; the credentials in
// lib/networkCredentials-server.ts.
//
// WHAT IT IS FOR, AND WHAT IT IS NOT. It spreads logged-out listing load over
// several addresses, and lets the archive list a site that does not answer the
// home address. It is not a disguise: no fingerprint or user-agent spoofing is
// added, and a login (a cookie jar, a browser's cookies, a token) never moves
// between addresses.
//
// THE RULES, each enforced where its comment says:
// - `direct` (no proxy) always exists and is reserved.
// - A policy per platform queue, `network.platforms.
`; absent = direct.
// THE TRIAL routes only TRIAL_SCOPE (rumble and twitch listings); the
// writers refuse anything else with TRIAL_SCOPE_SENTENCE; a hand-edited
// out-of-scope policy fails the trial platforms' listings (strict read).
// - Sticky, never random: stickyExitFor hashes the channel slug over the
// platform's enabled exits once; the choice is recorded and kept.
// - A request that carries a login is pinned direct (requestJar). The trial
// refuses every jar assignment.
// - CREDENTIALS ARE NEVER A SETTING (review 1, finding 1). An exit is stored
// as id, scheme, host, port and `credentials: true|false`; the user and
// password live where the repo keeps every other secret — the environment,
// else a mode-600 key file whose PATH is `network.credentialsFile`
// (lib/networkCredentials-server.ts, the archive.org S3 keys' convention).
// A proxy URL carrying credentials is refused at save. Every answer, log
// line and record is built from the stored form, so there is nothing to
// mask; a child's own output is scrubbed of the exact secret values.
import type { FieldDocs } from "./fieldDocs";
import { YTDLP_OPTIONS } from "./ytdlpOptions";
import { YTDLP_OPTION_CLASSES, type YtdlpOptionClass } from "./ytdlpOptionClasses";
export const DIRECT_EXIT = "direct";
// The request kinds a policy may name. Only `listing` is routable in the
// trial; the others are named so a refusal can say what was asked.
export const NETWORK_REQUEST_KINDS = [
"listing",
"download",
"metadata",
"subtitles",
"clip",
"live",
"posts",
] as const;
export type NetworkRequestKind = (typeof NETWORK_REQUEST_KINDS)[number];
export const NETWORK_POLICY_MODES = ["sticky"] as const;
export type NetworkPolicyMode = (typeof NETWORK_POLICY_MODES)[number];
export const PROXY_SCHEMES = ["socks5h", "socks5", "http", "https"] as const;
export type ProxyScheme = (typeof PROXY_SCHEMES)[number];
export type NetworkExit = {
id: string;
label: string;
scheme: ProxyScheme;
host: string;
port: number;
// Whether the proxy needs a user and password — kept in the key file.
credentials: boolean;
enabled: boolean;
};
export type NetworkPlatformPolicy = {
exits: string[];
mode: NetworkPolicyMode;
kinds: NetworkRequestKind[];
};
export type NetworkSettings = {
exits: NetworkExit[];
platforms: Record;
jars: Record;
echoUrl: string;
credentialsFile: string;
startupProbe: boolean;
};
export const DEFAULT_NETWORK_CREDENTIALS_FILE = "~/.config/archilyzer/network-exits.env";
// THE TRIAL'S SCOPE — the one place it is widened, deliberately, later.
export const TRIAL_SCOPE: Readonly> = 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 = {
exits:
"NAMED NETWORK EXITS: proxies a fetch may leave through, `[{id, label, scheme, host, port, credentials, " +
"enabled}]` (table below). The exit `direct` (no proxy) always exists and is reserved. Written by `pnpm ops " +
"network` and /settings → Network exits, never by `pnpm ops settings`. It spreads logged-out listing load over " +
"addresses and lets the archive list a site that does not answer the home address; it is not a disguise — no " +
"fingerprint or user-agent spoofing is added, and a login never moves between addresses. Worked example, " +
"Mullvad: while the machine is connected to the VPN, each WireGuard relay offers a SOCKS5 proxy at its own " +
"hostname on port 1080 (`socks5h://nl-ams-wg-socks5-001.relays.mullvad.net:1080`), resolvable only inside the " +
"tunnel — https://mullvad.net/en/help/socks5-proxy and " +
"https://mullvad.net/en/help/different-entryexit-node-using-wireguard-and-socks5-proxy .",
platforms:
"Which exits a platform queue's requests may use, keyed by platform: `{exits: [ids], mode: \"sticky\", kinds: " +
"[\"listing\"]}` (table below). Absent = every request goes direct, exactly as before. THE TRIAL routes only " +
"the LISTING (flat-playlist) requests of `rumble` and `twitch`; any other platform or kind is refused when " +
"saved; written by hand, it fails every rumble and twitch listing until fixed. Each channel's exit is chosen once, on its first listing, by a stable " +
"hash of its slug over the platform's enabled exits and recorded in `channels//network-exit.json`; only " +
"`pnpm ops network-exit` changes it. A recorded exit that is disabled or removed FAILS that channel's listing " +
"(naming the reassignment) — it is never re-chosen and never sent direct; a policy whose exits are all disabled " +
"fails every listing on the platform (`direct` is used only when the policy names it). Once any policy exists, no " +
"child process inherits a proxy variable (common/lib/childEnvGuard.mjs). One job keeps one exit for all its " +
"pages. Pacing stays per platform: the job gap, the pace, the cooldown and the hold count every exit together. " +
"A rate limit or bot check through an exit rests that exit for the platform (the platform cooldown's length); " +
"its channels' listings wait (the job ends deferred) and never move to another exit; when every exit rests " +
"after a rate limit the platform cools down as before. A proxy that does not answer, or a listing whose yt-dlp " +
"output does not show the proxy, fails naming the exit — never a fallback to direct.",
jars:
"A cookie jar's one fixed exit, keyed by jar id (`browser:`, `file:`, `login:`, " +
"`header`, `config`). A request that carries a login is pinned: direct in the trial, never the platform's " +
"pool, and a jar's exit is not changed while the jar is fresh. In the trial every assignment is refused: " +
"logged-in requests go direct — so a Rumble channel listing with its Firefox clearance cookie (the default " +
"for a new Rumble channel) stays direct, and the trial on Rumble covers only cookie-free channels.",
echoUrl:
"An address-echo URL (`http(s)://…`, answering the caller's public address as text) that the operator's " +
"`pnpm ops get network --probe` fetches through each exit to show the address it presents. Never fetched by " +
"the startup probe. Blank (the default) = no echo request at all.",
credentialsFile:
"The PATH of the mode-600 file holding the exits' credentials, one line per exit with `credentials: true`: " +
"`NETWORK_EXIT_=user:password` (ID upper-cased, `-` as `_`; each part percent-encoded: `my pass#1` is " +
"`my%20pass%231`). The environment variable of the same name wins (it is moved out of the environment at boot, so no " +
"child process inherits it). An absolute or `~/` path under the user's config directory (`~/.config`, or " +
"`$XDG_CONFIG_HOME`) or `ARCHILYZER_CREDENTIALS_DIR`; owned by the user, mode 600. Never the credentials themselves — " +
"a value that is not such a path is refused.",
startupProbe:
"A minute after the editor boots, check that each enabled exit's proxy accepts a TCP connection (no SOCKS " +
"greeting, no destination, no echo). One line per exit in the server log. false = no connection at boot.",
};
export const NETWORK_EXIT_FIELD_DOCS: FieldDocs = {
id:
"The exit's name in policies, records and `pnpm ops`: lowercase letters, digits and `-`, up to 40, not " +
"`direct`. Records store this, never the proxy.",
label: "A display name (defaults to the id).",
scheme:
"`socks5h` (the hostname is resolved by the proxy), `socks5` (resolved here), `http` or `https`. `pnpm ops " +
"network` also takes the whole as `proxy: \"socks5h://host:port\"`.",
host: "The proxy's hostname or IP address (letters, digits, `.`, `-`; an IPv6 address in brackets).",
port: "The proxy's port, 1–65535.",
credentials:
"Whether the proxy needs a user and password. They are read from `network.credentialsFile` (or its " +
"environment variable), never from settings.json; an exit that needs them and has none fails its listings.",
enabled:
"Off = the exit is out of every pool; a channel already recorded on it fails its listings until `pnpm ops " +
"network-exit` moves it.",
};
export const NETWORK_PLATFORM_POLICY_FIELD_DOCS: FieldDocs = {
exits: "The exit ids the platform's channels are spread over, `direct` allowed. Disabled exits are skipped.",
mode: "`sticky` (the only mode): a channel keeps its exit; never chosen per request, never moved on a failure.",
kinds: "The request kinds routed (default `[\"listing\"]`). The trial allows `listing` only.",
};
export function defaultNetworkSettings(): NetworkSettings {
return { exits: [], platforms: {}, jars: {}, echoUrl: "", credentialsFile: DEFAULT_NETWORK_CREDENTIALS_FILE, startupProbe: true };
}
const EXIT_ID_RE = /^[a-z0-9][a-z0-9-]{0,39}$/;
const PLATFORM_KEY_RE = /^[a-z0-9][a-z0-9.-]{0,99}$/;
const HOST_RE = /^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,62})(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,62}))*|\[[0-9A-Fa-f:.]+\])$/;
// Unreserved characters and %XX, nothing else (RFC 3986): what the key file's
// user and password may hold, so no parser — ours, yt-dlp's, a config line's —
// can read them differently.
const ENCODED_PART_RE = /^(?:[A-Za-z0-9\-._~]|%[0-9A-Fa-f]{2})+$/;
export const PERCENT_ENCODE_SENTENCE =
"percent-encode the user and the password (every character but letters, digits and - . _ ~ — for example " +
"`my pass#1` is `my%20pass%231`; encodeURIComponent does it)";
function isObject(v: unknown): v is Record {
return typeof v === "object" && v !== null && !Array.isArray(v);
}
function hostOk(h: unknown): h is string {
return typeof h === "string" && h.length <= 253 && HOST_RE.test(h);
}
function portOk(p: unknown): p is number {
return typeof p === "number" && Number.isInteger(p) && p >= 1 && p <= 65535;
}
function schemeOf(s: unknown): ProxyScheme | null {
return typeof s === "string" && (PROXY_SCHEMES as readonly string[]).includes(s) ? (s as ProxyScheme) : null;
}
// A PROXY URL TYPED BY THE OPERATOR, read into its stored parts — never its
// credentials. Parsed by hand (no WHATWG URL normalising one thing while
// yt-dlp reads another), and a URL that carries userinfo is refused: with the
// encoding sentence when it is not percent-encoded, always with where the
// credentials go instead. Never echoes the input.
export function parseProxyInput(raw: unknown): { scheme: ProxyScheme; host: string; port: number } | { error: string } {
if (typeof raw !== "string" || raw.trim() === "") return { error: "no proxy URL" };
const s = raw.trim();
const m = /^([A-Za-z0-9+.-]+):\/\/(.*)$/s.exec(s);
const scheme = schemeOf(m?.[1]?.toLowerCase());
if (!m || !scheme) return { error: "the proxy URL's scheme must be socks5h://, socks5://, http:// or https://" };
let rest = m[2]!;
if (!rest.includes("@") && /[/?#]/.test(rest.replace(/\/$/, ""))) {
return { error: "the proxy URL is scheme://host:port, with no path, query or fragment" };
}
rest = rest.replace(/\/$/, "");
const at = rest.lastIndexOf("@");
// eslint-disable-next-line no-control-regex
if (at < 0 && /[\s\u0000-\u001f\u007f]/.test(rest)) return { error: "the proxy URL holds whitespace or a control character" };
if (at >= 0) {
const info = rest.slice(0, at);
const encoded = info.split(":").every((p) => p === "" || ENCODED_PART_RE.test(p)) && info.split(":").length <= 2;
return {
error:
(encoded ? "" : `the proxy URL's credentials are not percent-encoded — ${PERCENT_ENCODE_SENTENCE}. `) +
"Proxy credentials are not a setting — give the exit `credentials: true` and put " +
"NETWORK_EXIT_=user:password (percent-encoded) in the mode-600 file network.credentialsFile names",
};
}
const hp = /^(\[[^\]]*\]|[^:]*):(\d{1,5})$/.exec(rest);
if (!hp) return { error: "the proxy URL must name its host and port (socks5h://host:1080)" };
const host = hp[1]!;
const port = Number(hp[2]);
if (!hostOk(host)) return { error: "the proxy URL's host is not a hostname or an IP address" };
if (!portOk(port)) return { error: "the proxy URL's port is not 1–65535" };
return { scheme, host, port };
}
export type ExitCredentials = { username: string; password: string; encoded: string };
// A key-file value, `user:password`, each part percent-encoded. Never echoes it.
export function parseCredentials(raw: string): ExitCredentials | { error: string } {
const v = raw.trim();
const i = v.indexOf(":");
if (i <= 0 || i === v.length - 1) return { error: `the credentials are not user:password — ${PERCENT_ENCODE_SENTENCE}` };
const user = v.slice(0, i);
const pass = v.slice(i + 1);
if (!ENCODED_PART_RE.test(user) || !ENCODED_PART_RE.test(pass)) {
return { error: `the credentials hold characters that are not percent-encoded — ${PERCENT_ENCODE_SENTENCE}` };
}
try {
return { username: decodeURIComponent(user), password: decodeURIComponent(pass), encoded: `${user}:${pass}` };
} catch {
return { error: `the credentials are not valid percent-encoding — ${PERCENT_ENCODE_SENTENCE}` };
}
}
export function credentialsEnvKey(id: string): string {
return `NETWORK_EXIT_${id.toUpperCase().replace(/-/g, "_")}`;
}
// What to show for an exit anywhere: built from the stored parts, so it has
// no secret in it to mask.
export function exitDisplay(e: Pick): string {
return `${e.scheme}://${e.host}:${e.port}${e.credentials ? " (credentials)" : ""}`;
}
// THE PROXY URL A CHILD IS GIVEN (internal only — stdin, the proxy client).
export function proxyUrlOf(e: Pick, creds: ExitCredentials | null): string {
return `${e.scheme}://${creds ? `${creds.encoded}@` : ""}${e.host}:${e.port}`;
}
// The exact strings a child's output must never carry into a log: the
// encoded userinfo, the user, the password encoded, decoded and as a Python
// repr (yt-dlp -v prints the config as one). Values, never a pattern.
export function secretFragmentsOf(creds: ExitCredentials | null): string[] {
if (!creds) return [];
const [user, pass] = [creds.encoded.slice(0, creds.encoded.indexOf(":")), creds.encoded.slice(creds.encoded.indexOf(":") + 1)];
const repr = (s: string) => s.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
const out = new Set([creds.encoded, user, pass, creds.username, creds.password, repr(creds.password), repr(creds.username)]);
return [...out].filter((f) => f.length > 0).sort((a, b) => b.length - a.length);
}
export function redactFragments(text: string, fragments: readonly string[]): string {
let out = text;
for (const f of fragments) out = out.split(f).join("");
return out;
}
function exitFromRaw(e: Record): NetworkExit | null {
const id = typeof e.id === "string" ? e.id.trim() : "";
const scheme = schemeOf(e.scheme);
if (!EXIT_ID_RE.test(id) || id === DIRECT_EXIT || !scheme || !hostOk(e.host) || !portOk(e.port)) return null;
const label = typeof e.label === "string" && e.label.trim() ? e.label.trim().slice(0, 80) : id;
return { id, label, scheme, host: e.host, port: e.port, credentials: e.credentials === true, enabled: e.enabled !== false };
}
// THE TOTAL READER (the settings schema's coercion). Keeps every structurally
// valid entry and drops what is not. It never decides a route: the listing
// reads the file strictly (controller/networkExits.ts loadNetworkStrict) and
// FAILS on anything networkSettingsProblems refuses.
export function sanitizeNetwork(v: unknown): NetworkSettings {
const r = isObject(v) ? v : {};
const exits: NetworkExit[] = [];
const seen = new Set();
for (const e of Array.isArray(r.exits) ? r.exits : []) {
if (!isObject(e)) continue;
const x = exitFromRaw(e);
if (!x || seen.has(x.id)) continue;
seen.add(x.id);
exits.push(x);
}
const platforms: Record = {};
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 = {};
if (isObject(r.jars)) {
for (const [jar, exit] of Object.entries(r.jars)) {
if (jar.length === 0 || jar.length > 300 || typeof exit !== "string") continue;
if (exit !== DIRECT_EXIT && !EXIT_ID_RE.test(exit)) continue;
jars[jar] = exit;
}
}
const echoUrl = typeof r.echoUrl === "string" && validEchoUrl(r.echoUrl.trim()) ? r.echoUrl.trim() : "";
const credentialsFile =
typeof r.credentialsFile === "string" && looksLikePath(r.credentialsFile) ? r.credentialsFile.trim() : DEFAULT_NETWORK_CREDENTIALS_FILE;
return { exits, platforms, jars, echoUrl, credentialsFile, startupProbe: r.startupProbe !== false };
}
// An absolute path or one under the home directory (`~/`), no `..`, no
// whitespace (review 2 nit 8). Where it may live (the config directory, or
// ARCHILYZER_CREDENTIALS_DIR) and its owner and mode are checked when it is
// read (lib/networkCredentials-server.ts).
function looksLikePath(v: string): boolean {
if (v !== v.trim() || /\s/.test(v)) return false;
if (!v.startsWith("/") && !v.startsWith("~/")) return false;
return !v.split("/").includes("..");
}
function validEchoUrl(s: string): boolean {
if (s === "") return true;
try {
const u = new URL(s);
return (u.protocol === "http:" || u.protocol === "https:") && !u.username && !u.password;
} catch {
return false;
}
}
const NETWORK_KEYS = ["exits", "platforms", "jars", "echoUrl", "credentialsFile", "startupProbe"];
const EXIT_KEYS = ["id", "label", "scheme", "host", "port", "credentials", "enabled"];
// THE STRICT CHECK every writer refuses with — and the listing fails on: one
// sentence per problem, each naming its path. Never echoes a value that could
// be a secret.
export function networkSettingsProblems(v: unknown): string[] {
const problems: string[] = [];
if (!isObject(v)) return ["network: must be an object {exits, platforms, jars, echoUrl, credentialsFile, startupProbe}"];
for (const k of Object.keys(v)) {
if (!NETWORK_KEYS.includes(k)) problems.push(`network.${k}: not a network key (${NETWORK_KEYS.join(", ")})`);
}
const ids = new Set();
if (v.exits !== undefined && !Array.isArray(v.exits)) problems.push("network.exits: must be a list");
(Array.isArray(v.exits) ? v.exits : []).forEach((e, i) => {
const at = `network.exits[${i}]`;
if (!isObject(e)) return problems.push(`${at}: must be {${EXIT_KEYS.join(", ")}}`);
for (const k of Object.keys(e)) {
if (!EXIT_KEYS.includes(k)) {
problems.push(
`${at}.${k}: not an exit key (${EXIT_KEYS.join(", ")})` +
(k === "proxy" ? " — an exit is stored as scheme, host and port; its credentials live in network.credentialsFile" : ""),
);
}
}
const id = typeof e.id === "string" ? e.id : "";
if (id === DIRECT_EXIT) problems.push(`${at}.id: "direct" is the built-in exit with no proxy and cannot be redefined`);
else if (!EXIT_ID_RE.test(id)) problems.push(`${at}.id: lowercase letters, digits and "-", up to 40 characters`);
else if (ids.has(id)) problems.push(`${at}.id: "${id}" is defined twice`);
else ids.add(id);
if (!schemeOf(e.scheme)) problems.push(`${at}.scheme: socks5h, socks5, http or https`);
if (!hostOk(e.host)) problems.push(`${at}.host: a hostname or an IP address (no credentials, no spaces)`);
if (!portOk(e.port)) problems.push(`${at}.port: a whole number 1–65535`);
if (e.label !== undefined && typeof e.label !== "string") problems.push(`${at}.label: must be a string`);
if (e.enabled !== undefined && typeof e.enabled !== "boolean") problems.push(`${at}.enabled: must be true or false`);
if (e.credentials !== undefined && typeof e.credentials !== "boolean") problems.push(`${at}.credentials: must be true or false`);
});
if (v.platforms !== undefined && !isObject(v.platforms)) problems.push("network.platforms: must be an object keyed by platform");
for (const [platform, raw] of Object.entries(isObject(v.platforms) ? v.platforms : {})) {
const at = `network.platforms.${platform}`;
if (!isObject(raw)) {
problems.push(`${at}: must be {exits, mode: "sticky", kinds}`);
continue;
}
for (const k of Object.keys(raw)) {
if (!["exits", "mode", "kinds"].includes(k)) problems.push(`${at}.${k}: not a policy key (exits, mode, kinds)`);
}
const exits = Array.isArray(raw.exits) ? raw.exits : null;
const nonDirect = (exits ?? []).some((x) => x !== DIRECT_EXIT);
if (!(platform in TRIAL_SCOPE)) {
if (nonDirect || exits === null) problems.push(`${at}: refused — ${TRIAL_SCOPE_SENTENCE}`);
continue;
}
const kinds = raw.kinds === undefined ? ["listing"] : raw.kinds;
if (!Array.isArray(kinds) || kinds.length === 0) problems.push(`${at}.kinds: a non-empty list of request kinds`);
else {
for (const k of kinds) {
if (!(NETWORK_REQUEST_KINDS as readonly unknown[]).includes(k)) {
problems.push(`${at}.kinds: "${String(k)}" is not a request kind (${NETWORK_REQUEST_KINDS.join(", ")})`);
} else if (!isRoutable(platform, k as NetworkRequestKind) && nonDirect) {
problems.push(`${at}.kinds: "${String(k)}" refused — ${TRIAL_SCOPE_SENTENCE}`);
}
}
}
if (raw.mode !== undefined && raw.mode !== "sticky") {
problems.push(`${at}.mode: "sticky" is the only mode — a channel keeps its exit; exits are never chosen per request or at random`);
}
if (exits === null || exits.length === 0) {
problems.push(`${at}.exits: a non-empty list of exit ids ("direct" allowed)`);
continue;
}
const seen = new Set();
for (const x of exits) {
if (seen.has(x)) problems.push(`${at}.exits: "${String(x)}" is listed twice`);
seen.add(x);
if (x === DIRECT_EXIT) continue;
if (typeof x !== "string" || !ids.has(x)) problems.push(`${at}.exits: "${String(x)}" is not a defined exit`);
}
}
if (v.jars !== undefined && !isObject(v.jars)) problems.push("network.jars: must be an object keyed by jar id");
for (const [jar, exit] of Object.entries(isObject(v.jars) ? v.jars : {})) {
if (exit === DIRECT_EXIT) continue;
problems.push(`network.jars.${jar}: refused — ${JAR_TRIAL_SENTENCE}`);
}
if (v.echoUrl !== undefined && (typeof v.echoUrl !== "string" || !validEchoUrl(v.echoUrl.trim()))) {
problems.push("network.echoUrl: blank, or an http(s) URL with no credentials");
}
if (v.credentialsFile !== undefined && (typeof v.credentialsFile !== "string" || !looksLikePath(v.credentialsFile))) {
problems.push(
"network.credentialsFile: the PATH of the mode-600 file that holds the exits' credentials — the value sent is " +
"not a path; refused, not stored",
);
}
if (v.startupProbe !== undefined && typeof v.startupProbe !== "boolean") problems.push("network.startupProbe: true or false");
return problems;
}
// FNV-1a, 32 bits, over the UTF-8 bytes: stable across processes, releases
// and machines (never Math.random, never a per-process seed).
export function stableHash(s: string): number {
let h = 0x811c9dc5;
for (const b of new TextEncoder().encode(s)) {
h ^= b;
h = Math.imul(h, 0x01000193) >>> 0;
}
return h >>> 0;
}
export function stickyExitFor(slug: string, pool: readonly string[]): string {
if (pool.length === 0) return DIRECT_EXIT;
return pool[stableHash(slug) % pool.length]!;
}
// The platform's pool for `kind`: its policy's exits that are enabled (direct
// always is), in policy order; null = no policy (direct), and for a platform
// or kind outside the trial's scope.
export function exitPool(
network: NetworkSettings | undefined,
platform: string,
kind: NetworkRequestKind,
): string[] | null {
const policy = network?.platforms?.[platform];
if (!policy || !isRoutable(platform, kind) || !policy.kinds.includes(kind)) return null;
const enabled = new Set(network!.exits.filter((e) => e.enabled).map((e) => e.id));
return policy.exits.filter((id) => id === DIRECT_EXIT || enabled.has(id));
}
export function exitById(network: NetworkSettings | undefined, id: string): NetworkExit | undefined {
return network?.exits.find((e) => e.id === id);
}
// WHAT EACH OPTION MEANS is a person's classification (lib/ytdlpOptionClasses.ts);
// an option it does not list counts as `config` — a login, pinned direct.
function optionClass(long: string): YtdlpOptionClass {
return YTDLP_OPTION_CLASSES[long] ?? "config";
}
const LONG = new Map(YTDLP_OPTIONS.map(([, l, v]) => [l, v] as const));
const SHORT = new Map(YTDLP_OPTIONS.filter(([s]) => s !== null).map(([s, l, v]) => [s!, { long: l, value: v }] as const));
// yt-dlp's (optparse's) rule for a long option: the exact name, else the one
// name the argument is a prefix of. null: unknown or ambiguous — yt-dlp would
// refuse it, or it is a user alias; either way the request is not logged-out.
export function resolveLongOption(name: string): string | null {
if (LONG.has(name)) return name;
const hits = [...LONG.keys()].filter((l) => l.startsWith(name));
return hits.length === 1 ? hits[0]! : null;
}
type ArgvOption = { long: string | null; raw: string; value?: string };
// The options of an argv as yt-dlp reads them (`--` ends options; a value-
// taking option swallows its value; a short cluster is flags until a
// value-taking one, which takes the rest). Positional arguments come back as
// `{long: null}` with `raw` set... only when they hold a URL with userinfo.
function argvOptions(argv: readonly string[]): { options: ArgvOption[]; userinfoUrl: boolean } {
const options: ArgvOption[] = [];
let userinfoUrl = false;
for (let i = 0; i < argv.length; i++) {
const a = argv[i]!;
if (a === "--") {
for (const p of argv.slice(i + 1)) if (/^[a-z][a-z0-9+.-]*:\/\/[^/?#]*@/i.test(p)) userinfoUrl = true;
break;
}
if (a.startsWith("--")) {
const eq = a.indexOf("=");
const name = eq < 0 ? a : a.slice(0, eq);
const long = resolveLongOption(name);
let value: string | undefined = eq < 0 ? undefined : a.slice(eq + 1);
if (long && LONG.get(long) && value === undefined) value = argv[++i];
options.push({ long, raw: name, ...(value !== undefined ? { value } : {}) });
continue;
}
if (a.startsWith("-") && a.length > 1) {
for (let j = 1; j < a.length; j++) {
const opt = SHORT.get(a[j]!);
if (!opt) {
options.push({ long: null, raw: `-${a[j]}` });
break;
}
if (opt.value) {
const rest = a.slice(j + 1);
options.push({ long: opt.long, raw: `-${a[j]}`, value: rest !== "" ? rest : argv[++i] });
break;
}
options.push({ long: opt.long, raw: `-${a[j]}` });
}
continue;
}
if (/^[a-z][a-z0-9+.-]*:\/\/[^/?#]*@/i.test(a)) userinfoUrl = true;
}
return { options, userinfoUrl };
}
// THE LOGIN A REQUEST CARRIES, read off its final argv with yt-dlp's own
// option rules: the jar id, or null for a logged-out request. Conservative by
// design (review 1 finding 4, review 2 nit 6): a cookie, a credential, a
// token-bearing extractor argument, any extra header, another config, an
// alias, an info file, an unknown or ambiguous option, or a URL with
// userinfo pins the request. The routed listing also passes --ignore-config.
export function requestJar(argv: readonly string[]): string | null {
const { options, userinfoUrl } = argvOptions(argv);
for (const o of options) {
if (o.long === null) return "config";
if (o.long === "--cookies-from-browser") return `browser:${o.value ?? ""}`;
if (o.long === "--cookies") return `file:${o.value ?? ""}`;
const c = optionClass(o.long);
if (c === "cookie" || c === "login") return `login:${o.long}`;
if (c === "header") return "header";
if (c === "config") return "config";
}
return userinfoUrl ? "login:url" : null;
}
// The channel's own proxy in its args (`--proxy`, `--prox`, `--geo-verification-
// proxy`, …): today's request, which the channel's explicit proxy carries.
export function ownProxy(argv: readonly string[]): boolean {
return argvOptions(argv).options.some((o) => o.long !== null && YTDLP_OPTION_CLASSES[o.long] === "proxy");
}
// A JAR NEVER USES TWO EXITS: changing a jar's exit while the jar is fresh
// is refused (an account seen from two addresses invites a lock). Unused in
// the trial, where every assignment is refused earlier; built so a later
// widening cannot rotate a login by accident.
export function jarExitChangeRefusal(args: {
jar: string;
from: string | undefined;
to: string;
jarFresh: boolean;
}): string | null {
const from = args.from ?? DIRECT_EXIT;
if (from === args.to || !args.jarFresh) return null;
return (
`network.jars.${args.jar}: refused — the jar is fresh and has been used from "${from}"; an account seen ` +
`from two addresses invites a lock. Let the login expire (or log out) before giving it "${args.to}".`
);
}
// A listing that could not be sent through its network exit — the proxy did
// not answer, the settings could not be read, the recorded exit is gone, the
// credentials are missing, or yt-dlp's output did not show the proxy. Never
// retried direct.
export class NetworkExitError extends Error {
readonly exit: string;
constructor(exit: string, message: string) {
super(message);
this.name = "NetworkExitError";
this.exit = exit;
}
}
// ---------------------------------------------------------------------------
// ONE WRITE OF THE BLOCK — what `pnpm ops network` and the /settings section
// both send, applied to the stored block. Pure; the writers then refuse the
// result with networkSettingsProblems and save it through saveSettings.
//
// exits: [...] the whole list (stored form)
// upsertExit: {id, label?, proxy? | scheme?/host?/port?, credentials?, enabled?}
// removeExit: "" one exit gone — and out of every policy
// platforms: {: policy | null} merged per platform; null removes
// jars: {...} the whole map (refused in the trial unless every value is direct)
// echoUrl, credentialsFile, startupProbe
export const NETWORK_REQUEST_KEYS = [
"exits",
"upsertExit",
"removeExit",
"platforms",
"jars",
"echoUrl",
"credentialsFile",
"startupProbe",
] as const;
export class NetworkRequestError extends Error {}
export function applyNetworkRequest(current: NetworkSettings, body: Record): Record {
const unknown = Object.keys(body).filter((k) => !(NETWORK_REQUEST_KEYS as readonly string[]).includes(k));
if (unknown.length) {
throw new NetworkRequestError(`unknown key(s): ${unknown.join(", ")} — accepted: ${NETWORK_REQUEST_KEYS.join(", ")}`);
}
if (Object.keys(body).length === 0) throw new NetworkRequestError("nothing to change");
let exits: unknown[] = current.exits.map((e) => ({ ...e }));
let platforms: Record = Object.fromEntries(
Object.entries(current.platforms).map(([p, v]) => [p, { ...v, exits: [...v.exits], kinds: [...v.kinds] }]),
);
if (body.exits !== undefined) {
if (!Array.isArray(body.exits)) throw new NetworkRequestError("exits: must be a list");
exits = body.exits;
}
if (body.upsertExit !== undefined) {
const u = body.upsertExit;
if (!isObject(u) || typeof u.id !== "string") {
throw new NetworkRequestError("upsertExit: must be {id, label?, proxy?, credentials?, enabled?}");
}
const i = exits.findIndex((e) => isObject(e) && e.id === u.id);
const prev = i >= 0 ? (exits[i] as Record) : undefined;
let parts: Record = {};
if (u.proxy !== undefined) {
const p = parseProxyInput(u.proxy);
if ("error" in p) throw new NetworkRequestError(`upsertExit.proxy: ${p.error}`);
parts = p;
} else {
for (const k of ["scheme", "host", "port"]) if (u[k] !== undefined) parts[k] = u[k];
}
if (!prev && parts.host === undefined) throw new NetworkRequestError(`upsertExit: a new exit "${u.id}" needs its proxy (scheme://host:port)`);
const merged: Record = {
id: u.id,
label: u.label ?? prev?.label ?? u.id,
scheme: parts.scheme ?? prev?.scheme,
host: parts.host ?? prev?.host,
port: parts.port ?? prev?.port,
credentials: u.credentials ?? prev?.credentials ?? false,
enabled: u.enabled ?? prev?.enabled ?? true,
};
for (const k of Object.keys(u)) if (![...EXIT_KEYS, "proxy"].includes(k)) merged[k] = u[k];
if (i >= 0) exits[i] = merged;
else exits.push(merged);
}
if (body.removeExit !== undefined) {
const id = body.removeExit;
if (typeof id !== "string" || !exits.some((e) => isObject(e) && e.id === id)) {
throw new NetworkRequestError(`removeExit: no exit "${String(id)}"`);
}
exits = exits.filter((e) => !(isObject(e) && e.id === id));
for (const [p, v] of Object.entries(platforms)) {
if (!isObject(v) || !Array.isArray(v.exits)) continue;
const left = v.exits.filter((x) => x !== id);
if (left.length) platforms[p] = { ...v, exits: left };
else delete platforms[p];
}
}
if (body.platforms !== undefined) {
if (!isObject(body.platforms)) throw new NetworkRequestError("platforms: must be an object keyed by platform");
platforms = { ...platforms };
for (const [p, v] of Object.entries(body.platforms)) {
if (v === null) delete platforms[p];
else platforms[p] = v;
}
}
return {
exits,
platforms,
jars: body.jars !== undefined ? body.jars : { ...current.jars },
echoUrl: body.echoUrl !== undefined ? body.echoUrl : current.echoUrl,
credentialsFile: body.credentialsFile !== undefined ? body.credentialsFile : current.credentialsFile,
startupProbe: body.startupProbe !== undefined ? body.startupProbe : current.startupProbe,
};
}