import { test, after, beforeEach } from "node:test"; import assert from "node:assert/strict"; import { mkdtempSync, writeFileSync, chmodSync, mkdirSync, readFileSync, readdirSync, statSync, existsSync, rmSync } from "node:fs"; import os from "node:os"; import path from "node:path"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/networkExitListing.test.ts // // THE LISTING THROUGH NAMED NETWORK EXITS (lane network-exits), end to end // below yt-dlp: a stand-in yt-dlp records its argv, stdin and proxy // environment and behaves like yt-dlp about proxies (the stdin `--proxy`, // else the environment's ALL_PROXY, else DIRECT — to a listening trap socket, // so a fall-back to direct is SEEN). The exits are in-process fake SOCKS5 // proxies on loopback. ytdlp/networkExitRealYtdlp.test.ts runs the real // binary. getPaths() memoizes, so the env is set before anything imports it. const ROOT = mkdtempSync(path.join(os.tmpdir(), "network-exits-")); process.env.TRANSCRIPTS_DIR = ROOT; process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); process.env.ARCHILYZER_CREDENTIALS_DIR = ROOT; writeFileSync(process.env.SETTINGS_FILE, "{}\n"); const { fetchFlatPlaylistUrls, runYtdlp, EnumerationIncompleteError, NetworkExitError } = await import("./runYtdlp"); const { readListingEvidence } = await import("../controller/listingEvidence"); const { getPaths } = await import("../lib/paths"); const { JobDeferredError } = await import("../jobs/jobDeferred"); const { platformCooldownRemainingMs } = await import("../jobs/downloadBackoff"); const { stickyExitFor } = await import("../lib/networkExits"); const NE = await import("../controller/networkExits"); const { downloadQueueKey } = await import("../lib/queueKeys"); const { waitForQueueGap, noteQueueJobEnd, clearQueueGaps } = await import("../jobs/queueGap"); const { withRumbleDefaults } = await import("../lib/rumbleDefaults"); const { closedPort, startCountingServer, startEchoServer, startFakeSocks5 } = await import("../testing/fakeProxy"); const FAKE_CRED = "fake-not-a-credential"; const trap = await startCountingServer(); const proxyA = await startFakeSocks5({ username: "example-user-a", password: FAKE_CRED, route: () => null }); const proxyB = await startFakeSocks5({ route: () => null }); after(async () => { await Promise.all([trap.close(), proxyA.close(), proxyB.close()]); rmSync(ROOT, { recursive: true, force: true }); }); // The key file (the repo's convention): mode 600, its PATH a setting. const KEYS = path.join(ROOT, "network-exits.env"); writeFileSync(KEYS, `NETWORK_EXIT_EXIT_A=example-user-a:${FAKE_CRED}\n`); chmodSync(KEYS, 0o600); const PROXY_A_URL = `socks5h://example-user-a:${FAKE_CRED}@127.0.0.1:${proxyA.port}`; const RECORD = path.join(ROOT, "spawns.jsonl"); const BIN = path.join(ROOT, "fake-listing.mjs"); writeFileSync( BIN, `#!/usr/bin/env node import { appendFileSync, readFileSync } from "node:fs"; import net from "node:net"; const argv = process.argv.slice(2); const mode = process.env.FAKE_MODE ?? "ok"; const ci = argv.indexOf("--config-locations"); const stdin = ci >= 0 && argv[ci + 1] === "-" && mode !== "ignore-stdin" ? readFileSync(0, "utf8") : null; const envProxy = {}; for (const k of ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "all_proxy", "no_proxy"]) if (process.env[k] !== undefined) envProxy[k] = process.env[k]; appendFileSync(process.env.FAKE_RECORD, JSON.stringify({ argv, stdin, envProxy }) + "\\n"); const stdinProxy = stdin ? /--proxy '([^']*)'/.exec(stdin)?.[1] : undefined; const proxy = stdinProxy ?? process.env.ALL_PROXY ?? process.env.all_proxy; if (argv.includes("-v")) process.stderr.write("[debug] | Stdin config: " + JSON.stringify(stdin) + "\\n"); if (argv.includes("-v") && proxy && mode !== "no-map" && mode !== "no-map-429") process.stderr.write("[debug] Proxy map: {'all': '" + proxy + "'}\\n"); if (mode === "slow") { process.stdout.write("https://rumble.com/v1-a.html\\n"); await new Promise((r) => setTimeout(r, 3000)); } const finish = () => { if (mode === "429" || mode === "no-map-429") { process.stdout.write("https://rumble.com/v1-a.html\\n"); process.stderr.write("[RumbleChannel] x: Downloading page 2\\nERROR: [RumbleChannel] x: Unable to download webpage: HTTP Error 429: Too Many Requests\\n"); process.exit(1); } process.stdout.write("https://rumble.com/v1-a.html\\nhttps://rumble.com/v2-b.html\\n"); }; if (stdinProxy) finish(); else { // No stdin proxy: like yt-dlp, the environment's proxy, else DIRECT. const port = proxy ? Number(new URL(proxy).port) : Number(process.env.FAKE_TRAP_PORT); const s = net.connect(port, "127.0.0.1", () => { s.destroy(); finish(); }); s.on("error", () => { process.stderr.write("ERROR: Unable to connect\\n"); process.exit(1); }); } `, ); chmodSync(BIN, 0o755); process.env.FAKE_RECORD = RECORD; process.env.FAKE_TRAP_PORT = String(trap.port); function exitRow(id: string, port: number, extra: Record = {}) { return { id, label: id.toUpperCase(), scheme: "socks5h", host: "127.0.0.1", port, credentials: false, enabled: true, ...extra }; } const EXITS = [exitRow("exit-a", proxyA.port, { credentials: true }), exitRow("exit-b", proxyB.port)]; const RUMBLE_POLICY = { exits: EXITS, platforms: { rumble: { exits: ["exit-a", "exit-b"], mode: "sticky" } }, credentialsFile: KEYS }; function settings(network?: unknown, extra: Record = {}) { writeFileSync( process.env.SETTINGS_FILE!, JSON.stringify({ pacing: { jitter: 0 }, ...extra, ...(network ? { network } : {}) }) + "\n", ); } const SLUGS = Array.from({ length: 40 }, (_, i) => `demo-rumble-${i}`); const ON_A = SLUGS.find((s) => stickyExitFor(s, ["exit-a", "exit-b"]) === "exit-a")!; const ON_B = SLUGS.find((s) => stickyExitFor(s, ["exit-a", "exit-b"]) === "exit-b")!; type Spawn = { argv: string[]; stdin: string | null; envProxy: Record }; function spawns(): Spawn[] { if (!existsSync(RECORD)) return []; return readFileSync(RECORD, "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l)); } async function list(slug: string, config: Record = {}, log: string[] = [], holder?: object) { mkdirSync(path.join(ROOT, "channels", slug), { recursive: true }); writeFileSync( path.join(ROOT, "channels", slug, "config.json"), JSON.stringify({ handling: "transcribe", url: "https://rumble.com/c/demo", ...config }), ); return fetchFlatPlaylistUrls({ channelConfig: { handling: "transcribe", url: "https://rumble.com/c/demo", ...config } as never, paths: { ...getPaths(), ytdlpBin: BIN }, channelSlug: slug, onLog: (s: string) => log.push(s), signal: new AbortController().signal, ...(holder ? { listingRoute: holder } : {}), } as never); } // Today's rumble listing argv (main a0ef2b1ae), pacing jitter off. const MAIN_ARGV = ["--flat-playlist", "--skip-download", "--print", "url", "--impersonate", "chrome", "--sleep-requests", "1", "https://rumble.com/c/demo"]; const ROUTED_PREFIX = ["--ignore-config", "--config-locations", "-", "-v"]; const PROXY_VARS = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "all_proxy", "no_proxy"]; beforeEach(() => { rmSync(RECORD, { force: true }); rmSync(path.join(ROOT, ".network"), { recursive: true, force: true }); rmSync(path.join(ROOT, ".auto-queue"), { recursive: true, force: true }); for (const d of existsSync(path.join(ROOT, "channels")) ? readdirSync(path.join(ROOT, "channels")) : []) { rmSync(path.join(ROOT, "channels", d, "network-exit.json"), { force: true }); } for (const k of PROXY_VARS) delete process.env[k]; process.env.FAKE_MODE = "ok"; }); test("no policy: the argv, the echo, the environment and the files are today's", async () => { settings(); process.env.HTTPS_PROXY = "http://127.0.0.1:2"; const log: string[] = []; assert.deepEqual(await list(ON_A, {}, log), ["https://rumble.com/v1-a.html", "https://rumble.com/v2-b.html"]); assert.deepEqual(spawns(), [{ argv: MAIN_ARGV, stdin: null, envProxy: { HTTPS_PROXY: "http://127.0.0.1:2" } }]); assert.deepEqual(log, [`$ ${BIN} ${MAIN_ARGV.join(" ")}\n`]); assert.ok(!existsSync(path.join(ROOT, ".network"))); assert.ok(!existsSync(NE.channelExitPath(getPaths(), ON_A))); }); test("through an exit: --ignore-config, the proxy on stdin only, every proxy variable dead or gone (findings 2-4)", async () => { settings(RUMBLE_POLICY); process.env.NO_PROXY = "*"; process.env.no_proxy = "*"; process.env.HTTPS_PROXY = "http://127.0.0.1:2"; const log: string[] = []; await list(ON_A, {}, log); const [s] = spawns(); assert.deepEqual(s!.argv, [...ROUTED_PREFIX, ...MAIN_ARGV]); assert.equal(s!.stdin, `--proxy '${PROXY_A_URL}'\n`); // NO_PROXY gone; the proxy variables point at a loopback port that refuses. assert.deepEqual(Object.keys(s!.envProxy).sort(), ["ALL_PROXY", "HTTPS_PROXY", "HTTP_PROXY", "all_proxy", "http_proxy", "https_proxy"]); for (const v of Object.values(s!.envProxy)) assert.equal(v, "socks5h://127.0.0.1:1"); const text = log.join(""); assert.ok(!text.includes(FAKE_CRED) && !text.includes("example-user-a"), text); assert.ok(!text.includes("[debug]"), "yt-dlp's debug lines stay out of the job log"); assert.match(text, new RegExp(`Network exit: "exit-a" \\(socks5h://127\\.0\\.0\\.1:${proxyA.port} \\(credentials\\)\\)`)); assert.match(text, /yt-dlp confirmed the listing's proxy is exit "exit-a"/); }); test("a direct spawn under a policy has every inherited proxy variable removed (finding 2)", async () => { settings(RUMBLE_POLICY); process.env.HTTPS_PROXY = "http://127.0.0.1:2"; process.env.no_proxy = "*"; await list(ON_A, { cookiesFromBrowser: "firefox", cookieMode: "always" }); const [s] = spawns(); assert.ok(!s!.argv.includes("--config-locations")); assert.deepEqual(s!.envProxy, {}); }); test("a child that ignores stdin meets the dead proxy, never the direct path (finding 3)", async () => { settings(RUMBLE_POLICY); process.env.FAKE_MODE = "ignore-stdin"; const before = trap.connections(); await assert.rejects(list(ON_B), /through network exit "exit-b"|did not show/); assert.equal(trap.connections(), before, "nothing reached the direct path"); }); test("a listing whose output does not show the proxy is discarded and fails closed (finding 3)", async () => { settings(RUMBLE_POLICY); process.env.FAKE_MODE = "no-map"; await assert.rejects(list(ON_B), (err: unknown) => { assert.ok(err instanceof NetworkExitError); assert.match(err.message, /could not show that the rumble listing went through network exit "exit-b" — its result is discarded/); return true; }); }); test("sticky: chosen once by the hash, recorded, kept; adding an exit moves no one", async () => { settings(RUMBLE_POLICY); await list(ON_B); assert.equal((await NE.readChannelExitRecord(getPaths(), ON_B))!.exit, "exit-b"); settings({ ...RUMBLE_POLICY, exits: [...EXITS, exitRow("exit-c", proxyB.port)], platforms: { rumble: { exits: ["exit-c", "exit-a", "exit-b"] } } }); await list(ON_B); assert.equal((await NE.readChannelExitRecord(getPaths(), ON_B))!.exit, "exit-b"); }); test("a recorded exit disabled or removed FAILS the listing; nothing re-chooses it (finding 5)", async () => { settings(RUMBLE_POLICY); await list(ON_A); const n = spawns().length; for (const net of [ { ...RUMBLE_POLICY, exits: [{ ...EXITS[0], enabled: false }, EXITS[1]] }, { ...RUMBLE_POLICY, exits: [EXITS[1]], platforms: { rumble: { exits: ["exit-b"] } } }, ]) { settings(net); await assert.rejects(list(ON_A), (err: unknown) => { assert.ok(err instanceof NetworkExitError); assert.match(err.message, /recorded network exit "exit-a" is no longer an enabled exit of rumble .* pnpm ops network-exit/); return true; }); } assert.equal(spawns().length, n); assert.equal((await NE.readChannelExitRecord(getPaths(), ON_A))!.exit, "exit-a"); // A policy taken away on purpose is direct again. settings({ ...RUMBLE_POLICY, platforms: {} }); await list(ON_A); assert.deepEqual(spawns().at(-1)!.argv, MAIN_ARGV); }); test("unreadable settings, a broken network block, or missing credentials fail the listing, never direct (finding 5)", async () => { settings(RUMBLE_POLICY); await list(ON_A); const n = spawns().length; writeFileSync(process.env.SETTINGS_FILE!, "{ not json"); await assert.rejects(list(ON_A), /settings\.json could not be read .* the rumble listing was not sent/); await assert.rejects(list(ON_B), /settings\.json could not be read/); settings({ ...RUMBLE_POLICY, exits: [{ ...EXITS[0], host: "bad host" }, EXITS[1]] }); await assert.rejects(list(ON_A), /network settings do not validate: network\.exits\[0\]\.host/); settings({ ...RUMBLE_POLICY, credentialsFile: path.join(ROOT, "absent.env") }); await assert.rejects(list(ON_A), /exit "exit-a" needs credentials/); assert.equal(spawns().length, n); }); test("reassign only by the action: network-exit {slug, exit}", async () => { settings(RUMBLE_POLICY); await list(ON_A); assert.deepEqual(await NE.assignChannelExit({ paths: getPaths(), slug: ON_A, exit: "exit-b" }), { slug: ON_A, platform: "rumble", exit: "exit-b", previous: "exit-a" }); await list(ON_A); assert.ok(spawns().at(-1)!.stdin!.includes(`:${proxyB.port}`)); await NE.assignChannelExit({ paths: getPaths(), slug: ON_A, exit: "direct" }); await list(ON_A); assert.deepEqual(spawns().at(-1)!.argv, MAIN_ARGV); await assert.rejects(NE.assignChannelExit({ paths: getPaths(), slug: ON_A, exit: "exit-z" }), /no exit "exit-z"/); }); test("cookies supplied any way keep the listing direct (finding 4)", async () => { const ways: Array<[string, Record, Record]> = [ ["global browser cookies, always", {}, { cookiesFromBrowser: "firefox", cookieMode: "always" }], ["channel browser cookies, always", { cookiesFromBrowser: "firefox", cookieMode: "always" }, {}], ["a cookie file", { ytdlpExtraArgs: ["--cookies", "/tmp/jar.txt"] }, {}], ["an abbreviated option", { ytdlpExtraArgs: ["--cookies-from-b", "firefox"] }, {}], ["a header", { ytdlpExtraArgs: ["--add-headers", "Cookie: cf_clearance=x"] }, {}], ["a config file", { ytdlpExtraArgs: ["--config-locations", "/tmp/yt.conf"] }, {}], ["netrc", { ytdlpExtraArgs: ["-n"] }, {}], ["a Rumble channel made with the defaults", withRumbleDefaults({ handling: "transcribe", platform: "rumble", url: "https://rumble.com/c/demo" } as never) as never, {}], ]; for (const [what, config, global] of ways) { settings(RUMBLE_POLICY, global); rmSync(RECORD, { force: true }); const log: string[] = []; await list(ON_A, config, log); const [s] = spawns(); assert.ok(!s!.argv.includes("--config-locations") || s!.argv.indexOf("--config-locations") > 3, what); assert.equal(s!.stdin, null, what); assert.match(log.join(""), /Network exit: direct \(this listing carries a login/, what); } }); test("a 429 through an exit rests that exit only; its channels wait; when both rest the platform is due", async () => { settings(RUMBLE_POLICY); process.env.FAKE_MODE = "429"; await assert.rejects(list(ON_A), (err: unknown) => { assert.ok(err instanceof EnumerationIncompleteError); assert.equal(err.exit, "exit-a"); assert.equal(err.platformBackoffDue, false); return true; }); assert.equal(await platformCooldownRemainingMs("rumble", getPaths()), 0); process.env.FAKE_MODE = "ok"; const before = spawns().length; await assert.rejects(list(ON_A), (err: unknown) => err instanceof JobDeferredError && /rests until/.test(err.message)); assert.equal(spawns().length, before, "no hop: nothing was sent"); assert.equal((await list(ON_B)).length, 2); process.env.FAKE_MODE = "429"; await assert.rejects(list(ON_B), (err: unknown) => err instanceof EnumerationIncompleteError && err.platformBackoffDue === true); }); test("one job, one exit: the route is pinned for every page; a rest mid-walk defers, never switches (finding 7)", async () => { settings(RUMBLE_POLICY); const job = {}; await list(ON_A, {}, [], job); // A reassignment between two pages of the same job. await NE.assignChannelExit({ paths: getPaths(), slug: ON_A, exit: "exit-b" }); await list(ON_A, {}, [], job); const [p1, p2] = spawns(); assert.equal(p1!.stdin, p2!.stdin, "page 2 left by page 1's exit"); assert.ok(p2!.stdin!.includes(`:${proxyA.port}`)); // The next job takes the new assignment. await list(ON_A); assert.ok(spawns().at(-1)!.stdin!.includes(`:${proxyB.port}`)); // The pinned exit goes to rest mid-walk: the job defers. await NE.restExit(getPaths(), "rumble", "exit-a", ["exit-a", "exit-b"]); await assert.rejects(list(ON_A, {}, [], job), JobDeferredError); }); test("a dead proxy fails closed: named error, nothing spawned, the direct trap untouched", async () => { const dead = await closedPort(); const trapBefore = trap.connections(); settings({ ...RUMBLE_POLICY, exits: [exitRow("exit-a", dead, { credentials: true })], platforms: { rumble: { exits: ["exit-a"] } } }); await assert.rejects(list(ON_A), (err: unknown) => { assert.ok(err instanceof NetworkExitError); assert.match(err.message, /^network exit "exit-a" \(socks5h:\/\/127\.0\.0\.1:\d+ \(credentials\)\) did not answer: connection refused\. The rumble listing was not sent — a listing never falls back to direct\.$/); return true; }); assert.deepEqual(spawns(), []); assert.equal(trap.connections(), trapBefore, "nothing reached the direct path"); }); test("the secret appears in no log, error, record, report or settings answer", async () => { settings(RUMBLE_POLICY); const log: string[] = []; await list(ON_A, {}, log); process.env.FAKE_MODE = "429"; let message = ""; await list(ON_A, {}, log).catch((e: Error) => (message = e.message)); assert.ok(message.length > 0); const report = JSON.stringify(await NE.networkReport(getPaths())); const files: string[] = []; const walk = (d: string) => { for (const n of readdirSync(d)) { const p = path.join(d, n); if (statSync(p).isDirectory()) walk(p); else if (![KEYS, RECORD].includes(p)) files.push(readFileSync(p, "utf8")); } }; walk(ROOT); for (const [what, text] of [["log", log.join("")], ["error", message], ["report", report], ["files incl. settings.json", files.join("\n")]] as const) { assert.ok(!text.includes(FAKE_CRED), `${what} carries the secret`); assert.ok(!text.includes("example-user-a:"), `${what} carries the userinfo`); } }); test("pacing per platform: two exits make the same requests per hour as one, at main's pace", async () => { const config = { handling: "transcribe", url: "https://rumble.com/c/demo" } as never; const run = async (slugs: string[]) => { rmSync(RECORD, { force: true }); clearQueueGaps(); let now = 1_000_000; const clock = { now: () => now, sleep: async (ms: number) => void (now += ms) }; const pacing = () => ({ jobGapSeconds: { rumble: 120 }, jitter: 0 }); const jobsDir = mkdtempSync(path.join(ROOT, "jobs-")); for (let i = 0; ; i++) { // The queue a listing waits on is named from its channel alone. const queueKey = downloadQueueKey(config); await waitForQueueGap({ paths: { jobsDir }, queueKey, pacing, clock }); if (now >= 1_000_000 + 3_600_000) break; await list(slugs[i % slugs.length]!); now += 5_000; await noteQueueJobEnd({ jobsDir }, queueKey, now); } return spawns(); }; settings({ ...RUMBLE_POLICY, platforms: { rumble: { exits: ["exit-a"] } } }); const one = await run([ON_A]); settings(RUMBLE_POLICY); const two = await run([ON_A, ON_B]); assert.equal(one.length, 29); assert.equal(two.length, one.length); for (const s of [...one, ...two]) assert.deepEqual(s.argv.slice(ROUTED_PREFIX.length), MAIN_ARGV); assert.deepEqual(new Set(two.map((s) => /127\.0\.0\.1:(\d+)/.exec(s.stdin!)![1])), new Set([String(proxyA.port), String(proxyB.port)])); }); test("the probe: connect-only at startup (no echo, can be off); the echo only when asked (finding 6)", async () => { const echo = await startEchoServer("198.51.100.23\n"); const routed = await startFakeSocks5({ route: (host, port) => (host === "echo.exit.test" ? { host: "127.0.0.1", port } : null) }); try { const exits = [exitRow("exit-a", routed.port), exitRow("exit-dead", await closedPort())]; const net = { exits, platforms: {}, credentialsFile: KEYS, echoUrl: `http://echo.exit.test:${echo.port}/` }; settings(net); const lines: string[] = []; NE.startupNetworkProbe({ log: (l) => lines.push(l), delayMs: 0, paths: getPaths() }); for (let i = 0; i < 100 && lines.length < 2; i++) await new Promise((r) => setTimeout(r, 20)); assert.deepEqual(lines.map((l) => l.split(":")[0]).sort(), ['network exit "exit-a"', 'network exit "exit-dead"']); assert.equal(echo.hits(), 0, "the startup probe sends no echo request"); assert.equal(routed.greetings, 0, "and no SOCKS greeting: a connection only"); assert.ok(routed.connections > 0); // Off: nothing at all. settings({ ...net, startupProbe: false }); const before = routed.connections; const quiet: string[] = []; NE.startupNetworkProbe({ log: (l) => quiet.push(l), delayMs: 0, paths: getPaths() }); await new Promise((r) => setTimeout(r, 300)); assert.equal(routed.connections, before); assert.deepEqual(quiet, []); // The operator's explicit probe fetches the echo through the exit. const loud = await NE.probeNetworkExits(getPaths(), undefined, new Date(), { explicit: true }); assert.equal(loud.exits["exit-a"]!.address, "198.51.100.23"); assert.equal(echo.hits(), 1); } finally { await Promise.all([echo.close(), routed.close()]); } }); test("in scope in a synthetic corpus: cookie-free Rumble channels and Twitch channels", () => { const rumble = (extra: Record) => ({ handling: "transcribe", platform: "rumble", url: "https://rumble.com/c/x", ...extra }); const corpus = [ withRumbleDefaults(rumble({}) as never), withRumbleDefaults(rumble({}) as never), withRumbleDefaults(rumble({}) as never), rumble({ cookieMode: "when-required", cookiesFromBrowser: "firefox", ytdlpExtraArgs: ["--impersonate", "firefox"] }), rumble({ ytdlpExtraArgs: ["--impersonate", "chrome"] }), { handling: "transcribe", url: "https://www.twitch.tv/x/videos" }, { handling: "transcribe", url: "https://www.twitch.tv/y/videos", cookiesFromBrowser: "firefox", cookieMode: "always" }, { handling: "youtube", url: "https://www.youtube.com/@x" }, ]; const inScope = corpus.filter((c) => NE.listingRoutable(c as never, { cookiesFromBrowser: "", cookieMode: "when-required" })); assert.equal(inScope.length, 3); }); test("a policy whose exits are all disabled fails the listing; direct only when the policy names it (review 2 finding 3)", async () => { settings({ ...RUMBLE_POLICY, exits: EXITS.map((e) => ({ ...e, enabled: false })) }); const fresh = "demo-rumble-unlisted"; await assert.rejects(list(fresh), (err: unknown) => { assert.ok(err instanceof NetworkExitError); assert.match(err.message, /network\.platforms\.rumble has no enabled exit .* the exits were turned off but the policy left in place/); return true; }); assert.equal(await NE.readChannelExitRecord(getPaths(), fresh), null, "nothing recorded"); assert.deepEqual(spawns(), []); // A policy that NAMES direct may send a channel direct, and records it so. settings({ ...RUMBLE_POLICY, exits: EXITS.map((e) => ({ ...e, enabled: false })), platforms: { rumble: { exits: ["direct", "exit-a"] } } }); await list(fresh); assert.equal((await NE.readChannelExitRecord(getPaths(), fresh))!.exit, "direct"); assert.deepEqual(spawns().at(-1)!.argv, MAIN_ARGV); }); test("a pinned exit disabled mid-walk, or a page that now carries a login, stops the job — never switches (review 2 nit 4)", async () => { settings(RUMBLE_POLICY); const job = {}; await list(ON_A, {}, [], job); settings({ ...RUMBLE_POLICY, exits: [{ ...EXITS[0], enabled: false }, EXITS[1]] }); await assert.rejects(list(ON_A, {}, [], job), /exit "exit-a" was disabled while this job was using it/); settings(RUMBLE_POLICY); const job2 = {}; await list(ON_A, {}, [], job2); await assert.rejects(list(ON_A, { cookiesFromBrowser: "firefox", cookieMode: "always" }, [], job2), /now carries a login/); assert.equal(spawns().length, 2); }); test("an aborted routed listing returns nothing (review 2 nit 5)", async () => { settings(RUMBLE_POLICY); mkdirSync(path.join(ROOT, "channels", ON_B), { recursive: true }); const ac = new AbortController(); process.env.FAKE_MODE = "slow"; const p = fetchFlatPlaylistUrls({ channelConfig: { handling: "transcribe", url: "https://rumble.com/c/demo" } as never, paths: { ...getPaths(), ytdlpBin: BIN }, channelSlug: ON_B, onLog: () => {}, signal: ac.signal, }); for (let i = 0; i < 200 && spawns().length === 0; i++) await new Promise((r) => setTimeout(r, 10)); await new Promise((r) => setTimeout(r, 300)); ac.abort(); const urls = await p.catch(() => []); assert.deepEqual(urls, []); }); test("a rate limit is classified before the secret is scrubbed (review 2 nit 7)", async () => { const keys = path.join(ROOT, "error-user.env"); writeFileSync(keys, "NETWORK_EXIT_EXIT_A=Error:Too\n"); chmodSync(keys, 0o600); settings({ ...RUMBLE_POLICY, exits: [exitRow("exit-a", proxyB.port, { credentials: true }), EXITS[1]], credentialsFile: keys }); process.env.FAKE_MODE = "429"; await assert.rejects(list(ON_A), (err: unknown) => err instanceof EnumerationIncompleteError && err.exit === "exit-a"); assert.ok((await NE.exitRestUntil(getPaths(), "rumble", "exit-a"))! > Date.now()); }); // LANE verify-resume MEETS THE EXIT: a cut-short listing's entries are kept as // evidence for the pre-clean check — but only entries yt-dlp showed came // through the exit. async function storePlaylistJob(slug: string) { mkdirSync(path.join(ROOT, "channels", slug), { recursive: true }); const config = { handling: "transcribe", url: "https://rumble.com/c/demo" }; writeFileSync(path.join(ROOT, "channels", slug, "config.json"), JSON.stringify(config)); return runYtdlp({ channelSlug: slug, mode: "store-playlist", channelConfig: config as never, paths: { ...getPaths(), ytdlpBin: BIN }, onLog: () => {}, signal: new AbortController().signal, }); } test("a rate-limited listing CONFIRMED through its exit keeps its partial entries as evidence and rests the exit", async () => { settings(RUMBLE_POLICY); rmSync(path.join(ROOT, "channels", ON_A, "listing-evidence.json"), { force: true }); process.env.FAKE_MODE = "429"; await assert.rejects(storePlaylistJob(ON_A), (err: unknown) => err instanceof EnumerationIncompleteError && err.urls.length === 1 && err.exit === "exit-a"); const ev = await readListingEvidence(getPaths(), ON_A); assert.ok(Object.keys(ev.seen).length > 0, JSON.stringify(ev)); assert.ok((await NE.exitRestUntil(getPaths(), "rumble", "exit-a"))! > Date.now()); }); test("a routed listing whose proxy use was NOT confirmed contributes no evidence (its entries are dropped first)", async () => { settings(RUMBLE_POLICY); rmSync(path.join(ROOT, "channels", ON_B, "listing-evidence.json"), { force: true }); process.env.FAKE_MODE = "no-map-429"; await assert.rejects(storePlaylistJob(ON_B), (err: unknown) => err instanceof EnumerationIncompleteError && err.urls.length === 0); const ev = await readListingEvidence(getPaths(), ON_B); assert.deepEqual(ev.seen, {}); // A clean exit with no confirmation: discarded, no evidence either. process.env.FAKE_MODE = "no-map"; await NE.clearExitRest(getPaths(), "rumble", "exit-b"); await assert.rejects(storePlaylistJob(ON_B), /its result is discarded/); assert.deepEqual((await readListingEvidence(getPaths(), ON_B)).seen, {}); });