// The cookie recheck timer (serviceCookieTimer.ts): what one tick asks and // what it leaves alone (never stacking on a running job, a running recheck, a // cooling platform or a recent clean answer; never retrying), Rumble's // one-time confirmation on a second known-good video, X's jar from disk, and // the timer itself (off at 0, not armed on an idle boot, a tick in flight // skips the next). Every dependency is injected: nothing here asks a site. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/serviceCookieTimer.test.ts import { test, afterEach } from "node:test"; import assert from "node:assert/strict"; import { OFF_POLL_MS, runServiceCookieTick, serviceCookieTimerView, startServiceCookieTimer, stopServiceCookieTimer, type ServiceCookieTickDeps, type TickJob, } from "./serviceCookieTimer"; import { applyServiceCookieSignal, emptyServiceCookieState, type ServiceCookieState, type XJarStatusView, } from "../lib/serviceCookies"; import type { RecheckOutcome } from "./recheckServiceCookies"; const NOW = Date.parse("2026-11-01T04:00:00Z"); const ago = (min: number) => new Date(NOW - min * 60_000).toISOString(); function jar(fresh: boolean): XJarStatusView { return { source: "profile", at: ago(fresh ? 5 : 300), ageMinutes: fresh ? 5 : 300, maxAgeMinutes: 60, loggedIn: true, fresh, readAt: new Date(NOW).toISOString(), summary: fresh ? "The X cookie jar was written 5 min ago (limit 60 min)." : "The X cookie jar was written 5 h ago (limit 60 min): press Refresh cookies (or Connect X account) on /cookies.", }; } type Harness = { deps: ServiceCookieTickDeps; state: ServiceCookieState; calls: { service: string; target?: string }[]; jobs: TickJob[]; stale: string[]; freshCalls: number; waits: number; answers: Record; cooling: Set; xFresh: boolean; }; function harness(init: (s: ServiceCookieState) => void = () => {}): Harness { const state = emptyServiceCookieState(); init(state); const h: Harness = { state, calls: [], jobs: [], stale: [], freshCalls: 0, waits: 0, answers: {}, cooling: new Set(), xFresh: true, deps: undefined as unknown as ServiceCookieTickDeps, }; h.deps = { now: () => NOW, settings: () => ({ recheckIntervalMinutes: 180, probeServices: ["rumble"] }), readState: async () => structuredClone(h.state), jobs: () => h.jobs, cooling: async (p) => h.cooling.has(p), recheck: async (service, target) => { h.calls.push({ service, ...(target ? { target: target.url } : {}) }); const result = h.answers[service]?.shift() ?? "clean"; // A stale Rumble answer records a pending embed 403 on the asked video. if (result === "stale" && service === "rumble") { const url = target?.url ?? h.state.lastGood.rumble?.url ?? ""; applyServiceCookieSignal(h.state, { service, kind: "embed-403", line: "403", videoId: url }, { url }, NOW); } return { service, result, message: result }; }, xJar: async () => jar(h.xFresh), noteXJarStale: async (line) => { h.stale.push(line); return true; }, noteXJarFresh: async () => { h.freshCalls++; return "cleared"; }, confirmWait: async () => { h.waits++; }, log: () => {}, }; return h; } const withGood = (min: number, prev = true) => (s: ServiceCookieState) => { s.lastGood.rumble = { url: "https://rumble.com/v1-a.html", at: ago(min), channel: "huck", ...(prev ? { prev: { url: "https://rumble.com/v2-b.html", at: ago(min + 30) } } : {}), }; }; test("a probe: Rumble idle past the interval is asked ONCE for its last clean video", async () => { const h = harness(withGood(240)); const actions = await runServiceCookieTick(h.deps); assert.deepEqual(h.calls, [{ service: "rumble" }]); assert.equal(actions.find((a) => a.service === "rumble")?.action, "probed"); }); test("never stacking: a job on Rumble's queue, a recheck already running, a cooling platform, a recent clean answer, nothing known-good — no request", async () => { for (const [label, setup] of [ ["a sync running", (h: Harness) => h.jobs.push({ kind: "sync", queueKey: "platform:rumble", status: "running" })], ["a clip fetch queued", (h: Harness) => h.jobs.push({ kind: "fetch-windows", queueKey: "clips:rumble", status: "queued" })], ["a recheck running", (h: Harness) => h.jobs.push({ kind: "recheck-service-cookies", queueKey: "service-cookies:rumble", status: "running" })], ["cooling", (h: Harness) => h.cooling.add("rumble")], ] as const) { const h = harness(withGood(240)); setup(h); const actions = await runServiceCookieTick(h.deps); assert.deepEqual(h.calls, [], label); assert.equal(actions.find((a) => a.service === "rumble")?.action, "skipped", label); } // A job that has ended does not hold it back. const ended = harness(withGood(240)); ended.jobs.push({ kind: "sync", queueKey: "platform:rumble", status: "done" }); await runServiceCookieTick(ended.deps); assert.equal(ended.calls.length, 1); const recent = harness(withGood(30)); assert.match((await runServiceCookieTick(recent.deps)).find((a) => a.service === "rumble")?.message ?? "", /answered cleanly 30 min ago/); assert.deepEqual(recent.calls, []); const none = harness(); await runServiceCookieTick(none.deps); assert.deepEqual(none.calls, []); }); test("Rumble's ambiguous 403: confirmed ONCE on the previous, different known-good video after a wait; never a third request", async () => { const h = harness(withGood(240)); h.answers.rumble = ["stale", "stale"]; const actions = await runServiceCookieTick(h.deps); assert.deepEqual(h.calls, [{ service: "rumble" }, { service: "rumble", target: "https://rumble.com/v2-b.html" }]); assert.equal(h.waits, 1); assert.deepEqual(actions.filter((a) => a.service === "rumble").map((a) => a.action), ["probed", "confirmed"]); // Two different videos refused: the alert is up. assert.ok(h.state.services.rumble?.raisedAt); // No earlier, different video: one request, the first 403 stays pending. const solo = harness(withGood(240, false)); solo.answers.rumble = ["stale"]; await runServiceCookieTick(solo.deps); assert.equal(solo.calls.length, 1); assert.equal(solo.waits, 0); assert.equal(solo.state.services.rumble?.raisedAt, undefined); // A probe that failed for another reason is not retried. const failed = harness(withGood(240)); failed.answers.rumble = ["failed"]; await runServiceCookieTick(failed.deps); assert.equal(failed.calls.length, 1); }); test("raised alerts are rechecked once (any service that has something to ask); a running job on the platform holds it back", async () => { const h = harness((s) => { withGood(240)(s); applyServiceCookieSignal(s, { service: "youtube", kind: "bot-check", line: "bot" }, { url: "https://www.youtube.com/watch?v=aaaaaaaaaaa" }, NOW - 3600_000); applyServiceCookieSignal(s, { service: "rumble", kind: "embed-403", line: "a", videoId: "e1" }, { url: "https://rumble.com/v1-a.html" }, NOW - 3600_000); applyServiceCookieSignal(s, { service: "rumble", kind: "embed-403", line: "b", videoId: "e2" }, { url: "https://rumble.com/v2-b.html" }, NOW - 3600_000); }); h.jobs.push({ kind: "sync", queueKey: "platform:youtube", status: "running" }); const actions = await runServiceCookieTick(h.deps); // Rumble's banner rechecked; not probed again in the same tick. YouTube held back by its running sync. assert.deepEqual(h.calls, [{ service: "rumble" }]); assert.equal(actions.find((a) => a.service === "youtube")?.action, "skipped"); assert.equal(actions.find((a) => a.service === "rumble")?.action, "rechecked"); }); test("X from disk: queued X jobs on an old jar raise the jar-age banner; a fresh jar clears it; no X job queued, nothing is raised", async () => { const idle = harness(); idle.xFresh = false; await runServiceCookieTick(idle.deps); assert.deepEqual(idle.stale, [], "no X work waiting: no banner"); const waiting = harness(); waiting.xFresh = false; waiting.jobs.push({ kind: "fetch-posts", queueKey: "platform:twitter", status: "queued" }); await runServiceCookieTick(waiting.deps); assert.equal(waiting.stale.length, 1); assert.match(waiting.stale[0], /^1 X job is queued on an old cookie jar: The X cookie jar was written 5 h ago/); const raised = harness((s) => { applyServiceCookieSignal(s, { service: "x", kind: "jar-age", line: "old" }, {}, NOW - 3600_000); }); raised.xFresh = true; const actions = await runServiceCookieTick(raised.deps); assert.equal(raised.freshCalls, 1); assert.equal(actions.find((a) => a.service === "x")?.action, "cleared"); assert.deepEqual(raised.calls.filter((c) => c.service === "x"), [], "jar-age is re-read, not rechecked"); }); // ── the timer ────────────────────────────────────────────────────────────── afterEach(() => stopServiceCookieTimer()); function fakeScheduler() { const pending: { fn: () => void; ms: number; cancelled: boolean }[] = []; return { pending, schedule: (fn: () => void, ms: number) => { const p = { fn, ms, cancelled: false }; pending.push(p); return { cancel: () => (p.cancelled = true) }; }, fire: () => { const p = pending.shift(); assert.ok(p && !p.cancelled, "a tick was scheduled"); p.fn(); }, }; } test("the timer: 0 is off (it only looks again later whether it was turned on)", async () => { const sched = fakeScheduler(); let ticks = 0; assert.equal( startServiceCookieTimer({ env: {}, settings: () => ({ recheckIntervalMinutes: 0, probeServices: ["rumble"] }), schedule: sched.schedule, jitter: (ms) => ms, deps: async () => { ticks++; return harness().deps; }, log: () => {}, }), true, ); assert.equal(sched.pending[0].ms, OFF_POLL_MS); sched.fire(); await new Promise((r) => setImmediate(r)); assert.equal(ticks, 0); assert.equal(sched.pending[0].ms, OFF_POLL_MS); assert.equal(serviceCookieTimerView().armed, true); }); test("the timer: not armed on an idle boot, nor twice", () => { assert.equal(startServiceCookieTimer({ env: { ARCHILYZER_IDLE_BOOT: "1" }, log: () => {} }), false); assert.equal(serviceCookieTimerView().armed, false); const sched = fakeScheduler(); const opts = { env: {}, settings: () => ({ recheckIntervalMinutes: 180, probeServices: [] }), schedule: sched.schedule, jitter: (ms: number) => ms, deps: async () => harness().deps, log: () => {}, }; assert.equal(startServiceCookieTimer(opts), true); assert.equal(startServiceCookieTimer(opts), false); // The first tick comes no sooner than 15 min after boot, and no later than the interval. assert.equal(sched.pending[0].ms, 15 * 60_000); }); test("the timer: a tick still in flight when the next is due skips it; the next is scheduled after the interval, jittered up", async () => { const sched = fakeScheduler(); let release!: () => void; let ticks = 0; const logs: string[] = []; startServiceCookieTimer({ env: {}, settings: () => ({ recheckIntervalMinutes: 180, probeServices: [] }), schedule: sched.schedule, jitter: (ms) => ms * 1.1, deps: async () => { ticks++; const h = harness(); return { ...h.deps, settings: () => ({ recheckIntervalMinutes: 180, probeServices: [] }), readState: async () => { await new Promise((r) => (release = r)); return emptyServiceCookieState(); }, }; }, log: (l) => logs.push(l), }); sched.fire(); // tick 1 starts and hangs await new Promise((r) => setImmediate(r)); assert.equal(ticks, 1); // No tick is scheduled while one is in flight: the next is armed only when // this one ends, so two can never overlap. assert.equal(sched.pending.length, 0); release(); await new Promise((r) => setTimeout(r, 10)); assert.equal(sched.pending.length, 1); assert.equal(sched.pending[0].ms, 180 * 60_000 * 1.1); assert.ok(serviceCookieTimerView().lastTickAt); assert.equal(logs.filter((l) => /still running/.test(l)).length, 0); }); test("Instagram's alert is a person's to clear: the timer never rechecks it, raised or listed as a probe", async () => { const h = harness((s) => { applyServiceCookieSignal(s, { service: "instagram", kind: "challenge", line: "HTTP redirect to challenge page" }, { channel: "example-ig" }, NOW - 3600_000); }); h.deps.settings = () => ({ recheckIntervalMinutes: 180, probeServices: ["instagram"] }); const actions = await runServiceCookieTick(h.deps); assert.deepEqual(h.calls, []); assert.equal(actions.find((a) => a.service === "instagram")?.action, "skipped"); assert.match(actions.find((a) => a.service === "instagram")?.message ?? "", /person's Recheck only/); });