// Cookie refresh alerts — the file, the job's log line, the yt-dlp hook, the // forum and archive.today paths (plans/cookie-refresh-alerts.md; Recheck is // controller/recheckServiceCookies.test.ts). // Every test in a temp transcripts dir. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/serviceCookies-server.test.ts import test from "node:test"; import assert from "node:assert/strict"; import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { readFileSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { runInJobContext, type JobContext } from "./jobContext"; import { dismissServiceCookieAlert, markServiceCookieRerun, noteArchiveTodayOutcome, noteForumServiceOutcome, noteServiceCookieAction, noteServiceCookieClean, noteServiceCookieSignal, observeYtdlpServiceOutcome, readServiceCookieState, serviceCookiesFile, } from "./serviceCookies-server"; import { isAlertRaised } from "./serviceCookies"; import { classifyForumPage } from "../social/xenforoParse"; import { CHALLENGE_PAGE, LOGIN_PAGE } from "../social/__fixtures__/xenforoPages"; import { ArchiveTodayClient } from "./archives/archiveTodayClient"; import { startFakeArchiveToday, AT_CHECKED_ID, AT_ARTICLE_URL } from "../testing/web/fakeArchiveToday.mjs"; const FIX = path.join(path.dirname(fileURLToPath(import.meta.url)), "__fixtures__"); const EMBED_403 = readFileSync(path.join(FIX, "rumble-embed-403.download.log"), "utf8"); const embed403For = (id: string) => EMBED_403.replaceAll("v7ez8hg", id); async function tmpPaths() { const transcriptsDir = await mkdtemp(path.join(os.tmpdir(), "service-cookies-")); return { transcriptsDir, channelsDir: path.join(transcriptsDir, "channels") }; } function jobCtx(jobId: string, kind = "fetch-windows"): JobContext & { lines: string[] } { const lines: string[] = []; return { jobId, kind, onLog: (l) => lines.push(l), staleServices: new Set(), lines }; } test("two embed 403s on different videos inside a job: the alert is raised, the job recorded, its log says the cause and the fix once", async () => { const paths = await tmpPaths(); try { const ctx = jobCtx("JOB1"); await runInJobContext(ctx, async () => { await observeYtdlpServiceOutcome(paths, { url: "https://rumble.com/v7fdzwe-x.html", channel: "huck", exitCode: 1, stderrTail: embed403For("v7d7myw") }); await observeYtdlpServiceOutcome(paths, { url: "https://rumble.com/v7f8yuw-y.html", channel: "huck", exitCode: 1, stderrTail: embed403For("v7d2lxe") }); await observeYtdlpServiceOutcome(paths, { url: "https://rumble.com/v7f8yuw-y.html", channel: "huck", exitCode: 1, stderrTail: embed403For("v7d2lxe") }); }); const state = await readServiceCookieState(paths); assert.equal(isAlertRaised(state.services.rumble), true); assert.deepEqual(state.services.rumble.jobs, [{ id: "JOB1", kind: "fetch-windows" }]); assert.equal(state.services.rumble.evidence.channel, "huck"); assert.equal(state.services.rumble.evidence.url, "https://rumble.com/v7f8yuw-y.html"); assert.deepEqual([...ctx.staleServices], ["rumble"]); const stopped = ctx.lines.filter((l) => l.startsWith("stopped: Rumble cookies look stale")); assert.equal(stopped.length, 1, ctx.lines.join("")); assert.match(ctx.lines[0], /a removed video does this too/); // The file is JSON on disk. JSON.parse(await readFile(serviceCookiesFile(paths), "utf8")); } finally { await rm(paths.transcriptsDir, { recursive: true, force: true }); } }); test("a clean yt-dlp run clears the alert, remembers the request, and an aborted run is not observed", async () => { const paths = await tmpPaths(); try { await noteServiceCookieSignal(paths, { service: "youtube", kind: "bot-check", line: "x" }); await observeYtdlpServiceOutcome(paths, { url: "https://www.youtube.com/watch?v=abc", exitCode: 0, stderrTail: "", aborted: true }); assert.equal(isAlertRaised((await readServiceCookieState(paths)).services.youtube), true); const ctx = jobCtx("JOB2", "download-one"); await runInJobContext(ctx, () => observeYtdlpServiceOutcome(paths, { url: "https://www.youtube.com/watch?v=abc", channel: "c", exitCode: 0, stderrTail: "" }), ); const state = await readServiceCookieState(paths); assert.equal(state.services.youtube.clearedBy, "clean"); assert.deepEqual(state.lastGood.youtube && [state.lastGood.youtube.url, state.lastGood.youtube.channel], ["https://www.youtube.com/watch?v=abc", "c"]); assert.deepEqual(ctx.lines, ["YouTube answered cleanly: its cookie alert is cleared.\n"]); } finally { await rm(paths.transcriptsDir, { recursive: true, force: true }); } }); test("a clean run of a platform with nothing recorded and a fresh lastGood writes nothing", async () => { const paths = await tmpPaths(); try { await observeYtdlpServiceOutcome(paths, { url: "https://rumble.com/a", exitCode: 0, stderrTail: "" }); const first = await readFile(serviceCookiesFile(paths), "utf8"); await observeYtdlpServiceOutcome(paths, { url: "https://rumble.com/b", exitCode: 0, stderrTail: "" }); assert.equal(await readFile(serviceCookiesFile(paths), "utf8"), first); // A platform that is not a cookie service is never written. await observeYtdlpServiceOutcome(paths, { url: "https://www.twitch.tv/videos/1", exitCode: 0, stderrTail: "" }); assert.equal(JSON.parse(await readFile(serviceCookiesFile(paths), "utf8")).lastGood.twitch, undefined); } finally { await rm(paths.transcriptsDir, { recursive: true, force: true }); } }); test("two services meeting their signals at once are both recorded (the lock)", async () => { const paths = await tmpPaths(); try { await Promise.all([ noteServiceCookieSignal(paths, { service: "youtube", kind: "bot-check", line: "y" }), noteServiceCookieSignal(paths, { service: "odysee", kind: "challenge", line: "o" }), noteServiceCookieSignal(paths, { service: "archive.today", kind: "check-page", line: "a" }), ]); assert.deepEqual(Object.keys((await readServiceCookieState(paths)).services).sort(), ["archive.today", "odysee", "youtube"]); } finally { await rm(paths.transcriptsDir, { recursive: true, force: true }); } }); test("a file that is not JSON reads as empty and is replaced by the next write", async () => { const paths = await tmpPaths(); try { await writeFile(serviceCookiesFile(paths), "{ torn"); assert.deepEqual((await readServiceCookieState(paths)).services, {}); await noteServiceCookieSignal(paths, { service: "youtube", kind: "bot-check", line: "y" }); assert.ok((await readServiceCookieState(paths)).services.youtube); } finally { await rm(paths.transcriptsDir, { recursive: true, force: true }); } }); test("Kiwi Farms: a challenge page that stopped the walk raises the forum host's alert; a clean walk clears it", async () => { const paths = await tmpPaths(); try { const url = "https://kiwifarms.st/threads/some-thread.123/"; assert.equal(classifyForumPage(CHALLENGE_PAGE)?.kind, "challenge"); assert.equal(classifyForumPage(LOGIN_PAGE)?.kind, "login"); await noteForumServiceOutcome(paths, url, { block: "challenge", error: "kiwifarms.st kept its browser check", channel: "kf-thread" }); let state = await readServiceCookieState(paths); assert.equal(isAlertRaised(state.services["kiwifarms.st"]), true); assert.equal(state.services["kiwifarms.st"].evidence.url, url); // A refusal (403/429) is not the session's cookies. await noteForumServiceOutcome(paths, url, { block: "blocked", error: "refused" }); const line = await noteForumServiceOutcome(paths, url, { channel: "kf-thread" }); assert.match(line ?? "", /Kiwi Farms \(kiwifarms\.st\) answered cleanly/); state = await readServiceCookieState(paths); assert.equal(state.services["kiwifarms.st"].clearedBy, "clean"); } finally { await rm(paths.transcriptsDir, { recursive: true, force: true }); } }); test("archive.today: the client's check refusal raises the alert; a copy read clears it", async () => { const paths = await tmpPaths(); const at = await startFakeArchiveToday({ challenge: [AT_CHECKED_ID] }); try { let t = 1_000_000; const c = new ArchiveTodayClient({ fetch: at.fetch, now: () => t, sleep: async (ms: number) => { t += ms; }, random: () => 0, observe: (o) => noteArchiveTodayOutcome(paths, o), }); await assert.rejects(c.getCapture(`https://archive.ph/${AT_CHECKED_ID}`), /Connect archive session/); let state = await readServiceCookieState(paths); assert.equal(isAlertRaised(state.services["archive.today"]), true); assert.equal(state.services["archive.today"].kind, "check-page"); await c.listCaptures(AT_ARTICLE_URL); state = await readServiceCookieState(paths); assert.equal(state.services["archive.today"].clearedBy, "clean"); } finally { await at.close(); await rm(paths.transcriptsDir, { recursive: true, force: true }); } }); test("dismiss and re-run marks", async () => { const paths = await tmpPaths(); try { assert.equal(await dismissServiceCookieAlert(paths, "youtube"), false); await noteServiceCookieSignal(paths, { service: "youtube", kind: "bot-check", line: "y" }); assert.equal(await dismissServiceCookieAlert(paths, "youtube"), true); let state = await readServiceCookieState(paths); assert.equal(state.services.youtube.clearedBy, "dismiss"); await markServiceCookieRerun(paths, "youtube", ["N1"]); state = await readServiceCookieState(paths); assert.deepEqual(state.services.youtube.rerunJobIds, ["N1"]); assert.equal(await noteServiceCookieClean(paths, "youtube"), null, "already cleared"); } finally { await rm(paths.transcriptsDir, { recursive: true, force: true }); } }); test("a Rumble listing 403 on a channel with no cookie config names the missing keys in the job's log; a configured one says nothing extra", async () => { const paths = await tmpPaths(); try { const dir = path.join(paths.channelsDir, "bare-rumble"); await mkdir(dir, { recursive: true }); await writeFile(path.join(dir, "config.json"), JSON.stringify({ name: "Bare", url: "https://rumble.com/c/bare", platform: "rumble", handling: "youtube" })); const okDir = path.join(paths.channelsDir, "ok-rumble"); await mkdir(okDir, { recursive: true }); await writeFile( path.join(okDir, "config.json"), JSON.stringify({ name: "Ok", url: "https://rumble.com/c/ok", platform: "rumble", handling: "youtube", cookiesFromBrowser: "firefox", cookieMode: "always", ytdlpExtraArgs: ["--impersonate", "firefox"], }), ); const stderr = "ERROR: [RumbleChannel] bare: Unable to download webpage: HTTP Error 403: Forbidden"; const ctx = jobCtx("JOB2", "sync"); await runInJobContext(ctx, async () => { await observeYtdlpServiceOutcome(paths, { url: "https://rumble.com/c/bare", channel: "bare-rumble", exitCode: 1, stderrTail: stderr }); await observeYtdlpServiceOutcome(paths, { url: "https://rumble.com/c/ok", channel: "ok-rumble", exitCode: 1, stderrTail: stderr }); }); assert.equal(ctx.lines.length, 1, ctx.lines.join("")); assert.match(ctx.lines[0], /bare-rumble has no cookiesFromBrowser, no cookieMode, no --impersonate in ytdlpExtraArgs/); assert.match(ctx.lines[0], /Rumble needs cookies from firefox, cookieMode always and --impersonate firefox/); } finally { await rm(paths.transcriptsDir, { recursive: true, force: true }); } }); test("the last press per service is recorded, replaced by the next, and coerced back", async () => { const paths = await tmpPaths(); try { await noteServiceCookieAction(paths, "x", { action: "refresh", ok: true, message: "Cookies refreshed." }, Date.parse("2026-11-16T09:00:00Z")); await noteServiceCookieAction( paths, "rumble", { action: "recheck", ok: false, result: "stale", message: "Rumble still refused.", jobId: "job-1" }, Date.parse("2026-11-16T09:01:00Z"), ); await noteServiceCookieAction(paths, "x", { action: "refresh", ok: false, message: "No X session profile yet." }, Date.parse("2026-11-16T09:02:00Z")); const state = await readServiceCookieState(paths); assert.deepEqual(state.actions, { x: { at: "2026-11-16T09:02:00.000Z", action: "refresh", ok: false, message: "No X session profile yet." }, rumble: { at: "2026-11-16T09:01:00.000Z", action: "recheck", ok: false, result: "stale", message: "Rumble still refused.", jobId: "job-1" }, }); // A torn record is dropped, never thrown on. const raw = JSON.parse(await readFile(serviceCookiesFile(paths), "utf8")); raw.actions.youtube = { at: "not a time", action: "refresh" }; raw.actions["not a service!"] = { at: "2026-11-16T09:00:00Z", action: "refresh" }; raw.actions.odysee = { at: "2026-11-16T09:00:00Z", action: "explode" }; await writeFile(serviceCookiesFile(paths), JSON.stringify(raw)); assert.deepEqual(Object.keys((await readServiceCookieState(paths)).actions ?? {}).sort(), ["rumble", "x"]); } finally { await rm(paths.transcriptsDir, { recursive: true, force: true }); } });