import { test } from "node:test"; import assert from "node:assert/strict"; import { DIRECT_EXIT, NetworkRequestError, applyNetworkRequest, credentialsEnvKey, exitDisplay, exitPool, jarExitChangeRefusal, networkSettingsProblems, parseCredentials, parseProxyInput, proxyUrlOf, redactFragments, requestJar, sanitizeNetwork, secretFragmentsOf, stableHash, stickyExitFor, ownProxy, type NetworkSettings, } from "./networkExits"; import { execFileSync } from "node:child_process"; import { readFileSync, realpathSync } from "node:fs"; import { YTDLP_OPTIONS, YTDLP_OPTIONS_DUMP } from "./ytdlpOptions"; import { YTDLP_OPTION_CLASSES } from "./ytdlpOptionClasses"; // The installed yt-dlp's own option table, from its own parser, run with the // interpreter its launcher names (a pip/pipx install); null when there is no // such yt-dlp (a standalone binary, none on PATH). function installedTable(): unknown[] | null { try { const bin = realpathSync(execFileSync("sh", ["-c", "command -v yt-dlp"]).toString().trim()); const shebang = /^#!(\S+)/.exec(readFileSync(bin, "utf8").split("\n")[0] ?? "")?.[1]; if (!shebang) return null; return JSON.parse(execFileSync(shebang, ["-E", "-c", YTDLP_OPTIONS_DUMP], { timeout: 60_000 }).toString()).rows; } catch { return null; } } const INSTALLED = installedTable(); // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test lib/networkExits.test.ts // // REVIEW 1 (finding 1): a proxy's credentials are never a setting and never // masked by pattern. The settings hold the exit's id, scheme, host, port and // whether it has credentials; the secret lives in the key file // (lib/networkCredentials-server.ts). Every answer is built from that form. function exit(id: string, extra: Record = {}) { return { id, label: id.toUpperCase(), scheme: "socks5h", host: `${id}.example.test`, port: 1080, credentials: false, enabled: true, ...extra }; } function net(extra: Partial = {}): NetworkSettings { return sanitizeNetwork({ exits: [exit("exit-a", { credentials: true }), exit("exit-b")], platforms: { rumble: { exits: ["exit-a", "exit-b"], mode: "sticky" } }, ...extra, }); } test("the stored form has no secret: id, scheme, host, port, credentials yes/no", () => { const n = net(); assert.deepEqual(n.exits[0], { id: "exit-a", label: "EXIT-A", scheme: "socks5h", host: "exit-a.example.test", port: 1080, credentials: true, enabled: true }); assert.equal(exitDisplay(n.exits[0]!), "socks5h://exit-a.example.test:1080 (credentials)"); assert.equal(exitDisplay(n.exits[1]!), "socks5h://exit-b.example.test:1080"); assert.equal(n.credentialsFile, "~/.config/archilyzer/network-exits.env"); assert.equal(n.startupProbe, true); assert.deepEqual(networkSettingsProblems(n), []); }); test("a proxy URL with credentials is refused at save; raw special characters get the encoding sentence", () => { for (const pw of ["pa'ss", 'pa"ss', "pa ss", "pa=user:password/); assert.ok(!enc.error.includes("pa%27ss")); assert.deepEqual(parseProxyInput("socks5h://h.example.test:1080"), { scheme: "socks5h", host: "h.example.test", port: 1080 }); assert.deepEqual(parseProxyInput("HTTP://127.0.0.1:3128"), { scheme: "http", host: "127.0.0.1", port: 3128 }); for (const bad of ["socks4://h:1", "socks5h://h:1/path", "socks5h://h", "socks5h://h\t:1", "socks5h://@h:1"]) { assert.ok("error" in parseProxyInput(bad), bad); } }); test("credentials in the key file: user:password, percent-encoded, unreserved only", () => { assert.deepEqual(parseCredentials("example-user:fake%27value"), { username: "example-user", password: "fake'value", encoded: "example-user:fake%27value" }); for (const raw of ["user:pa'ss", "user:p@ss", "user:pa ss", "user:pa\\ss", "nouser", "user:pa%zz"]) { const r = parseCredentials(raw); assert.ok("error" in r, raw); assert.match(r.error, /percent-encode/); assert.ok(!r.error.includes(raw.split(":")[1] ?? raw)); } assert.equal(credentialsEnvKey("nl-ams-1"), "NETWORK_EXIT_NL_AMS_1"); }); test("the proxy URL is built from the parsed parts; the fragments are exact values", () => { const n = net(); const creds = parseCredentials("example-user:fake%27value"); assert.ok(!("error" in creds)); assert.equal(proxyUrlOf(n.exits[0]!, creds), "socks5h://example-user:fake%27value@exit-a.example.test:1080"); assert.equal(proxyUrlOf(n.exits[1]!, null), "socks5h://exit-b.example.test:1080"); const frags = secretFragmentsOf(creds); for (const f of ["example-user:fake%27value", "fake%27value", "fake'value", "fake\\'value", "example-user"]) assert.ok(frags.includes(f), f); const line = "[debug] | Stdin config: ['--proxy', 'socks5h://example-user:fake%27value@exit-a.example.test:1080'] fake\\'value"; const red = redactFragments(line, frags); assert.ok(!red.includes("fake") && !red.includes("example-user"), red); // Exact values, no pattern: text without them is untouched. assert.equal(redactFragments("https://example.org?mail=a@b.example", frags), "https://example.org?mail=a@b.example"); }); test("a policy for rumble or twitch listings is accepted; another platform, kind or a jar is refused", () => { assert.deepEqual(networkSettingsProblems(net({ platforms: { twitch: { exits: ["direct", "exit-b"], mode: "sticky", kinds: ["listing"] } } })), []); const yt = networkSettingsProblems({ ...net(), platforms: { youtube: { exits: ["exit-a"], mode: "sticky" } } }); assert.match(yt[0]!, /^network\.platforms\.youtube: refused — the network-exit trial routes only the listing requests of rumble and twitch/); const kind = networkSettingsProblems({ ...net(), platforms: { rumble: { exits: ["exit-a"], kinds: ["listing", "download"] } } }); assert.match(kind[0]!, /kinds: "download" refused/); const jar = networkSettingsProblems({ ...net(), jars: { "browser:firefox": "exit-a" } }); assert.match(jar[0]!, /network\.jars\.browser:firefox: refused — a request that carries a login/); const mode = networkSettingsProblems({ ...net(), platforms: { rumble: { exits: ["exit-a"], mode: "random" } } }); assert.match(mode[0]!, /mode: "sticky" is the only mode/); const keyFile = networkSettingsProblems({ ...net(), credentialsFile: "a-pasted-value" }); assert.match(keyFile[0]!, /credentialsFile: the PATH of the mode-600 file/); assert.ok(!keyFile[0]!.includes("a-pasted-value")); const oldShape = networkSettingsProblems({ exits: [{ id: "x", proxy: "socks5h://u:p@h:1" }] }); assert.ok(oldShape.some((p) => /exits\[0\]\.proxy: not an exit key/.test(p))); assert.ok(oldShape.every((p) => !p.includes("u:p"))); }); test("the sticky choice is a stable hash of the slug over the pool, never random", () => { assert.equal(stableHash(""), 0x811c9dc5); const pool = ["exit-a", "exit-b", "direct"]; const first = stickyExitFor("demo-rumble", pool); for (let i = 0; i < 50; i++) assert.equal(stickyExitFor("demo-rumble", pool), first); const seen = new Set(Array.from({ length: 60 }, (_, i) => stickyExitFor(`channel-${i}`, pool))); assert.deepEqual([...seen].sort(), [...pool].sort()); assert.equal(stickyExitFor("x", []), DIRECT_EXIT); }); test("the pool skips disabled exits; out-of-scope is null", () => { const n = net(); assert.deepEqual(exitPool(n, "rumble", "listing"), ["exit-a", "exit-b"]); n.exits[0]!.enabled = false; assert.deepEqual(exitPool(n, "rumble", "listing"), ["exit-b"]); assert.equal(exitPool(n, "rumble", "download"), null); assert.equal(exitPool(sanitizeNetwork({ ...net(), platforms: { youtube: { exits: ["exit-a"] } } }), "youtube", "listing"), null); }); test("requestJar resolves options by yt-dlp's own prefix rule over its option table (review 2 nit 6)", () => { const base = ["--flat-playlist", "--skip-download", "--print", "url", "--impersonate", "chrome", "-I", "1:50", "--sleep-requests", "1", "--user-agent", "UA"]; assert.equal(requestJar(base), null); const pinned: Array<[string[], string]> = [ [["--cookies-from-browser", "firefox"], "browser:firefox"], [["--cookies-from-b", "firefox"], "browser:firefox"], [["--cookies=/tmp/jar.txt"], "file:/tmp/jar.txt"], [["--add-headers", "X-Any: 1"], "header"], [["--add-header=Referer: x"], "header"], [["--username", "u"], "login:--username"], [["--pas", "x"], "login:--password"], [["-u", "u"], "login:--username"], [["-n"], "login:--netrc"], [["-vn"], "login:--netrc"], [["--netrc-cmd", "x"], "login:--netrc-cmd"], [["--config-locations", "/etc/x.conf"], "config"], [["--alias", "get-c,-X", "--cookies-from-browser firefox"], "config"], [["--load-info-json", "/tmp/i.json"], "config"], [["--extractor-args", "twitch:client_id=x"], "login:--extractor-args"], [["--made-up-alias"], "config"], [["https://example-user:fake-value@rumble.com/c/demo"], "login:url"], ]; for (const [extra, jar] of pinned) assert.equal(requestJar([...base, ...extra]), jar, extra.join(" ")); // A value glued to a short option is a value, not flags: -f22 is a format. assert.equal(requestJar([...base, "-f22", "-o", "-n"]), null); assert.equal(requestJar(["--", "--cookies-from-browser"]), null); }); test("ownProxy: --proxy in any unambiguous spelling is the channel's own proxy (review 2 nit 6)", () => { for (const a of [["--proxy", ""], ["--prox", ""], ["--proxy="], ["--geo-verification-proxy", "x"]]) assert.equal(ownProxy(a), true, a.join(" ")); assert.equal(ownProxy(["--print", "url"]), false); }); test("the option table is the installed yt-dlp's (fails when yt-dlp adds, renames or re-arities an option)", { skip: INSTALLED === null ? "no python yt-dlp on PATH" : false }, () => { assert.deepEqual(INSTALLED, YTDLP_OPTIONS.map(([s, l, v]) => [s, l, v])); }); test("credentialsFile: an absolute or ~/ path, no .. — anything else is refused (review 2 nit 8)", () => { for (const bad of ["user:pa/ss", "relative/keys.env", "/a/../b.env", "~/x/../y.env", "~user/keys.env", " /x.env"]) { assert.match(networkSettingsProblems({ ...net(), credentialsFile: bad })[0] ?? "", /credentialsFile/, bad); } for (const ok of ["~/.config/archilyzer/network-exits.env", "/home/example/.config/x.env"]) assert.deepEqual(networkSettingsProblems({ ...net(), credentialsFile: ok }), [], ok); }); test("a jar's exit is not changed while it is fresh", () => { assert.equal(jarExitChangeRefusal({ jar: "browser:firefox", from: undefined, to: "direct", jarFresh: true }), null); assert.match(jarExitChangeRefusal({ jar: "browser:firefox", from: "direct", to: "exit-a", jarFresh: true })!, /invites a lock/); }); test("applyNetworkRequest: a proxy URL fills the fields; credentials only as yes/no; remove leaves policies", () => { const cur = net(); const up = applyNetworkRequest(cur, { upsertExit: { id: "exit-c", proxy: "socks5h://exit-c.example.test:1080", credentials: true } }); assert.deepEqual((up.exits as unknown[])[2], { id: "exit-c", label: "exit-c", scheme: "socks5h", host: "exit-c.example.test", port: 1080, credentials: true, enabled: true }); assert.throws(() => applyNetworkRequest(cur, { upsertExit: { id: "exit-c", proxy: "socks5h://u:fake%40value@h:1" } }), /credentials are not a setting/); const off = applyNetworkRequest(cur, { upsertExit: { id: "exit-a", enabled: false } }); assert.equal((off.exits as Array<{ enabled: boolean; host: string }>)[0]!.enabled, false); assert.equal((off.exits as Array<{ host: string }>)[0]!.host, "exit-a.example.test"); const rm = applyNetworkRequest(cur, { removeExit: "exit-a" }); assert.deepEqual((rm.platforms as Record).rumble!.exits, ["exit-b"]); assert.throws(() => applyNetworkRequest(cur, { bogus: 1 }), NetworkRequestError); assert.throws(() => applyNetworkRequest(cur, { upsertExit: { id: "new" } }), /needs its proxy/); const probeOff = applyNetworkRequest(cur, { startupProbe: false }); assert.equal(probeOff.startupProbe, false); }); test("every option of the table is classified by a person (review 3 nit 5): a new one fails until it is", () => { const unclassified = [...new Set(YTDLP_OPTIONS.map(([, l]) => l))].filter((l) => !(l in YTDLP_OPTION_CLASSES)); assert.deepEqual(unclassified, []); const stale = Object.keys(YTDLP_OPTION_CLASSES).filter((l) => !YTDLP_OPTIONS.some(([, x]) => x === l)); assert.deepEqual(stale, []); // And an option the classes do not know is a login at run time. assert.equal(requestJar(["--flat-playlist", "--plugin-dirs", "/x"]), "config"); assert.equal(requestJar(["--flat-playlist", "--xff", "US"]), "header"); assert.equal(requestJar(["--flat-playlist", "--mark-watched"]), "login:--mark-watched"); assert.equal(requestJar(["--flat-playlist", "--referer", "https://example.test/"]), null); });