commit fa307601909d8608b7cce602771e9268cc3566ce
parent e1e7aa0b9280ddc48605c9bdbc142e43ca96d4c2
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 21 Oct 2026 18:35:57 -0400
Merge lane/cookie-alerts: one cookie refresh alert per service (Rumble, YouTube, Odysee, forums, archive.today) on the dashboard, with Recheck and re-run of the jobs it stopped
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
52 files changed, 2838 insertions(+), 16 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -149,6 +149,9 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `tts` | tts speaks a line with a local text-to-speech engine and a STOCK voice, as a job on the `tts` queue: {"text": "..."} or {"file": "/abs/script.txt"} (UTF-8, at most 20,000 characters), "engine" (kokoro \| orpheus \| espeak-ng), "voice" (one of the engine's stock voices; kokoro: af\_heart, bm\_george, ...; orpheus: leah, zac, ...), "speed" (0.5-2; orpheus has none) — defaults from settings.tts (kokoro, af\_heart, 1) — and "out" (an absolute .wav path the result is copied to, never inside the corpus). The expressive tags <laugh> <chuckle> <sigh> <cough> <sniffle> <groan> <yawn> <gasp> are performed by orpheus and stripped for the others; any other <...> is refused. Numbers, years, money and times are spoken (2024: "twenty twenty-four"). The result is {wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate, speed, disclosure}: wav is the 48 kHz mono WAV the editor wrote (out, or its cache), disclosure the line a narrated export carries. The same ask again is answered from the cache (cached: true, no engine run). Kokoro and orpheus need `archilyzer tts setup [--engine orpheus]` first; orpheus runs on the GPU (a local llama-server the editor starts and stops) and waits while a transcription holds it. With --wait the result is printed on stdout. | `pnpm ops tts --json '{"text":"In 2024 the archive spoke."}' --wait`<br>`pnpm ops tts --json '{"file":"/abs/script.txt","voice":"bm_george","out":"/abs/line.wav"}' --wait` |
| `settings` | settings patches settings.json through the editor's one writer: {"patch": {"<top-level key>": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage — the refusal names it); a value the schema would not keep as sent (clamped, dropped), named with what would be saved. Answers the saved values. | `pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}'` |
| `clear-platform-hold` | clear-platform-hold clears a platform's rate-limit hold, backoff and raised pace, as the lane strip's Clear hold: {"platform"}. Answers the sentence. | |
+| `recheck-service` | recheck-service asks a service whose cookie refresh alert is up ONE request through its own path, as the dashboard banner's Recheck: {"service"} ("rumble", "youtube", "odysee", "archive.today" or a forum host). Waits for it: {jobId, result: "clean" \| "stale" \| "failed", message}; "clean" clears the alert (and a yt-dlp service's backoff, as any clean request). dismiss-service clears a service's cookie alert by hand: {"service"}. rerun-service-jobs retries every job a service's cookie alert stopped, once it is OK again: {"service"} -> {jobIds, skipped}. --wait follows them. | `pnpm ops recheck-service --json '{"service":"rumble"}'` |
+| `dismiss-service` | — | |
+| `rerun-service-jobs` | — | |
| `workers` | workers switches transcription workers as /workers does: {"op": "enable" \| "disable" \| "drain", "ids": \[...\]} — the live pool; a restart restores the launch default. An unknown id is named; the others still apply. | `pnpm ops workers --json '{"op":"disable","ids":["parakeet-cpu"]}'` |
| `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. A job; --wait follows it. "salvage": true decodes a damaged file with error tolerance and transcribes what decodes, on the recording's clock, its gaps recorded (the transcript is listed as salvaged); a corrupt-full-source video is salvaged unless "salvage": false — once its full audio was tried: when its record stores an Odysee media URL, that URL is downloaded first, up to 2 times (20 min apart), and the salvage follows only if neither download is clean. "storedUrl": "only" \| "fallback" \| "never" downloads missing audio from the media URL the record stores (Odysee's CDN), read in ranges as its player reads it — no page request with "only", the page first with "fallback" — through the audio check; one new file per platform per 20 min. Absent = the channel's storedUrlDownloads. "whilePaused": true runs this one transcription during a pause-all on a worker the pause alone switched off; the pause stays on (the video page's "Transcribe now (workers paused)"). | |
| `delete-file` | delete-file deletes one file of one video, as its Files list does: {"slug", "id", "file"}. A tiered media file goes with its bytes on the media drive (never a bare link); refused while that drive is not answering. No undo. | |
@@ -197,6 +200,7 @@ Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait]
pnpm ops job wait <id>... [--wait-timeout <seconds>]
pnpm ops get settings [<key>]
pnpm ops get storage | sites | workers | auto-queue | scheduler
+ pnpm ops get services
pnpm ops get cleanup <slug>
pnpm ops get remote-listing <slug> [--wait-timeout <seconds>]
pnpm ops get transcript <videoId> [--slug <slug>]
@@ -235,6 +239,10 @@ get sites lists every site: id, title, siteUrl, Pages project, audience,
is the status.)
get workers, get auto-queue and get scheduler are /workers, the four lanes
of /operations, and /operations/sync — the payloads those pages poll.
+get services is the dashboard's cookie refresh alerts: each service
+ (rumble, youtube, odysee, archive.today, a forum host) whose cookies look
+ stale, or are OK again with the jobs the alert stopped; "pending" lists
+ a first Rumble embed 403 waiting for a second video.
get cleanup <slug> is one channel's /cleanup row: what each sweep would
reclaim (they overlap — never add them), what holds the rest, and the
failed-transcriptions count. measured: false means unknown, not zero.
diff --git a/OPERATING.md b/OPERATING.md
@@ -55,6 +55,28 @@ pnpm ops persist-videos --json '{"items":[{"slug":"example","id":"<videoId>"}]
- Bucket names and sizes: `pnpm ops get channel example`.
- Keep videos out of cleanup by title or description: `pnpm ops keep-videos --json '{"slug":"example","match":"interview","dryRun":true}'`.
+### Cookies gone stale: the dashboard's banner
+
+```sh
+pnpm ops get services # what is stale, since when, which jobs it stopped
+pnpm ops recheck-service --json '{"service":"rumble"}' # one request through the service's own path
+pnpm ops rerun-service-jobs --json '{"service":"rumble"}' --wait
+pnpm ops dismiss-service --json '{"service":"rumble"}'
+```
+
+- A banner at the top of the dashboard says which service's cookies look stale and what to do. Do it,
+ then press **Recheck**; when the service answers, the banner turns to "OK again" and offers **Re-run
+ stopped jobs**. The next clean request clears it without you too.
+- What raises it: Rumble refusing its embed JSON with a 403 on **two different videos in a row** (one is
+ not enough — a removed video answers 403 too) → open rumble.com in the browser `cookiesFromBrowser`
+ names. YouTube's bot check → open youtube.com there, signed in. Odysee's Cloudflare page (a 403 with
+ Cloudflare's challenge words; no real sample yet) → open odysee.com. A forum's browser check, captcha or
+ login wall, by host → Connect forum session on the thread's channel page. archive.today's check page →
+ Connect archive session (Settings). A Connect that ends on a cleared page clears the banner too.
+- The job it stopped says so in its log: `stopped: Rumble cookies look stale — open rumble.com in …, then
+ Recheck on the dashboard.` `archilyzer doctor` lists it under "service cookies".
+- The state is `transcripts/.service-cookies.json` (`common/lib/serviceCookies.ts`); never hand-edit it.
+
## Import from archive.org, Odysee, BitChute and the Wayback Machine
```sh
diff --git a/common/bin/doctor.test.ts b/common/bin/doctor.test.ts
@@ -632,6 +632,56 @@ test("download pacing: a held platform and a raised pace warn, and nothing is wr
assert.deepEqual(tree(c.root), before);
});
+test("service cookies: a stale service warns with its fix, a pending first 403 is a note, and nothing is written", async () => {
+ const c = checkout();
+ mkdirSync(c.paths.transcriptsDir, { recursive: true });
+ const now = Date.UTC(2026, 9, 21, 17, 10);
+ writeFileSync(
+ path.join(c.paths.transcriptsDir, ".service-cookies.json"),
+ JSON.stringify({
+ version: 1,
+ services: {
+ rumble: {
+ kind: "embed-403",
+ since: "2026-10-21T17:02:00.000Z",
+ lastSeen: "2026-10-21T17:04:00.000Z",
+ count: 2,
+ videos: ["v7d7myw", "v7d2lxe"],
+ raisedAt: "2026-10-21T17:04:00.000Z",
+ evidence: { line: "ERROR: [RumbleEmbed] v7d2lxe: Unable to download JSON metadata: HTTP Error 403: Forbidden" },
+ jobs: [],
+ },
+ youtube: {
+ kind: "bot-check",
+ since: "2026-10-21T17:05:00.000Z",
+ lastSeen: "2026-10-21T17:05:00.000Z",
+ count: 1,
+ videos: [],
+ raisedAt: "2026-10-21T17:05:00.000Z",
+ clearedAt: "2026-10-21T17:08:00.000Z",
+ clearedBy: "recheck",
+ evidence: { line: "x" },
+ jobs: [],
+ },
+ },
+ lastGood: {},
+ }),
+ );
+ const before = tree(c.root);
+ const r = await run(c, {}, { now: new Date(now) });
+ const sc = r.checks.filter((x) => x.section === "service cookies");
+ assert.deepEqual(
+ sc.map((x) => [x.id, x.status]),
+ [
+ ["rumble", "warn"],
+ ["youtube", "info"],
+ ],
+ );
+ assert.match(sc[0].detail, /^cookies look stale — 2 embed 403s on different videos since 17:02 UTC\. Fix: open rumble\.com in /);
+ assert.match(sc[1].detail, /^YouTube cookies OK again \(cleared .*, recheck\)$/);
+ assert.deepEqual(tree(c.root), before);
+});
+
// ── release 18: the downloader and publish checks ─────────────────────────
const find = (r: DoctorReport, section: string, id: string) =>
diff --git a/common/bin/doctor.ts b/common/bin/doctor.ts
@@ -338,6 +338,35 @@ export async function collectDoctorReport(deps: DoctorDeps): Promise<DoctorRepor
add(DP, "platforms", "info", "no auto-queue state yet — nothing has been rate-limited");
}
+ // ── service cookies ──────────────────────────────────────────────────────
+ // The cookie refresh alerts (lib/serviceCookies.ts): a service whose cookies
+ // look stale — Rumble's embed 403s on two videos in a row, YouTube's bot
+ // check, Odysee's Cloudflare page, a forum's browser check, archive.today's
+ // check page. A warning with the fix; read-only (the reader never writes).
+ const SC = "service cookies";
+ if (paths.transcriptsDir && existsSync(paths.transcriptsDir)) {
+ const { readServiceCookieState } = await import("../lib/serviceCookies-server");
+ const { buildServiceCookieAlerts } = await import("../lib/serviceCookies");
+ const nowMs = (deps.now ?? new Date()).getTime();
+ const view = buildServiceCookieAlerts(await readServiceCookieState(paths), {
+ now: nowMs,
+ browser: settings?.cookiesFromBrowser || undefined,
+ });
+ for (const a of view.alerts) {
+ if (a.state === "stale") {
+ add(SC, a.service, "warn", `cookies look stale — ${a.detail}. Fix: ${a.fix}, then Recheck on the dashboard (or \`pnpm ops recheck-service\`)`);
+ } else {
+ add(SC, a.service, "info", `${a.headline} (cleared ${stamp(new Date(a.clearedAt ?? a.lastSeen))}, ${a.clearedBy ?? "clean"})`);
+ }
+ }
+ for (const p of view.pending) {
+ add(SC, p.service, "info", `one ${p.kind} seen (${p.videos.join(", ") || "no video named"}) — a second video refused in a row raises the alert`);
+ }
+ if (view.alerts.every((a) => a.state !== "stale")) {
+ add(SC, "services", "ok", "no service's cookies look stale");
+ }
+ }
+
// ── settings ─────────────────────────────────────────────────────────────
const S = "settings";
const settingsText = readOrNull(paths.settingsFile);
diff --git a/common/controller/checkAvailability.ts b/common/controller/checkAvailability.ts
@@ -11,6 +11,7 @@ import {
type Availability,
} from "../lib/availability";
import { recordDownloadBackoff } from "../jobs/downloadBackoff";
+import { observeStderrServiceSignal } from "../lib/serviceCookies-server";
import {
loadAvailability,
recordAvailability,
@@ -341,6 +342,8 @@ export async function runAvailabilityCheck({
} catch {
/* the cooldown is best-effort; the stop above already happened */
}
+ // A bot check is the service's cookies too (cookie refresh alerts).
+ await observeStderrServiceSignal(paths, b.message, { url: b.url, channel: channelSlug });
}
// Type guard: every key in AVAILABILITY_VALUES has been incremented above.
diff --git a/common/controller/fetchLiveChat.ts b/common/controller/fetchLiveChat.ts
@@ -168,7 +168,17 @@ export async function fetchLiveChat(opts: FetchLiveChatOpts): Promise<FetchLiveC
const policy: ResolvedCookiePolicy = opts.cookiePolicy ?? { cookies: undefined, mode: DEFAULT_COOKIE_MODE };
const run: ChatRunner =
opts.run ??
- ((cwd, args) => runOneYtdlp({ ytdlpBin: opts.paths.ytdlpBin, onLog: opts.onLog, signal: opts.signal }, cwd, args));
+ ((cwd, args) =>
+ runOneYtdlp(
+ {
+ ytdlpBin: opts.paths.ytdlpBin,
+ onLog: opts.onLog,
+ signal: opts.signal,
+ observe: { paths: opts.paths, url: opts.videoUrl, channel: opts.slug },
+ },
+ cwd,
+ args,
+ ));
if (!(await isDirectory(videoDir))) throw new Error(notFetchedRefusal(opts.videoId, opts.slug));
const pass = (cookies: string | undefined) =>
run(channelDir, liveChatOnlyArgs(opts.channelConfig, cookies, opts.videoUrl, opts.paceSeconds));
diff --git a/common/controller/fetchPosts.ts b/common/controller/fetchPosts.ts
@@ -67,6 +67,7 @@ import "../social/xNitterFetcher";
// A forum thread (platform "xenforo"): claims only thread URLs.
import "../social/xenforoFetcher";
import type { XCookieSource } from "../social/xCookieSource";
+import { noteForumServiceOutcome } from "../lib/serviceCookies-server";
import {
resolveXCookieSourceFor,
type XLoginSettings,
@@ -576,6 +577,17 @@ async function fetchTimeline(ctx: {
state.cursor = result.cursor;
}
if (result.needsCookies) state.needsCookies = true;
+ // A FORUM's browser check or login wall is the forum session's cookies: the
+ // cookie refresh alert for its host (lib/serviceCookies.ts) — the channel's
+ // own needsCookies stays as it was. A walk with no block clears it.
+ if (forum) {
+ const cleared = await noteForumServiceOutcome(paths, accountUrl, {
+ ...(result.block ? { block: result.block } : {}),
+ ...(result.error ? { error: result.error } : {}),
+ channel: slug,
+ });
+ if (cleared) log(cleared.trimEnd());
+ }
if (result.error) {
log(`[error] ${result.error}`);
state.lastError = result.error;
diff --git a/common/controller/recheckServiceCookies.test.ts b/common/controller/recheckServiceCookies.test.ts
@@ -0,0 +1,126 @@
+// RECHECK A SERVICE'S COOKIES (cookie refresh alerts,
+// plans/cookie-refresh-alerts.md): one request through the service's own path,
+// the alert cleared when it comes back clean. Every test in a temp transcripts
+// dir; yt-dlp and the forum browser are injected.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/recheckServiceCookies.test.ts
+
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, rm } 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 {
+ noteForumServiceOutcome,
+ noteServiceCookieSignal,
+ readServiceCookieState,
+} from "../lib/serviceCookies-server";
+import { isAlertRaised } from "../lib/serviceCookies";
+import { CHALLENGE_PAGE } from "../social/__fixtures__/xenforoPages";
+import { recheckServiceCookies } from "./recheckServiceCookies";
+
+const FIX = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "lib", "__fixtures__");
+const EMBED_403 = readFileSync(path.join(FIX, "rumble-embed-403.download.log"), "utf8");
+const embed403For = (id: string) => EMBED_403.replaceAll("v7ez8hg", id);
+
+type RecheckPaths = Parameters<typeof recheckServiceCookies>[0]["paths"];
+
+async function tmpPaths(): Promise<RecheckPaths> {
+ const transcriptsDir = await mkdtemp(path.join(os.tmpdir(), "service-cookies-recheck-"));
+ return { transcriptsDir, channelsDir: path.join(transcriptsDir, "channels"), ytdlpBin: "yt-dlp" } as RecheckPaths;
+}
+
+test("Recheck (Rumble): one metadata request for the request that failed, with the channel's args and cookies; clean clears and settles the backoff", async () => {
+ const paths = await tmpPaths();
+ try {
+ await noteServiceCookieSignal(paths, { service: "rumble", kind: "embed-403", line: "a", videoId: "e1" }, { url: "https://rumble.com/v1-a.html" });
+ await noteServiceCookieSignal(paths, { service: "rumble", kind: "embed-403", line: "b", videoId: "e2" }, { url: "https://rumble.com/v2-b.html", channel: "huck" });
+ const calls: { cwd: string; args: string[] }[] = [];
+ const settled: string[] = [];
+ let answer = { exitCode: 1, stderrTail: embed403For("e2"), archiveLine: null };
+ const deps = {
+ runYtdlp: async (cwd: string, args: string[]) => {
+ calls.push({ cwd, args });
+ return answer;
+ },
+ readChannelConfig: async () => ({ name: "Huck", url: "https://rumble.com/c/huck", cookiesFromBrowser: "firefox" }) as never,
+ cookieSpec: () => "firefox",
+ recordPlatformClean: async (p: string) => {
+ settled.push(p);
+ return "rumble answered cleanly: its rate-limit backoff is cleared.\n";
+ },
+ };
+ const stale = await recheckServiceCookies({ paths, service: "rumble", deps });
+ assert.equal(stale.result, "stale");
+ assert.equal(calls.length, 1);
+ const args = calls[0].args;
+ assert.equal(args.at(-1), "https://rumble.com/v2-b.html");
+ assert.ok(args.includes("--skip-download"));
+ assert.deepEqual(args.slice(args.indexOf("--print"), args.indexOf("--print") + 2), ["--print", "id"]);
+ assert.deepEqual(args.slice(args.indexOf("--cookies-from-browser"), args.indexOf("--cookies-from-browser") + 2), ["--cookies-from-browser", "firefox"]);
+ assert.ok(args.includes("--impersonate"), "Rumble's own platform args");
+ assert.ok(args.indexOf("--no-write-info-json") > args.indexOf("--cookies-from-browser"), "refusals after the channel's args");
+ assert.equal(calls[0].cwd, path.join(paths.channelsDir, "huck"));
+ assert.equal(isAlertRaised((await readServiceCookieState(paths)).services.rumble), true);
+
+ answer = { exitCode: 0, stderrTail: "", archiveLine: null };
+ const clean = await recheckServiceCookies({ paths, service: "rumble", deps });
+ assert.equal(clean.result, "clean");
+ const state = await readServiceCookieState(paths);
+ assert.equal(state.services.rumble.clearedBy, "recheck");
+ assert.equal(state.lastGood.rumble.url, "https://rumble.com/v2-b.html");
+ assert.deepEqual(settled, ["rumble"]);
+
+ const nothing = await recheckServiceCookies({ paths, service: "odysee", deps });
+ assert.equal(nothing.result, "failed");
+ } finally {
+ await rm(paths.transcriptsDir, { recursive: true, force: true });
+ }
+});
+
+test("Recheck (forum): one page through the profile, judged by classifyForumPage", async () => {
+ const paths = await tmpPaths();
+ try {
+ const url = "https://kiwifarms.st/threads/x.1/";
+ await noteForumServiceOutcome(paths, url, { block: "challenge" });
+ let html = CHALLENGE_PAGE;
+ const loaded: string[] = [];
+ const deps = {
+ loadForumPage: async (_p: unknown, u: string) => {
+ loaded.push(u);
+ return { html };
+ },
+ };
+ assert.equal((await recheckServiceCookies({ paths, service: "kiwifarms.st", deps })).result, "stale");
+ html = `<html data-template="thread_view"><article class="message" data-content="post-1"></article></html>`;
+ assert.equal((await recheckServiceCookies({ paths, service: "kiwifarms.st", deps })).result, "clean");
+ assert.deepEqual(loaded, [url, url]);
+ } finally {
+ await rm(paths.transcriptsDir, { recursive: true, force: true });
+ }
+});
+
+test("Recheck (archive.today): the request that met the check, again; a check still standing keeps it", async () => {
+ const paths = await tmpPaths();
+ try {
+ const url = "https://archive.ph/timemap/https://example.com/page";
+ await noteServiceCookieSignal(paths, { service: "archive.today", kind: "check-page", line: "check" }, { url });
+ const asked: string[] = [];
+ let refuse = true;
+ const deps = {
+ archiveTodayRequest: async (u: string) => {
+ asked.push(u);
+ if (refuse) throw Object.assign(new Error("a CAPTCHA"), { code: "challenge" });
+ },
+ };
+ assert.equal((await recheckServiceCookies({ paths, service: "archive.today", deps })).result, "stale");
+ refuse = false;
+ assert.equal((await recheckServiceCookies({ paths, service: "archive.today", deps })).result, "clean");
+ assert.deepEqual(asked, [url, url]);
+ assert.equal((await readServiceCookieState(paths)).services["archive.today"].clearedBy, "recheck");
+ } finally {
+ await rm(paths.transcriptsDir, { recursive: true, force: true });
+ }
+});
diff --git a/common/controller/recheckServiceCookies.ts b/common/controller/recheckServiceCookies.ts
@@ -0,0 +1,213 @@
+// RECHECK A SERVICE'S COOKIES (cookie refresh alerts,
+// plans/cookie-refresh-alerts.md): ONE cheap request through the service's own
+// path, and the alert clears when it comes back clean.
+//
+// rumble / youtube / odysee one yt-dlp metadata request (`--skip-download
+// --print id`, which still asks Rumble's embed
+// JSON) for the last video the service answered
+// cleanly — else the one that showed the
+// signal — with the channel's own platform args
+// and the configured browser cookies.
+// a forum host one thread page through the host's headless
+// profile (social/forumSession.ts), judged by
+// classifyForumPage.
+// archive.today the request that met the check, again, through
+// the polite client (its observe hook records
+// the answer).
+//
+// A clean answer clears the alert (clearedBy "recheck") and, for a yt-dlp
+// service, settles the platform's backoff as any clean manual request does
+// (recordPlatformClean) — so "Re-run stopped jobs" is not refused by the
+// cooldown the 403s left behind. A signal answer keeps the alert; any other
+// failure keeps it and says what failed.
+
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import { getSettings } from "../lib/settings";
+import { detectPlatform } from "../lib/platform";
+import { authRetryCookies, cookieArgs, resolveCookiePolicy } from "../lib/cookiePolicy";
+import { classifyForumPage } from "../social/xenforoParse";
+import {
+ serviceCookieSignalFromStderr,
+ serviceFamily,
+ serviceLabel,
+} from "../lib/serviceCookies";
+import {
+ noteServiceCookieClean,
+ noteServiceCookieSignal,
+ readServiceCookieState,
+} from "../lib/serviceCookies-server";
+import { recordPlatformClean } from "../jobs/downloadBackoff";
+import { runOneYtdlp, type AttemptOutcome } from "../ytdlp/runOneYtdlp";
+import { channelExtraArgs, configForVideoUrl, pacedPlatformArgs } from "../ytdlp/channelArgs";
+import type { ChannelConfig } from "../lib/channelConfig";
+import { readChannelConfig } from "./channels";
+
+export type RecheckOutcome = {
+ service: string;
+ // "clean": the alert is cleared. "stale": the service still refused.
+ // "failed": the probe could not say (no request to ask, another error).
+ result: "clean" | "stale" | "failed";
+ message: string;
+};
+
+export type RecheckDeps = {
+ runYtdlp: (cwd: string, args: string[], onLog: (l: string) => void, signal: AbortSignal) => Promise<AttemptOutcome>;
+ // One forum page through the host's headless profile.
+ loadForumPage: (
+ paths: Paths,
+ url: string,
+ signal: AbortSignal,
+ onLog: (l: string) => void,
+ ) => Promise<{ html: string; status?: number }>;
+ classifyForumPage: (html: string, status?: number) => { kind: string; detail: string } | null;
+ // archive.today's request again; throws its refusal.
+ archiveTodayRequest: (url: string, signal: AbortSignal) => Promise<void>;
+ readChannelConfig: (paths: Paths, slug: string) => Promise<ChannelConfig | null>;
+ cookieSpec: (config: ChannelConfig | null) => string | undefined;
+ recordPlatformClean: (platform: string, paths: Paths) => Promise<string | null>;
+};
+
+const defaultDeps = (paths: Paths): RecheckDeps => ({
+ runYtdlp: (cwd, args, onLog, signal) => runOneYtdlp({ ytdlpBin: paths.ytdlpBin, onLog, signal }, cwd, args),
+ loadForumPage: async (p, url, signal, onLog) => {
+ const { browserForumLoader, forumProfileDir } = await import("../social/forumSession");
+ const loader = browserForumLoader(forumProfileDir(p, new URL(url).hostname), { onLog });
+ try {
+ return await loader.load(url, signal);
+ } finally {
+ await loader.close();
+ }
+ },
+ classifyForumPage,
+ archiveTodayRequest: async (url, signal) => {
+ const { archiveTodayClient } = await import("../lib/archives");
+ const timemap = /^https?:\/\/[^/]+\/timemap\/(.+)$/.exec(url);
+ if (timemap) await archiveTodayClient.listCaptures(timemap[1], { limit: 1, signal });
+ else await archiveTodayClient.getCapture(url, { signal });
+ },
+ readChannelConfig,
+ cookieSpec: (config) => {
+ try {
+ return authRetryCookies(resolveCookiePolicy(getSettings(), config ?? undefined));
+ } catch {
+ return config?.cookiesFromBrowser || undefined;
+ }
+ },
+ recordPlatformClean: (platform, p) => recordPlatformClean(platform, p),
+});
+
+// The probe's argv: metadata only, nothing written, the channel's own args
+// (its platform's pace and impersonation, its extra args) and the cookies —
+// and the refusals after the operator's args, as the window fetch does.
+export function recheckYtdlpArgs(url: string, config: ChannelConfig | null, cookies: string | undefined): string[] {
+ const platform = detectPlatform(url);
+ return [
+ "--ignore-config",
+ "--no-playlist",
+ "--skip-download",
+ "--print",
+ "id",
+ ...(config ? channelExtraArgs(configForVideoUrl(config, url), cookies) : [...cookieArgs(cookies), ...pacedPlatformArgs(platform)]),
+ "--no-write-info-json",
+ "--no-write-description",
+ "--no-write-thumbnail",
+ "--no-write-subs",
+ "--no-write-auto-subs",
+ "--no-download-archive",
+ "--",
+ url,
+ ];
+}
+
+export async function recheckServiceCookies(opts: {
+ paths: Paths;
+ service: string;
+ onLog?: (line: string) => void;
+ signal?: AbortSignal;
+ deps?: Partial<RecheckDeps>;
+}): Promise<RecheckOutcome> {
+ const { paths, service } = opts;
+ const deps = { ...defaultDeps(paths), ...opts.deps };
+ const log = (l: string) => opts.onLog?.(l.endsWith("\n") ? l : `${l}\n`);
+ const signal = opts.signal ?? new AbortController().signal;
+ const label = serviceLabel(service);
+ const state = await readServiceCookieState(paths);
+ const entry = state.services[service];
+ const good = state.lastGood[service];
+ const target = good ?? (entry?.evidence.url ? { url: entry.evidence.url, channel: entry.evidence.channel } : null);
+ const out = (result: RecheckOutcome["result"], message: string): RecheckOutcome => {
+ log(message);
+ return { service, result, message };
+ };
+
+ const clean = async (detail: string): Promise<RecheckOutcome> => {
+ await noteServiceCookieClean(paths, service, target ? { url: target.url, ...(target.channel ? { channel: target.channel } : {}) } : undefined, {
+ by: "recheck",
+ });
+ if (serviceFamily(service) === "ytdlp") {
+ const settled = await deps.recordPlatformClean(service, paths).catch(() => null);
+ if (settled) log(settled.trimEnd());
+ }
+ return out("clean", `${label} answered cleanly (${detail}): its cookie alert is cleared.`);
+ };
+
+ switch (serviceFamily(service)) {
+ case "ytdlp": {
+ if (!target) {
+ return out("failed", `Nothing to recheck ${label} with: no clean request and no failing one is recorded.`);
+ }
+ const config = target.channel ? await deps.readChannelConfig(paths, target.channel).catch(() => null) : null;
+ const args = recheckYtdlpArgs(target.url, config, deps.cookieSpec(config));
+ const cwd = target.channel && config ? path.join(paths.channelsDir, target.channel) : paths.transcriptsDir;
+ log(`Rechecking ${label}: one metadata request for ${target.url}${good ? " (its last clean request)" : " (the request that failed)"}.`);
+ const res = await deps.runYtdlp(cwd, args, (l) => opts.onLog?.(l), signal);
+ if (res.exitCode === 0) return clean(target.url);
+ const sig = serviceCookieSignalFromStderr(res.stderrTail, detectPlatform(target.url));
+ if (sig && sig.service === service) {
+ await noteServiceCookieSignal(paths, sig, { url: target.url, ...(target.channel ? { channel: target.channel } : {}) });
+ return out("stale", `${label} still refused (${sig.line}). The cookies are still stale.`);
+ }
+ const tail = res.stderrTail.trim().split("\n").slice(-2).join(" / ");
+ return out("failed", `The ${label} recheck failed for another reason (exit ${res.exitCode ?? "null"}): ${tail || "no output"}. The alert stays.`);
+ }
+ case "forum": {
+ const url = target?.url;
+ if (!url) return out("failed", `Nothing to recheck ${label} with: no thread page is recorded.`);
+ log(`Rechecking ${label}: one page through the forum's headless profile (${url}).`);
+ let page: { html: string; status?: number };
+ try {
+ page = await deps.loadForumPage(paths, url, signal, (l) => log(l));
+ } catch (e) {
+ return out("failed", `The ${label} recheck could not load the page: ${(e as Error).message}. The alert stays.`);
+ }
+ const block = deps.classifyForumPage(page.html, page.status);
+ if (!block) return clean(url);
+ if (block.kind === "challenge" || block.kind === "captcha" || block.kind === "login") {
+ await noteServiceCookieSignal(
+ paths,
+ { service, kind: "challenge", line: `${service}: ${block.kind} — ${block.detail}` },
+ { url, ...(target?.channel ? { channel: target.channel } : {}) },
+ );
+ return out("stale", `${label} still shows a ${block.kind} (${block.detail}).`);
+ }
+ return out("failed", `${label} answered the page with ${block.kind} (${block.detail}); the alert stays.`);
+ }
+ case "archive": {
+ const url = target?.url;
+ if (!url) {
+ return out("failed", `Nothing to recheck ${label} with: no request is recorded. Connect archive session instead.`);
+ }
+ log(`Rechecking ${label}: the request that met the check, once more (${url}).`);
+ try {
+ await deps.archiveTodayRequest(url, signal);
+ } catch (e) {
+ const code = (e as { code?: string }).code;
+ if (code === "challenge") return out("stale", `${label} still answers with a check. Connect archive session.`);
+ if (code === "not-archived") return clean(url);
+ return out("failed", `The ${label} recheck failed: ${(e as Error).message}. The alert stays.`);
+ }
+ return clean(url);
+ }
+ }
+}
diff --git a/common/controller/refreshVideoMetadata.ts b/common/controller/refreshVideoMetadata.ts
@@ -402,7 +402,12 @@ export async function refreshVideoMetadata(
opts.run ??
((cwd, args) =>
runOneYtdlp(
- { ytdlpBin: opts.paths.ytdlpBin, onLog: opts.onLog, signal: opts.signal },
+ {
+ ytdlpBin: opts.paths.ytdlpBin,
+ onLog: opts.onLog,
+ signal: opts.signal,
+ observe: { paths: opts.paths, url: opts.videoUrl, channel: opts.slug },
+ },
cwd,
args,
));
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -112,6 +112,18 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
replayable: false,
queueKeyStrategy: "custom",
},
+ // THE DASHBOARD'S "Recheck" on a cookie refresh alert
+ // (controller/recheckServiceCookies.ts): ONE request through the service's
+ // own path, the alert cleared when it comes back clean. Its own queue
+ // (`service-cookies:<service>`), so a long download on the platform's queue
+ // never makes the click wait. Writes nothing but the alert's state file.
+ "recheck-service-cookies": {
+ kind: "recheck-service-cookies",
+ label: "Recheck service cookies",
+ drainable: false,
+ replayable: false,
+ queueKeyStrategy: "custom",
+ },
// The two OPERATION lanes' runners. Same shape as the two above — one
// long-lived job per lane on queueKey "", drainable, never replayable — with
// one difference worth stating: their units make NO job record. A digest or a
diff --git a/common/jobs/streamCommand.ts b/common/jobs/streamCommand.ts
@@ -27,6 +27,9 @@ import {
ChannelMediaUnreachableError,
} from "../lib/channelMedia";
import { mediaHoldText } from "../lib/channelMediaHold";
+import { runInJobContext, type JobContext } from "../lib/jobContext";
+import { serviceStoppedLine } from "../lib/serviceCookies";
+import { configuredCookieBrowser } from "../lib/serviceCookies-server";
// Mark a job's channel report dirty so the debounced scheduler regenerates the
// snapshot — called both on each completed sub-operation and on the job's
@@ -450,10 +453,21 @@ export async function runManagedFunction(
// THE GUARD AGAIN, NOW THAT THE QUEUE HAS STARTED THE JOB (see
// refuseForUnreachableMedia): a refusal here fails the job before `fn`
// touches anything, with the sentence as its log's `[error]` line.
+ //
+ // THE JOB'S ASYNC CONTEXT (lib/jobContext.ts): code under `fn` — the one
+ // yt-dlp runner, a forum fetch — reads which job it runs in, so a cookie
+ // refresh alert can name the job it stopped and write into its log.
+ const jobCtx: JobContext = {
+ jobId: id,
+ kind: opts.kind,
+ ...(opts.channelSlug ? { channelSlug: opts.channelSlug } : {}),
+ onLog,
+ staleServices: new Set<string>(),
+ };
const run = async () => {
const refusal = await refuseForUnreachableMedia(opts);
if (refusal) throw new Error(refusal);
- await opts.fn(onLog, abort.signal, setProgress, ctx);
+ await runInJobContext(jobCtx, () => opts.fn(onLog, abort.signal, setProgress, ctx));
};
run()
.then(() => {
@@ -469,6 +483,11 @@ export async function runManagedFunction(
return;
}
onLog(`[error] ${(err as Error).message}`);
+ // A job that met a stale service's cookies (a cookie refresh alert)
+ // ends naming the cause and the fix, after its own error line.
+ for (const service of jobCtx.staleServices) {
+ onLog(serviceStoppedLine(service, configuredCookieBrowser()));
+ }
registry.finalize(id, "failed");
})
.finally(async () => {
diff --git a/common/lib/__fixtures__/rumble-embed-403.download.log b/common/lib/__fixtures__/rumble-embed-403.download.log
@@ -0,0 +1,19 @@
+$ yt-dlp --ignore-config --restrict-filenames -o data/v7h5ley/audio.%(ext)s -o subtitle:data/v7h5ley/transcript -o infojson:data/v7h5ley/metadata --no-write-playlist-metafiles --write-info-json --skip-download --no-write-subs --no-write-auto-subs --cookies-from-browser firefox --impersonate chrome --sleep-requests 2 --impersonate firefox --user-agent Mozilla/5.0 (X11; Linux x86_64; rv:156.0) Gecko/20100101 Firefox/156.0 -- https://rumble.com/v7h5ley-ilhan-omar-in-hiding-as-new-dna-proves-guilt-and-donald-trump-erupts.html
+Extracting cookies from firefox
+Extracted 2639 cookies from firefox
+[Rumble] Extracting URL: https://rumble.com/v7h5ley-ilhan-omar-in-hiding-as-new-dna-proves-guilt-and-donald-trump-erupts.html
+[Rumble] v7h5ley: Downloading webpage
+[RumbleEmbed] Extracting URL: https://rumble.com/embed/v7ez8hg
+[RumbleEmbed] Sleeping 2.0 seconds ...
+[RumbleEmbed] v7ez8hg: Downloading JSON metadata
+ERROR: [RumbleEmbed] v7ez8hg: Unable to download JSON metadata: HTTP Error 403: Forbidden (caused by <HTTPError 403: Forbidden>)
+Persistence: audio-only via ytdlp extraction (outside keep-latest window).
+$ yt-dlp --ignore-config --restrict-filenames --no-quiet --progress --newline --progress-delta 1 --progress-template download:DLOM_PROGRESS status=%(progress.status)s downloaded=%(progress.downloaded_bytes)s total=%(progress.total_bytes,progress.total_bytes_estimate)s frag=%(progress.fragment_index)s/%(progress.fragment_count)s speed=%(progress.speed)s eta=%(progress.eta)s -o data/v7h5ley/audio.%(ext)s -o subtitle:data/v7h5ley/transcript -o infojson:data/v7h5ley/metadata --no-write-playlist-metafiles --write-info-json -f bestaudio/worst -x --audio-format mp3 --print after_video:DLOM_ARCHIVE %(extractor)s %(id)s --cookies-from-browser firefox --impersonate chrome --sleep-requests 2 --impersonate firefox --user-agent Mozilla/5.0 (X11; Linux x86_64; rv:156.0) Gecko/20100101 Firefox/156.0 -- https://rumble.com/v7h5ley-ilhan-omar-in-hiding-as-new-dna-proves-guilt-and-donald-trump-erupts.html
+Extracting cookies from firefox
+Extracted 2639 cookies from firefox
+[Rumble] Extracting URL: https://rumble.com/v7h5ley-ilhan-omar-in-hiding-as-new-dna-proves-guilt-and-donald-trump-erupts.html
+[Rumble] v7h5ley: Downloading webpage
+[RumbleEmbed] Extracting URL: https://rumble.com/embed/v7ez8hg
+[RumbleEmbed] Sleeping 2.0 seconds ...
+[RumbleEmbed] v7ez8hg: Downloading JSON metadata
+ERROR: [RumbleEmbed] v7ez8hg: Unable to download JSON metadata: HTTP Error 403: Forbidden (caused by <HTTPError 403: Forbidden>)
diff --git a/common/lib/__fixtures__/rumble-fetch-windows-stopped.log b/common/lib/__fixtures__/rumble-fetch-windows-stopped.log
@@ -0,0 +1,38 @@
+Fetched 399.40–467.88 of v7gwn3w into clips/399.40-467.88.mp4 (5920869 bytes).
+Sleeping 137s before the next fetch...
+$ yt-dlp --ignore-config --no-playlist --sleep-requests 1 --download-sections *2248.60-2267.16 --force-keyframes-at-cuts -f bv*[vcodec^=avc1][height<=720]+ba[acodec^=mp4a]/bv*[ext=mp4][height<=720]+ba[ext=m4a]/b[ext=mp4][height<=720]/b[height<=720] --merge-output-format mp4 --no-quiet --progress --newline --progress-delta 1 --cookies-from-browser firefox --impersonate chrome --sleep-requests 1 --impersonate firefox --user-agent Mozilla/5.0 (X11; Linux x86_64; rv:156.0) Gecko/20100101 Firefox/156.0 --no-write-info-json --no-write-description --no-write-thumbnail --no-write-subs --no-write-auto-subs --no-download-archive --downloader-args ffmpeg_i:-extension_picky 0 -o <corpus>/channels/the-quartering-rumble/data/v7fi2x6/clips/2248.60-2267.16.part.mp4 -- https://rumble.com/v7fi2x6-psycho-leftists-find-out-leaked-clancy-texts-possible-misconduct-hasan-pike.html
+Extracting cookies from firefox
+Extracted 2858 cookies from firefox
+[Rumble] Extracting URL: https://rumble.com/v7fi2x6-psycho-leftists-find-out-leaked-clancy-texts-possible-misconduct-hasan-pike.html
+[Rumble] v7fi2x6: Downloading webpage
+[RumbleEmbed] Extracting URL: https://rumble.com/embed/v7dbpzo
+[RumbleEmbed] Sleeping 1.0 seconds ...
+[RumbleEmbed] v7dbpzo: Downloading JSON metadata
+[RumbleEmbed] Sleeping 1.0 seconds ...
+[RumbleEmbed] v7dbpzo: Downloading m3u8 information
+[info] v7dbpzo: Downloading 1 format(s): hls-2140
+[info] v7dbpzo: Downloading 1 time ranges: 2248.6-2267.2
+[download] Destination: <corpus>/channels/the-quartering-rumble/data/v7fi2x6/clips/2248.60-2267.16.part.mp4
+Fetched 2248.60–2267.16 of v7fi2x6 into clips/2248.60-2267.16.mp4 (1419251 bytes).
+Sleeping 142s before the next fetch...
+$ yt-dlp --ignore-config --no-playlist --sleep-requests 1 --download-sections *245.40-265.40 --force-keyframes-at-cuts -f bv*[vcodec^=avc1][height<=720]+ba[acodec^=mp4a]/bv*[ext=mp4][height<=720]+ba[ext=m4a]/b[ext=mp4][height<=720]/b[height<=720] --merge-output-format mp4 --no-quiet --progress --newline --progress-delta 1 --cookies-from-browser firefox --impersonate chrome --sleep-requests 1 --impersonate firefox --user-agent Mozilla/5.0 (X11; Linux x86_64; rv:156.0) Gecko/20100101 Firefox/156.0 --no-write-info-json --no-write-description --no-write-thumbnail --no-write-subs --no-write-auto-subs --no-download-archive --downloader-args ffmpeg_i:-extension_picky 0 -o <corpus>/channels/the-quartering-rumble/data/v7fdzwe/clips/245.40-265.40.part.mp4 -- https://rumble.com/v7fdzwe-lindsay-clancy-hero-juror-identified-the-left-loses-their-minds.html
+Extracting cookies from firefox
+Extracted 2858 cookies from firefox
+[Rumble] Extracting URL: https://rumble.com/v7fdzwe-lindsay-clancy-hero-juror-identified-the-left-loses-their-minds.html
+[Rumble] v7fdzwe: Downloading webpage
+[RumbleEmbed] Extracting URL: https://rumble.com/embed/v7d7myw
+[RumbleEmbed] Sleeping 1.0 seconds ...
+[RumbleEmbed] v7d7myw: Downloading JSON metadata
+ERROR: [RumbleEmbed] v7d7myw: Unable to download JSON metadata: HTTP Error 403: Forbidden (caused by <HTTPError 403: Forbidden>)
+Sleeping 141s before the next fetch...
+$ yt-dlp --ignore-config --no-playlist --sleep-requests 1 --download-sections *2565.24-2592.84 --force-keyframes-at-cuts -f bv*[vcodec^=avc1][height<=720]+ba[acodec^=mp4a]/bv*[ext=mp4][height<=720]+ba[ext=m4a]/b[ext=mp4][height<=720]/b[height<=720] --merge-output-format mp4 --no-quiet --progress --newline --progress-delta 1 --cookies-from-browser firefox --impersonate chrome --sleep-requests 1 --impersonate firefox --user-agent Mozilla/5.0 (X11; Linux x86_64; rv:156.0) Gecko/20100101 Firefox/156.0 --no-write-info-json --no-write-description --no-write-thumbnail --no-write-subs --no-write-auto-subs --no-download-archive --downloader-args ffmpeg_i:-extension_picky 0 -o <corpus>/channels/the-quartering-rumble/data/v7f8yuw/clips/2565.24-2592.84.part.mp4 -- https://rumble.com/v7f8yuw-lindsay-clancy-copycat-kills-4-kids-tucker-gets-weird-mamdani-loves-911.html
+Extracting cookies from firefox
+Extracted 2858 cookies from firefox
+[Rumble] Extracting URL: https://rumble.com/v7f8yuw-lindsay-clancy-copycat-kills-4-kids-tucker-gets-weird-mamdani-loves-911.html
+[Rumble] v7f8yuw: Downloading webpage
+[RumbleEmbed] Extracting URL: https://rumble.com/embed/v7d2lxe
+[RumbleEmbed] Sleeping 1.0 seconds ...
+[RumbleEmbed] v7d2lxe: Downloading JSON metadata
+ERROR: [RumbleEmbed] v7d2lxe: Unable to download JSON metadata: HTTP Error 403: Forbidden (caused by <HTTPError 403: Forbidden>)
+Fetch windows: 4 fetched, 0 cached, 2 failed, 16 not attempted (stopped: network).
+[error] Stopped (network) with 16 window(s) not attempted — run it again later.
diff --git a/common/lib/archives/archiveTodayClient.ts b/common/lib/archives/archiveTodayClient.ts
@@ -96,8 +96,16 @@ export type ArchiveTodayClientDeps = {
// The canonical host, read per request (settings can change while the
// editor runs).
host?: () => string;
+ // Told of every check that stood and every answer that was not one — the
+ // cookie refresh alert for archive.today (lib/serviceCookies-server.ts).
+ // Its failure never fails the request.
+ observe?: (o: ArchiveTodayObservation) => void | Promise<void>;
};
+export type ArchiveTodayObservation =
+ | { challenge: true; url: string; line: string }
+ | { challenge: false; url: string };
+
export type ArchiveTodayClientOpts = {
minGapMs?: number | (() => number);
// Up to this fraction of the gap again, at random.
@@ -145,8 +153,8 @@ function retryAfterMs(value: string | null, nowMs: number): number | null {
const minutes = (ms: number) => Math.max(1, Math.round(ms / 60_000));
export class ArchiveTodayClient {
- private readonly deps: Required<Omit<ArchiveTodayClientDeps, "openBrowser" | "host" | "browserEnabled">> &
- Pick<ArchiveTodayClientDeps, "openBrowser" | "host" | "browserEnabled">;
+ private readonly deps: Required<Omit<ArchiveTodayClientDeps, "openBrowser" | "host" | "browserEnabled" | "observe">> &
+ Pick<ArchiveTodayClientDeps, "openBrowser" | "host" | "browserEnabled" | "observe">;
private readonly opts: Required<Omit<ArchiveTodayClientOpts, "minGapMs" | "cooldownMs">> & {
minGapMs: () => number;
cooldownMs: () => number;
@@ -168,6 +176,7 @@ export class ArchiveTodayClient {
...(deps.openBrowser ? { openBrowser: deps.openBrowser } : {}),
...(deps.host ? { host: deps.host } : {}),
...(deps.browserEnabled ? { browserEnabled: deps.browserEnabled } : {}),
+ ...(deps.observe ? { observe: deps.observe } : {}),
};
const gap = opts.minGapMs ?? 8_000;
const cool = opts.cooldownMs ?? 30 * 60_000;
@@ -305,6 +314,29 @@ export class ArchiveTodayClient {
);
}
+ // The refusal at a check that stood, told to `observe` first (the cookie
+ // refresh alert for archive.today).
+ private async challenged(url: string, html: string, triedBrowser: boolean): Promise<ArchiveRefusal> {
+ const refusal = this.challengeRefusal(url, html, triedBrowser);
+ await this.note({ challenge: true, url, line: refusal.message });
+ return refusal;
+ }
+
+ // An answer that was not a check (a copy, a timemap, a 404): told to
+ // `observe`, which clears a cookie refresh alert.
+ private async answered<T>(url: string, out: T): Promise<T> {
+ await this.note({ challenge: false, url });
+ return out;
+ }
+
+ private async note(o: ArchiveTodayObservation): Promise<void> {
+ try {
+ await this.deps.observe?.(o);
+ } catch {
+ // bookkeeping only
+ }
+ }
+
// THE COPIES OF A PAGE, oldest first: its timemap
// (`/timemap/<original>`, one request). A 404 is "none". Within
// `from`/`to` (capture-time prefixes), at most `limit`.
@@ -316,11 +348,11 @@ export class ArchiveTodayClient {
const url = `https://${this.host}/timemap/${originalUrl}`;
const res = await this.send(url, { accept: "application/link-format,text/plain;q=0.9,*/*;q=0.1", maxBytes: 8 * 1024 * 1024, signal: o.signal });
let text: string;
- if (res.status === 404 || res.status === 410) return [];
+ if (res.status === 404 || res.status === 410) return this.answered(url, []);
const body = res.body?.toString("utf8") ?? "";
if (isArchiveTodayChallenge(body)) {
const b = await this.viaBrowser(url, o.signal);
- if (!b || isArchiveTodayChallenge(b.html)) throw this.challengeRefusal(url, b?.html ?? body, !!b);
+ if (!b || isArchiveTodayChallenge(b.html)) throw await this.challenged(url, b?.html ?? body, !!b);
text = b.text;
} else if (res.status >= 200 && res.status < 300) {
if (res.tooLarge) throw new ArchiveTodayRequestError(`archive.today's timemap of ${originalUrl} is over 8 MB; not read`, res.status);
@@ -331,7 +363,7 @@ export class ArchiveTodayClient {
const rows = parseArchiveTodayTimemap(text, originalUrl)
.map((r) => ({ ...r, mementoUrl: this.canonical(r.mementoUrl) }))
.filter((r) => withinCaptureRange(r.captureTs, o.from, o.to));
- return o.limit ? rows.slice(0, o.limit) : rows;
+ return this.answered(url, o.limit ? rows.slice(0, o.limit) : rows);
});
}
@@ -387,8 +419,8 @@ export class ArchiveTodayClient {
const text = res.body?.toString("utf8") ?? "";
if (res.body && isArchiveTodayChallenge(text)) {
const b = await this.viaBrowser(at, o.signal);
- if (!b || isArchiveTodayChallenge(b.html)) throw this.challengeRefusal(at, b?.html ?? text, !!b);
- return this.copyOf(Buffer.from(b.html, "utf8"), "text/html; charset=utf-8", b.url && isArchiveTodayHost(safeHost(b.url)) ? this.canonical(b.url) : at, null, ref, true);
+ if (!b || isArchiveTodayChallenge(b.html)) throw await this.challenged(at, b?.html ?? text, !!b);
+ return this.answered(at, this.copyOf(Buffer.from(b.html, "utf8"), "text/html; charset=utf-8", b.url && isArchiveTodayHost(safeHost(b.url)) ? this.canonical(b.url) : at, null, ref, true));
}
if (res.status === 404 || res.status === 410) {
throw new ArchiveRefusal("archive.today", "not-archived", `archive.today holds no copy at ${at}`);
@@ -407,7 +439,7 @@ export class ArchiveTodayClient {
if (res.tooLarge || !res.body) {
throw new ArchiveRefusal("archive.today", "too-large", `archive.today's copy at ${at} is over ${Math.round(maxBytes / 1024)} KB; not read`);
}
- return this.copyOf(res.body, contentType, at, res.headers, ref, false);
+ return this.answered(at, this.copyOf(res.body, contentType, at, res.headers, ref, false));
}
throw new ArchiveRefusal("archive.today", "redirect-loop", `archive.today redirected ${ref.mementoUrl} more than ${ARCHIVE_TODAY_MAX_REDIRECTS} times`);
});
diff --git a/common/lib/archives/index.ts b/common/lib/archives/index.ts
@@ -21,6 +21,7 @@ import {
processArchiveTodayFetch,
} from "./archiveTodayClient";
import { archiveSessionBrowser } from "./archiveTodaySession";
+import { noteArchiveTodayOutcome } from "../serviceCookies-server";
import { ArchiveRefusal, type ArchiveCaptureRow, type ArchiveRefusalCode, type ArchiveSource, type ArchiveSourceId } from "./types";
export * from "./types";
@@ -42,6 +43,8 @@ export const archiveTodayClient = new ArchiveTodayClient(
host: () => archivesSettings()?.archiveTodayHost ?? "archive.ph",
openBrowser: () => archiveSessionBrowser(getPaths(), { onLog: (l) => console.log(`[archive-session] ${l}`) })(),
browserEnabled: () => archivesSettings()?.archiveTodayBrowser !== false && archiveTodayTestOrigin() === null,
+ // The cookie refresh alert for archive.today (lib/serviceCookies.ts).
+ observe: (o) => noteArchiveTodayOutcome(getPaths(), o),
},
{
minGapMs: () => (archivesSettings()?.archiveTodayGapSeconds ?? 8) * 1000,
diff --git a/common/lib/jobContext.ts b/common/lib/jobContext.ts
@@ -0,0 +1,40 @@
+// THE RUNNING JOB, as an async context (cookie refresh alerts,
+// plans/cookie-refresh-alerts.md). runManagedFunction runs every job's `fn`
+// inside `runInJobContext`, so code deep under it — the one yt-dlp runner, a
+// forum fetch — can say which job met a stale service and write the sentence
+// into THAT job's log, without a jobId threaded through forty signatures.
+//
+// Read-only for its consumers: what the job is, its log, and a set the cookie
+// recorder marks so the job's failure line can name the cause. Outside a job
+// (a test calling a controller directly, a CLI run) there is no context and
+// nothing is attributed.
+//
+// SERVER-ONLY (node:async_hooks). One storage per process, on globalThis — the
+// house pattern for state Next may load twice (jobs/registry.ts).
+
+import { AsyncLocalStorage } from "node:async_hooks";
+
+export type JobContext = {
+ jobId: string;
+ kind: string;
+ channelSlug?: string;
+ // The job's log (the same sink its `fn` writes to).
+ onLog: (line: string) => void;
+ // Services whose cookie alert this job met while it ran (serviceCookies).
+ staleServices: Set<string>;
+};
+
+const KEY = Symbol.for("archilyzer.jobContext");
+
+function storage(): AsyncLocalStorage<JobContext> {
+ const g = globalThis as unknown as Record<symbol, AsyncLocalStorage<JobContext> | undefined>;
+ return (g[KEY] ??= new AsyncLocalStorage<JobContext>());
+}
+
+export function runInJobContext<T>(ctx: JobContext, fn: () => T): T {
+ return storage().run(ctx, fn);
+}
+
+export function currentJobContext(): JobContext | undefined {
+ return storage().getStore();
+}
diff --git a/common/lib/serviceCookies-server.test.ts b/common/lib/serviceCookies-server.test.ts
@@ -0,0 +1,195 @@
+// 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 { 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,
+ 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 });
+ }
+});
diff --git a/common/lib/serviceCookies-server.ts b/common/lib/serviceCookies-server.ts
@@ -0,0 +1,305 @@
+// COOKIE REFRESH ALERTS — the file (plans/cookie-refresh-alerts.md):
+// `<transcriptsDir>/.service-cookies.json`, one record per service. The pure
+// rules are lib/serviceCookies.ts; this is the read, the locked
+// read-modify-write and the job-log line.
+//
+// Every writer goes through `mutate` (withJsonFileLock + writeJsonAtomic): two
+// jobs on two platforms meeting their services at once must not drop each
+// other's record. A read that fails or a file that is not JSON is an empty
+// state, never a throw — an alert is a convenience, and no job may fail
+// because its bookkeeping could not be written (every recorder here swallows
+// its own errors).
+
+import path from "node:path";
+import type { Paths } from "./paths";
+import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "./jsonFile-server";
+import { currentJobContext } from "./jobContext";
+import { getSettings } from "./settings";
+import { detectPlatform } from "./platform";
+import {
+ ARCHIVE_TODAY_SERVICE,
+ applyServiceCookieClean,
+ applyServiceCookieSignal,
+ coerceServiceCookieState,
+ forumServiceKey,
+ isAlertRaised,
+ isYtdlpCookieService,
+ noteLastGood,
+ pruneServiceCookieState,
+ serviceCookieSignalFromStderr,
+ serviceLabel,
+ serviceStoppedLine,
+ type ServiceCookieEntry,
+ type ServiceCookieSignal,
+ type ServiceCookieState,
+ type SignalContext,
+} from "./serviceCookies";
+
+export const SERVICE_COOKIES_FILE = ".service-cookies.json";
+
+export function serviceCookiesFile(paths: Pick<Paths, "transcriptsDir">): string {
+ return path.join(paths.transcriptsDir, SERVICE_COOKIES_FILE);
+}
+
+export async function readServiceCookieState(
+ paths: Pick<Paths, "transcriptsDir">,
+): Promise<ServiceCookieState> {
+ const read = await readJsonFile(serviceCookiesFile(paths));
+ return coerceServiceCookieState(read.ok ? read.value : null);
+}
+
+// The configured browser spec, for the fix sentence; undefined when settings
+// cannot be read (a CLI with no corpus, a test).
+export function configuredCookieBrowser(): string | undefined {
+ try {
+ return getSettings().cookiesFromBrowser || undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+// THE ONE WRITER: read under the file's lock, change, write when `mutate`
+// says something changed.
+async function mutate<T>(
+ paths: Pick<Paths, "transcriptsDir">,
+ fn: (state: ServiceCookieState, now: number) => { changed: boolean; out: T },
+ now: number = Date.now(),
+): Promise<T> {
+ const file = serviceCookiesFile(paths);
+ return withJsonFileLock(file, async () => {
+ const state = await readServiceCookieState(paths);
+ const pruned = pruneServiceCookieState(state, now);
+ const { changed, out } = fn(state, now);
+ if (changed || pruned) await writeJsonAtomic(file, state, { mkdir: true });
+ return out;
+ });
+}
+
+export type NoteSignalResult = {
+ entry: ServiceCookieEntry;
+ raisedNow: boolean;
+ // The alert is up (raised now or before).
+ raised: boolean;
+};
+
+// A cookie signal seen. Inside a job (lib/jobContext.ts) the job is recorded
+// against the alert and, once the alert is up, the job's log names the cause
+// and the fix — once per job per service.
+export async function noteServiceCookieSignal(
+ paths: Pick<Paths, "transcriptsDir">,
+ signal: ServiceCookieSignal,
+ ctx: Omit<SignalContext, "jobId" | "jobKind"> = {},
+ opts: { now?: number; browser?: string } = {},
+): Promise<NoteSignalResult | null> {
+ // A Recheck's own job is not one the alert stopped: it is the question.
+ const ctxJob = currentJobContext();
+ const job = ctxJob?.kind === "recheck-service-cookies" ? undefined : ctxJob;
+ try {
+ const res = await mutate(
+ paths,
+ (state, now) => {
+ const r = applyServiceCookieSignal(
+ state,
+ signal,
+ {
+ ...ctx,
+ ...(job ? { jobId: job.jobId, jobKind: job.kind } : {}),
+ ...(ctx.channel || !job?.channelSlug ? {} : { channel: job.channelSlug }),
+ },
+ now,
+ );
+ return { changed: true, out: { ...r, raised: isAlertRaised(r.entry) } };
+ },
+ opts.now,
+ );
+ if (res.raised && job && !job.staleServices.has(signal.service)) {
+ job.staleServices.add(signal.service);
+ job.onLog(`${serviceStoppedLine(signal.service, opts.browser ?? configuredCookieBrowser())}\n`);
+ } else if (!res.raised && job && signal.kind === "embed-403") {
+ job.onLog(
+ `${serviceLabel(signal.service)} refused an embed (${signal.videoId ?? "?"}) with a 403 — a removed video does ` +
+ `this too; a second video refused in a row raises the cookie alert.\n`,
+ );
+ }
+ return res;
+ } catch {
+ return null;
+ }
+}
+
+// A clean request to the service: a raised alert clears (the line for the
+// job log comes back), a pending first signal is forgotten, and the request is
+// remembered as the one Recheck asks again.
+export async function noteServiceCookieClean(
+ paths: Pick<Paths, "transcriptsDir">,
+ service: string,
+ good?: { url: string; channel?: string },
+ opts: { now?: number; by?: NonNullable<ServiceCookieEntry["clearedBy"]> } = {},
+): Promise<string | null> {
+ try {
+ return await mutate(
+ paths,
+ (state, now) => {
+ const effect = applyServiceCookieClean(state, service, now, opts.by ?? "clean");
+ const goodChanged = good ? noteLastGood(state, service, good, now) : false;
+ return {
+ changed: effect !== null || goodChanged,
+ out:
+ effect === "cleared"
+ ? `${serviceLabel(service)} answered cleanly: its cookie alert is cleared.\n`
+ : null,
+ };
+ },
+ opts.now,
+ );
+ } catch {
+ return null;
+ }
+}
+
+// The cheap peek every clean yt-dlp run makes before taking the lock: is there
+// anything for a clean to change? (An alert or a pending signal, or a
+// lastGood worth refreshing.) Never throws.
+async function cleanWouldChange(
+ paths: Pick<Paths, "transcriptsDir">,
+ service: string,
+ now: number,
+): Promise<boolean> {
+ const state = await readServiceCookieState(paths);
+ const e = state.services[service];
+ if (e && !e.clearedAt) return true;
+ const g = state.lastGood[service];
+ return !g || now - Date.parse(g.at) >= 10 * 60_000;
+}
+
+// THE yt-dlp HOOK (ytdlp/runOneYtdlp.ts): one invocation's outcome for the
+// service its URL is on. A non-zero exit whose stderr carries a cookie signal
+// records it; a zero exit is a clean request. Never throws.
+export async function observeYtdlpServiceOutcome(
+ paths: Pick<Paths, "transcriptsDir">,
+ run: { url: string; channel?: string; exitCode: number | null; stderrTail: string; aborted?: boolean },
+): Promise<void> {
+ if (run.aborted) return;
+ const platform = detectPlatform(run.url);
+ try {
+ if (run.exitCode === 0) {
+ if (!platform || !isYtdlpCookieService(platform)) return;
+ const now = Date.now();
+ if (!(await cleanWouldChange(paths, platform, now))) return;
+ const line = await noteServiceCookieClean(paths, platform, { url: run.url, channel: run.channel }, { now });
+ if (line) currentJobContext()?.onLog(line);
+ return;
+ }
+ const signal = serviceCookieSignalFromStderr(run.stderrTail, platform);
+ if (!signal) return;
+ await noteServiceCookieSignal(paths, signal, {
+ url: run.url,
+ ...(run.channel ? { channel: run.channel } : {}),
+ });
+ } catch {
+ // bookkeeping only
+ }
+}
+
+// A stderr that already stopped a batch (a metadata scan's bot check, an
+// availability probe's, a listing's): the signal, when there is one.
+export async function observeStderrServiceSignal(
+ paths: Pick<Paths, "transcriptsDir">,
+ stderr: string,
+ ctx: { url?: string; channel?: string; platform?: string | null } = {},
+): Promise<void> {
+ const signal = serviceCookieSignalFromStderr(stderr, ctx.platform ?? (ctx.url ? detectPlatform(ctx.url) : null));
+ if (!signal) return;
+ await noteServiceCookieSignal(paths, signal, {
+ ...(ctx.url ? { url: ctx.url } : {}),
+ ...(ctx.channel ? { channel: ctx.channel } : {}),
+ });
+}
+
+// A FORUM's walk (controller/fetchPosts.ts), keyed by the thread's host: a
+// browser check, a captcha or a login wall that stopped it is the forum
+// session's cookies (classifyForumPage → forumBlockFailure's needsCookies); a
+// walk that read its pages with no block is a clean request. Never throws.
+export async function noteForumServiceOutcome(
+ paths: Pick<Paths, "transcriptsDir">,
+ threadUrl: string,
+ outcome: { block?: string; error?: string; channel?: string },
+): Promise<string | null> {
+ let host: string;
+ try {
+ host = forumServiceKey(new URL(threadUrl).hostname);
+ } catch {
+ return null;
+ }
+ if (outcome.block === "challenge" || outcome.block === "captcha" || outcome.block === "login") {
+ await noteServiceCookieSignal(
+ paths,
+ { service: host, kind: "challenge", line: (outcome.error ?? `${host}: ${outcome.block}`).slice(0, 300) },
+ { url: threadUrl, ...(outcome.channel ? { channel: outcome.channel } : {}) },
+ );
+ return null;
+ }
+ if (outcome.block || outcome.error) return null;
+ return noteServiceCookieClean(paths, host, { url: threadUrl, ...(outcome.channel ? { channel: outcome.channel } : {}) });
+}
+
+// archive.today's polite client (lib/archives/archiveTodayClient.ts): a check
+// page that stood even through the headless browser, or a clean answer.
+export async function noteArchiveTodayOutcome(
+ paths: Pick<Paths, "transcriptsDir">,
+ outcome: { challenge: true; url: string; line: string } | { challenge: false; url: string },
+): Promise<void> {
+ if (outcome.challenge) {
+ await noteServiceCookieSignal(
+ paths,
+ { service: ARCHIVE_TODAY_SERVICE, kind: "check-page", line: outcome.line.slice(0, 300) },
+ { url: outcome.url },
+ );
+ return;
+ }
+ const state = await readServiceCookieState(paths).catch(() => null);
+ const e = state?.services[ARCHIVE_TODAY_SERVICE];
+ const g = state?.lastGood[ARCHIVE_TODAY_SERVICE];
+ if (!(e && !e.clearedAt) && g && Date.now() - Date.parse(g.at) < 10 * 60_000) return;
+ const line = await noteServiceCookieClean(paths, ARCHIVE_TODAY_SERVICE, { url: outcome.url });
+ if (line) currentJobContext()?.onLog(line);
+}
+
+// The operator's Dismiss: the alert is cleared as if a clean request had come
+// back. Answers whether there was one to dismiss.
+export async function dismissServiceCookieAlert(
+ paths: Pick<Paths, "transcriptsDir">,
+ service: string,
+ now: number = Date.now(),
+): Promise<boolean> {
+ return mutate(
+ paths,
+ (state, at) => {
+ const e = state.services[service];
+ if (!e) return { changed: false, out: false };
+ const effect = applyServiceCookieClean(state, service, at, "dismiss");
+ return { changed: effect !== null, out: effect === "cleared" || effect === "pending-dropped" };
+ },
+ now,
+ );
+}
+
+// "Re-run stopped jobs" was pressed: remembered so the offer goes away.
+export async function markServiceCookieRerun(
+ paths: Pick<Paths, "transcriptsDir">,
+ service: string,
+ jobIds: string[],
+ now: number = Date.now(),
+): Promise<void> {
+ await mutate(
+ paths,
+ (state, at) => {
+ const e = state.services[service];
+ if (!e) return { changed: false, out: undefined };
+ e.rerunAt = new Date(at).toISOString();
+ e.rerunJobIds = jobIds;
+ return { changed: true, out: undefined };
+ },
+ now,
+ );
+}
diff --git a/common/lib/serviceCookies.test.ts b/common/lib/serviceCookies.test.ts
@@ -0,0 +1,250 @@
+// Cookie refresh alerts (plans/cookie-refresh-alerts.md): the classifier on
+// real stderr (2026-10-21, Rumble's embed 403s that a fresh cf_clearance
+// cleared), the two-videos-in-a-row rule, clearing, coercion, the view.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/serviceCookies.test.ts
+
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import {
+ CLEARED_KEEP_MS,
+ OK_AGAIN_SHOW_MS,
+ PENDING_SIGNAL_TTL_MS,
+ applyServiceCookieClean,
+ applyServiceCookieSignal,
+ buildServiceCookieAlerts,
+ coerceServiceCookieState,
+ emptyServiceCookieState,
+ forumServiceKey,
+ isAlertRaised,
+ isServiceKey,
+ noteLastGood,
+ pruneServiceCookieState,
+ serviceCookieSignalFromStderr,
+ serviceFamily,
+ serviceFixText,
+ serviceStoppedLine,
+} from "./serviceCookies";
+import { classifyDownloadFailure } from "./availability";
+
+const FIX = path.join(path.dirname(fileURLToPath(import.meta.url)), "__fixtures__");
+const DOWNLOAD_LOG = readFileSync(path.join(FIX, "rumble-embed-403.download.log"), "utf8");
+const WINDOWS_LOG = readFileSync(path.join(FIX, "rumble-fetch-windows-stopped.log"), "utf8");
+
+// The fetch-windows log, one yt-dlp run per `$ yt-dlp` block.
+function runsOf(log: string): string[] {
+ return log
+ .split(/^\$ yt-dlp /m)
+ .slice(1)
+ .map((b) => b.split("\n").slice(1).join("\n"));
+}
+
+const T0 = Date.parse("2026-10-21T17:02:00.000Z");
+
+test("the real Rumble embed 403 is a rumble embed-403 signal naming the embed id", () => {
+ const sig = serviceCookieSignalFromStderr(DOWNLOAD_LOG, "rumble");
+ assert.ok(sig);
+ assert.equal(sig.service, "rumble");
+ assert.equal(sig.kind, "embed-403");
+ assert.equal(sig.videoId, "v7ez8hg");
+ assert.match(sig.line, /^ERROR: \[RumbleEmbed\] v7ez8hg: Unable to download JSON metadata: HTTP Error 403/);
+ // What it was before this feature: a bare network failure.
+ assert.equal(classifyDownloadFailure(DOWNLOAD_LOG, "error"), "network");
+});
+
+test("the fetch-windows log: two windows fetched, then two DIFFERENT videos' embeds 403 — the second raises the alert", () => {
+ const runs = runsOf(WINDOWS_LOG);
+ assert.equal(runs.length, 3);
+ const sigs = runs.map((r) => serviceCookieSignalFromStderr(r, "rumble"));
+ assert.equal(sigs[0], null, "a fetched window is no signal");
+ assert.deepEqual(
+ sigs.slice(1).map((s) => [s?.service, s?.kind, s?.videoId]),
+ [
+ ["rumble", "embed-403", "v7d7myw"],
+ ["rumble", "embed-403", "v7d2lxe"],
+ ],
+ );
+ const state = emptyServiceCookieState();
+ const first = applyServiceCookieSignal(state, sigs[1]!, { jobId: "J1", jobKind: "fetch-windows" }, T0);
+ assert.equal(first.raisedNow, false, "one embed 403 is not enough — a removed video answers 403 too");
+ assert.equal(isAlertRaised(state.services.rumble), false);
+ const second = applyServiceCookieSignal(state, sigs[2]!, { jobId: "J1", jobKind: "fetch-windows" }, T0 + 141_000);
+ assert.equal(second.raisedNow, true);
+ assert.equal(isAlertRaised(state.services.rumble), true);
+ assert.deepEqual(state.services.rumble.videos, ["v7d7myw", "v7d2lxe"]);
+ assert.deepEqual(state.services.rumble.jobs, [{ id: "J1", kind: "fetch-windows" }]);
+});
+
+test("the same video refused twice (prefetch, then the download) stays one video: no alert", () => {
+ const state = emptyServiceCookieState();
+ const sig = serviceCookieSignalFromStderr(DOWNLOAD_LOG, "rumble")!;
+ applyServiceCookieSignal(state, sig, {}, T0);
+ const again = applyServiceCookieSignal(state, sig, {}, T0 + 8_000);
+ assert.equal(again.raisedNow, false);
+ assert.equal(state.services.rumble.count, 2);
+ assert.deepEqual(state.services.rumble.videos, ["v7ez8hg"]);
+});
+
+test("a removed Rumble page's 403 and a media 403 are not cookie signals", () => {
+ assert.equal(
+ serviceCookieSignalFromStderr(
+ "ERROR: [Rumble] v7gone1: Unable to download webpage: HTTP Error 403: Forbidden (caused by <HTTPError 403: Forbidden>)",
+ "rumble",
+ ),
+ null,
+ );
+ assert.equal(serviceCookieSignalFromStderr("ERROR: [download] Got error: HTTP Error 403: Forbidden", "rumble"), null);
+ assert.equal(serviceCookieSignalFromStderr("", "rumble"), null);
+});
+
+test("a clean Rumble request between two embed 403s breaks the streak", () => {
+ const state = emptyServiceCookieState();
+ applyServiceCookieSignal(state, { service: "rumble", kind: "embed-403", line: "a", videoId: "v1" }, {}, T0);
+ assert.equal(applyServiceCookieClean(state, "rumble", T0 + 1000), "pending-dropped");
+ const r = applyServiceCookieSignal(state, { service: "rumble", kind: "embed-403", line: "b", videoId: "v2" }, {}, T0 + 2000);
+ assert.equal(r.raisedNow, false);
+});
+
+test("a pending first 403 older than an hour is forgotten", () => {
+ const state = emptyServiceCookieState();
+ applyServiceCookieSignal(state, { service: "rumble", kind: "embed-403", line: "a", videoId: "v1" }, {}, T0);
+ const r = applyServiceCookieSignal(
+ state,
+ { service: "rumble", kind: "embed-403", line: "b", videoId: "v2" },
+ {},
+ T0 + PENDING_SIGNAL_TTL_MS + 1,
+ );
+ assert.equal(r.raisedNow, false);
+ assert.deepEqual(state.services.rumble.videos, ["v2"]);
+});
+
+test("YouTube's bot check raises at once; its video id is read", () => {
+ const stderr =
+ "ERROR: [youtube] vid00000001: Sign in to confirm you’re not a bot. Use --cookies-from-browser or --cookies for the authentication.";
+ const sig = serviceCookieSignalFromStderr(stderr, "youtube");
+ assert.deepEqual([sig?.service, sig?.kind, sig?.videoId], ["youtube", "bot-check", "vid00000001"]);
+ const state = emptyServiceCookieState();
+ assert.equal(applyServiceCookieSignal(state, sig!, {}, T0).raisedNow, true);
+});
+
+test("Odysee: a 403 alone is not a signal; a 403 with Cloudflare's challenge words is (no real sample yet)", () => {
+ assert.equal(
+ serviceCookieSignalFromStderr("ERROR: [lbry] abc: Unable to download JSON metadata: HTTP Error 403: Forbidden", "odysee"),
+ null,
+ );
+ const sig = serviceCookieSignalFromStderr(
+ "ERROR: [lbry] abc: Unable to download webpage: HTTP Error 403: Forbidden\n<title>Just a moment...</title>",
+ "odysee",
+ );
+ assert.deepEqual([sig?.service, sig?.kind], ["odysee", "challenge"]);
+});
+
+test("clearing: a raised alert is cleared and kept a day; a second clean changes nothing; prune drops it after", () => {
+ const state = emptyServiceCookieState();
+ applyServiceCookieSignal(state, { service: "youtube", kind: "bot-check", line: "x" }, {}, T0);
+ assert.equal(applyServiceCookieClean(state, "youtube", T0 + 60_000, "recheck"), "cleared");
+ assert.equal(state.services.youtube.clearedBy, "recheck");
+ assert.equal(applyServiceCookieClean(state, "youtube", T0 + 120_000), null);
+ assert.equal(pruneServiceCookieState(state, T0 + 60_000 + CLEARED_KEEP_MS - 1), false);
+ assert.equal(pruneServiceCookieState(state, T0 + 60_000 + CLEARED_KEEP_MS + 1), true);
+ assert.equal(state.services.youtube, undefined);
+});
+
+test("a new signal after the clearing starts a fresh alert", () => {
+ const state = emptyServiceCookieState();
+ applyServiceCookieSignal(state, { service: "youtube", kind: "bot-check", line: "x" }, { jobId: "A" }, T0);
+ applyServiceCookieClean(state, "youtube", T0 + 1000);
+ const r = applyServiceCookieSignal(state, { service: "youtube", kind: "bot-check", line: "y" }, { jobId: "B" }, T0 + 2000);
+ assert.equal(r.raisedNow, true);
+ assert.equal(state.services.youtube.clearedAt, undefined);
+ assert.deepEqual(state.services.youtube.jobs.map((j) => j.id), ["B"]);
+});
+
+test("lastGood is refreshed at most every ten minutes", () => {
+ const state = emptyServiceCookieState();
+ assert.equal(noteLastGood(state, "rumble", { url: "https://rumble.com/a", channel: "c" }, T0), true);
+ assert.equal(noteLastGood(state, "rumble", { url: "https://rumble.com/b" }, T0 + 60_000), false);
+ assert.equal(noteLastGood(state, "rumble", { url: "https://rumble.com/b" }, T0 + 11 * 60_000), true);
+ assert.equal(state.lastGood.rumble.url, "https://rumble.com/b");
+});
+
+test("coerce: garbage is an empty state; bad entries are dropped, good ones kept", () => {
+ assert.deepEqual(coerceServiceCookieState(null), emptyServiceCookieState());
+ assert.deepEqual(coerceServiceCookieState("nope"), emptyServiceCookieState());
+ const s = coerceServiceCookieState({
+ services: {
+ rumble: { kind: "embed-403", since: "2026-10-21T17:02:00.000Z", count: 2, videos: ["a", 3, "b"], evidence: { line: "L", jobId: "J" }, raisedAt: "2026-10-21T17:04:00.000Z", jobs: [{ id: "J", kind: "fetch-windows" }, { nope: 1 }] },
+ "../../etc": { kind: "embed-403", since: "2026-10-21T17:02:00.000Z" },
+ youtube: { kind: "made-up", since: "2026-10-21T17:02:00.000Z" },
+ odysee: { kind: "challenge", since: "not a date" },
+ },
+ lastGood: { rumble: { url: "https://rumble.com/x", at: "2026-10-21T16:00:00.000Z" }, youtube: { url: 5 } },
+ });
+ assert.deepEqual(Object.keys(s.services), ["rumble"]);
+ assert.deepEqual(s.services.rumble.videos, ["a", "b"]);
+ assert.deepEqual(s.services.rumble.jobs, [{ id: "J", kind: "fetch-windows" }]);
+ assert.equal(s.services.rumble.lastSeen, "2026-10-21T17:02:00.000Z");
+ assert.deepEqual(Object.keys(s.lastGood), ["rumble"]);
+});
+
+test("service keys, families and the forum key", () => {
+ assert.equal(isServiceKey("rumble"), true);
+ assert.equal(isServiceKey("archive.today"), true);
+ assert.equal(isServiceKey("kiwifarms.st"), true);
+ assert.equal(isServiceKey("you tube/../x"), false);
+ assert.equal(isServiceKey("localhost"), false);
+ assert.equal(serviceFamily("odysee"), "ytdlp");
+ assert.equal(serviceFamily("archive.today"), "archive");
+ assert.equal(serviceFamily("kiwifarms.st"), "forum");
+ assert.equal(forumServiceKey("WWW.KiwiFarms.st"), "kiwifarms.st");
+});
+
+test("the fix names the configured browser; the job's stopped line says what and how", () => {
+ assert.match(serviceFixText("rumble", "firefox"), /^open rumble\.com in firefox/);
+ assert.match(serviceFixText("rumble", "chrome:Profile 1"), /in chrome /);
+ assert.match(serviceFixText("rumble"), /the browser yt-dlp reads cookies from/);
+ assert.equal(
+ serviceStoppedLine("rumble", "firefox"),
+ "stopped: Rumble cookies look stale — open rumble.com in firefox (a fresh Cloudflare clearance cookie), then Recheck on the dashboard.",
+ );
+ assert.match(serviceFixText("kiwifarms.st"), /Connect forum session/);
+ assert.match(serviceFixText("archive.today"), /Connect archive session/);
+});
+
+test("the view: a stale banner with its fix; OK again offers the stopped jobs, by status; a re-run hides the offer", () => {
+ const state = emptyServiceCookieState();
+ applyServiceCookieSignal(state, { service: "rumble", kind: "embed-403", line: "a", videoId: "v1" }, { jobId: "J1", jobKind: "fetch-windows", channel: "huck" }, T0);
+ applyServiceCookieSignal(state, { service: "rumble", kind: "embed-403", line: "b", videoId: "v2" }, { jobId: "J2", jobKind: "download-one", url: "https://rumble.com/v2" }, T0 + 60_000);
+ applyServiceCookieSignal(state, { service: "youtube", kind: "bot-check", line: "c" }, {}, T0);
+ const pendingOnly = emptyServiceCookieState();
+ applyServiceCookieSignal(pendingOnly, { service: "rumble", kind: "embed-403", line: "a", videoId: "v1" }, {}, T0);
+ assert.deepEqual(buildServiceCookieAlerts(pendingOnly, { now: T0 + 1000 }).alerts, []);
+ assert.equal(buildServiceCookieAlerts(pendingOnly, { now: T0 + 1000 }).pending.length, 1);
+
+ const statuses: Record<string, string> = { J1: "failed", J2: "done" };
+ let v = buildServiceCookieAlerts(state, { now: T0 + 120_000, browser: "firefox", statusOf: (id) => statuses[id] });
+ const rumble = v.alerts.find((a) => a.service === "rumble")!;
+ assert.equal(rumble.state, "stale");
+ assert.equal(rumble.headline, "Rumble needs fresh cookies: open rumble.com in firefox (a fresh Cloudflare clearance cookie)");
+ assert.match(rumble.detail, /^2 embed 403s on different videos since 17:02 UTC, job download-one J2/);
+ assert.equal(rumble.canRecheck, true);
+
+ applyServiceCookieClean(state, "rumble", T0 + 180_000, "recheck");
+ v = buildServiceCookieAlerts(state, { now: T0 + 240_000, statusOf: (id) => statuses[id] });
+ const ok = v.alerts.find((a) => a.service === "rumble")!;
+ assert.equal(ok.state, "ok-again");
+ assert.deepEqual(ok.stoppedJobs.map((j) => j.id), ["J1"], "a job that finished done was not stopped");
+ assert.equal(ok.headline, "Rumble cookies OK again — re-run the 1 job it stopped");
+ assert.equal(v.alerts[0].state, "stale", "stale banners come first");
+
+ // Still offered the next morning while there is a job to re-run...
+ assert.ok(buildServiceCookieAlerts(state, { now: T0 + 20 * 3600_000, statusOf: (id) => statuses[id] }).alerts.some((a) => a.service === "rumble"));
+ // ...and once re-run, shown only briefly after the clearing.
+ state.services.rumble.rerunAt = new Date(T0 + 200_000).toISOString();
+ state.services.rumble.rerunJobIds = ["J9"];
+ const after = buildServiceCookieAlerts(state, { now: T0 + 180_000 + OK_AGAIN_SHOW_MS + 1, statusOf: (id) => statuses[id] });
+ assert.equal(after.alerts.some((a) => a.service === "rumble"), false);
+});
diff --git a/common/lib/serviceCookies.ts b/common/lib/serviceCookies.ts
@@ -0,0 +1,548 @@
+// COOKIE REFRESH ALERTS (plans/cookie-refresh-alerts.md): one record per
+// SERVICE saying "the cookies this app reads for it look stale" — Rumble's
+// Cloudflare clearance, YouTube's sign-in, Odysee's Cloudflare check, a forum's
+// browser check (by host), archive.today's check page. The dashboard draws a
+// banner per stale service; the next clean request to it clears the alert by
+// itself.
+//
+// Client-safe: types, the signal classifier, the pure reducers and the
+// sentences. The file I/O is serviceCookies-server.ts.
+//
+// NAMING. "hold", "cooldown", `needsCookies` and a bare "session" are all
+// taken (plans/FACTS.md, "Naming hazards"): this is `serviceCookies`, a
+// "cookie refresh" alert, everywhere.
+//
+// THE RULE PER SIGNAL. A YouTube bot check, a Cloudflare challenge page and a
+// forum's or archive.today's check are not per-video: one is enough. Rumble's
+// embed 403 IS ambiguous — a removed Rumble video answers 403 too — so it takes
+// TWO DIFFERENT VIDEOS IN A ROW (no clean Rumble request between them) before
+// the alert is raised. A pending first 403 is forgotten after an hour, or the
+// moment Rumble answers cleanly.
+
+import { isBotCheck } from "./availability";
+
+export type ServiceCookieKind = "embed-403" | "bot-check" | "challenge" | "check-page";
+
+export const SERVICE_COOKIE_KINDS: readonly ServiceCookieKind[] = [
+ "embed-403",
+ "bot-check",
+ "challenge",
+ "check-page",
+];
+
+// The yt-dlp services: their requests go through yt-dlp with the browser
+// cookies `cookiesFromBrowser` names.
+export const YTDLP_COOKIE_SERVICES = ["rumble", "youtube", "odysee"] as const;
+export type YtdlpCookieService = (typeof YTDLP_COOKIE_SERVICES)[number];
+
+export const ARCHIVE_TODAY_SERVICE = "archive.today";
+
+export type ServiceFamily = "ytdlp" | "forum" | "archive";
+
+export function isYtdlpCookieService(s: string): s is YtdlpCookieService {
+ return (YTDLP_COOKIE_SERVICES as readonly string[]).includes(s);
+}
+
+// A service key: a yt-dlp service's name, "archive.today", or a forum's host
+// (lowercased, no www.). Anything else is not a service.
+export function isServiceKey(s: unknown): s is string {
+ if (typeof s !== "string" || s.length === 0 || s.length > 100) return false;
+ if (isYtdlpCookieService(s) || s === ARCHIVE_TODAY_SERVICE) return true;
+ return /^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(s);
+}
+
+export function serviceFamily(service: string): ServiceFamily {
+ if (isYtdlpCookieService(service)) return "ytdlp";
+ if (service === ARCHIVE_TODAY_SERVICE) return "archive";
+ return "forum";
+}
+
+// A forum host as its service key.
+export function forumServiceKey(host: string): string {
+ return host.trim().toLowerCase().replace(/^www\./, "");
+}
+
+export function serviceLabel(service: string): string {
+ switch (service) {
+ case "rumble":
+ return "Rumble";
+ case "youtube":
+ return "YouTube";
+ case "odysee":
+ return "Odysee";
+ case ARCHIVE_TODAY_SERVICE:
+ return "archive.today";
+ default:
+ return /(^|\.)kiwifarms\./.test(service) ? `Kiwi Farms (${service})` : service;
+ }
+}
+
+// What the operator does about it, as one clause ("open rumble.com in
+// firefox"). `browser` is the configured `cookiesFromBrowser` spec — what
+// yt-dlp reads the cookies from — when there is one.
+export function serviceFixText(service: string, browser?: string): string {
+ const b = browserName(browser);
+ switch (service) {
+ case "rumble":
+ return `open rumble.com in ${b} (a fresh Cloudflare clearance cookie)`;
+ case "youtube":
+ return `open youtube.com in ${b} and make sure it is signed in`;
+ case "odysee":
+ return `open odysee.com in ${b} and let its check pass`;
+ case ARCHIVE_TODAY_SERVICE:
+ return "Connect archive session (Settings → Archive sources) and pass the check once in the window";
+ default:
+ return `use “Connect forum session” on the thread's channel page and clear the check in the window`;
+ }
+}
+
+function browserName(spec: string | undefined): string {
+ const s = spec?.trim() ?? "";
+ if (!s) return "the browser yt-dlp reads cookies from (Settings → cookies)";
+ if (s.startsWith("file:")) return `a browser, then export a fresh cookies file to ${s.slice(5).trim()}`;
+ // "firefox", "chrome:Profile 1", "firefox::container" — the browser's name.
+ return s.split(/[:+]/)[0] || s;
+}
+
+// The line a job's log carries when it meets a stale service.
+export function serviceStoppedLine(service: string, browser?: string): string {
+ return `stopped: ${serviceLabel(service)} cookies look stale — ${serviceFixText(service, browser)}, then Recheck on the dashboard.`;
+}
+
+// ── the signal ────────────────────────────────────────────────────────────
+
+export type ServiceCookieSignal = {
+ service: string;
+ kind: ServiceCookieKind;
+ // The stderr line that showed it (trimmed, at most 300 characters).
+ line: string;
+ // The video the request was for, when the line names one (Rumble's embed
+ // id; YouTube's video id).
+ videoId?: string;
+};
+
+// [RumbleEmbed] v7d7myw: Unable to download JSON metadata: HTTP Error 403: Forbidden
+const RUMBLE_EMBED_403 = /\[RumbleEmbed\]\s+([A-Za-z0-9_-]+):\s*Unable to download[^\n]*HTTP Error 403/;
+const YOUTUBE_BOT_ID = /\[youtube\]\s+([A-Za-z0-9_-]{11}):[^\n]*confirm you['’]?re not a bot/i;
+// Odysee (yt-dlp's `lbry` extractor) behind Cloudflare. NO REAL SAMPLE EXISTS
+// YET (2026-10-21): the hook asks for a 403 on an lbry/odysee line AND
+// Cloudflare's challenge words somewhere in the output, which a removed claim
+// never carries. Widen it when a real one is seen.
+const ODYSEE_403 = /\[(?:lbry|odysee)[^\]]*\][^\n]*HTTP Error 403/i;
+const CLOUDFLARE_CHALLENGE = /just a moment|cloudflare|cf[-_]mitigated|cf[-_]chl|anti-bot challenge/i;
+
+function lineOf(stderr: string, re: RegExp): string {
+ for (const l of stderr.split("\n")) if (re.test(l)) return l.trim().slice(0, 300);
+ return stderr.trim().split("\n").slice(-1)[0]?.slice(0, 300) ?? "";
+}
+
+// The cookie signal in one yt-dlp run's stderr, or null. `platform` is the
+// service the request's URL is on, when known (detectPlatform).
+export function serviceCookieSignalFromStderr(
+ stderr: string,
+ platform?: string | null,
+): ServiceCookieSignal | null {
+ if (!stderr) return null;
+ const rumble = RUMBLE_EMBED_403.exec(stderr);
+ if (rumble) {
+ return { service: "rumble", kind: "embed-403", line: lineOf(stderr, RUMBLE_EMBED_403), videoId: rumble[1] };
+ }
+ if (isBotCheck(stderr) && (platform == null || platform === "youtube" || /\[youtube/i.test(stderr))) {
+ const id = YOUTUBE_BOT_ID.exec(stderr)?.[1];
+ return {
+ service: "youtube",
+ kind: "bot-check",
+ line: lineOf(stderr, /confirm you['’]?re not a bot/i),
+ ...(id ? { videoId: id } : {}),
+ };
+ }
+ const odyseeLine = ODYSEE_403.test(stderr) || (platform === "odysee" && /HTTP Error 403/i.test(stderr));
+ if (odyseeLine && CLOUDFLARE_CHALLENGE.test(stderr)) {
+ return { service: "odysee", kind: "challenge", line: lineOf(stderr, /HTTP Error 403/i) };
+ }
+ return null;
+}
+
+// ── the state ─────────────────────────────────────────────────────────────
+
+export type ServiceCookieJobRef = { id: string; kind?: string };
+
+export type ServiceCookieEvidence = {
+ jobId?: string;
+ channel?: string;
+ videoId?: string;
+ // The request's URL (a video page, a forum thread page, a copy).
+ url?: string;
+ line: string;
+};
+
+export type ServiceCookieEntry = {
+ service: string;
+ kind: ServiceCookieKind;
+ since: string;
+ lastSeen: string;
+ count: number;
+ evidence: ServiceCookieEvidence;
+ // The distinct videos the signal was seen on (Rumble's two-in-a-row rule).
+ videos: string[];
+ // Set once the rule is met: from then on the alert shows.
+ raisedAt?: string;
+ // The jobs that met the signal (the ones it stopped, when they failed).
+ jobs: ServiceCookieJobRef[];
+ clearedAt?: string;
+ clearedBy?: "clean" | "recheck" | "dismiss" | "connect";
+ // "Re-run stopped jobs" was pressed: when, and the jobs it started.
+ rerunAt?: string;
+ rerunJobIds?: string[];
+};
+
+// The last clean request per service — what Recheck asks again.
+export type ServiceCookieLastGood = { url: string; channel?: string; at: string };
+
+export type ServiceCookieState = {
+ version: 1;
+ services: Record<string, ServiceCookieEntry>;
+ lastGood: Record<string, ServiceCookieLastGood>;
+};
+
+export const PENDING_SIGNAL_TTL_MS = 60 * 60_000;
+export const CLEARED_KEEP_MS = 24 * 60 * 60_000;
+// An "OK again" with no job to re-run is shown this long after the clearing.
+export const OK_AGAIN_SHOW_MS = 15 * 60_000;
+// lastGood is refreshed at most this often (a write per clean request would
+// be a write per download).
+export const LAST_GOOD_REFRESH_MS = 10 * 60_000;
+const MAX_VIDEOS = 10;
+const MAX_JOBS = 20;
+
+export function emptyServiceCookieState(): ServiceCookieState {
+ return { version: 1, services: {}, lastGood: {} };
+}
+
+// How many distinct videos (or signals) raise the alert.
+export function signalsToRaise(kind: ServiceCookieKind): number {
+ return kind === "embed-403" ? 2 : 1;
+}
+
+function str(v: unknown, max = 2000): string | undefined {
+ return typeof v === "string" && v.length > 0 ? v.slice(0, max) : undefined;
+}
+
+function iso(v: unknown): string | undefined {
+ return typeof v === "string" && Number.isFinite(Date.parse(v)) ? v : undefined;
+}
+
+// COERCE-TOLERANT: whatever is on disk becomes a valid state; an entry that
+// cannot be read is dropped, never thrown on.
+export function coerceServiceCookieState(raw: unknown): ServiceCookieState {
+ const out = emptyServiceCookieState();
+ if (!raw || typeof raw !== "object") return out;
+ const r = raw as Record<string, unknown>;
+ const services = r.services && typeof r.services === "object" ? (r.services as Record<string, unknown>) : {};
+ for (const [key, v] of Object.entries(services)) {
+ if (!isServiceKey(key) || !v || typeof v !== "object") continue;
+ const e = v as Record<string, unknown>;
+ const kind = SERVICE_COOKIE_KINDS.includes(e.kind as ServiceCookieKind) ? (e.kind as ServiceCookieKind) : null;
+ const since = iso(e.since);
+ const lastSeen = iso(e.lastSeen) ?? since;
+ if (!kind || !since || !lastSeen) continue;
+ const ev = e.evidence && typeof e.evidence === "object" ? (e.evidence as Record<string, unknown>) : {};
+ const evidence: ServiceCookieEvidence = { line: str(ev.line, 300) ?? "" };
+ for (const k of ["jobId", "channel", "videoId", "url"] as const) {
+ const s = str(ev[k]);
+ if (s) evidence[k] = s;
+ }
+ const entry: ServiceCookieEntry = {
+ service: key,
+ kind,
+ since,
+ lastSeen,
+ count: typeof e.count === "number" && e.count > 0 ? Math.floor(e.count) : 1,
+ evidence,
+ videos: Array.isArray(e.videos) ? e.videos.filter((x): x is string => typeof x === "string").slice(-MAX_VIDEOS) : [],
+ jobs: Array.isArray(e.jobs)
+ ? e.jobs
+ .filter((j): j is { id: string; kind?: unknown } => !!j && typeof (j as { id?: unknown }).id === "string")
+ .map((j) => ({ id: j.id, ...(typeof j.kind === "string" ? { kind: j.kind } : {}) }))
+ .slice(-MAX_JOBS)
+ : [],
+ };
+ const raisedAt = iso(e.raisedAt);
+ if (raisedAt) entry.raisedAt = raisedAt;
+ const clearedAt = iso(e.clearedAt);
+ if (clearedAt) {
+ entry.clearedAt = clearedAt;
+ const by = e.clearedBy;
+ entry.clearedBy = by === "recheck" || by === "dismiss" || by === "connect" ? by : "clean";
+ }
+ const rerunAt = iso(e.rerunAt);
+ if (rerunAt) {
+ entry.rerunAt = rerunAt;
+ entry.rerunJobIds = Array.isArray(e.rerunJobIds)
+ ? e.rerunJobIds.filter((x): x is string => typeof x === "string")
+ : [];
+ }
+ out.services[key] = entry;
+ }
+ const lastGood = r.lastGood && typeof r.lastGood === "object" ? (r.lastGood as Record<string, unknown>) : {};
+ for (const [key, v] of Object.entries(lastGood)) {
+ if (!isServiceKey(key) || !v || typeof v !== "object") continue;
+ const g = v as Record<string, unknown>;
+ const url = str(g.url);
+ const at = iso(g.at);
+ if (!url || !at) continue;
+ const channel = str(g.channel, 200);
+ out.lastGood[key] = { url, at, ...(channel ? { channel } : {}) };
+ }
+ return out;
+}
+
+export function isAlertRaised(e: ServiceCookieEntry | undefined): boolean {
+ return !!e?.raisedAt && !e.clearedAt;
+}
+
+export type SignalContext = {
+ jobId?: string;
+ jobKind?: string;
+ channel?: string;
+ url?: string;
+};
+
+// A signal seen. Mutates `state`; answers the entry and whether THIS signal
+// raised the alert (the rule was met just now).
+export function applyServiceCookieSignal(
+ state: ServiceCookieState,
+ signal: ServiceCookieSignal,
+ ctx: SignalContext,
+ now: number,
+): { entry: ServiceCookieEntry; raisedNow: boolean } {
+ const at = new Date(now).toISOString();
+ let entry = state.services[signal.service];
+ const stalePending =
+ entry && !entry.raisedAt && now - Date.parse(entry.lastSeen) > PENDING_SIGNAL_TTL_MS;
+ // A cleared alert is replaced by the new trouble; so is a pending one gone
+ // stale, and one of another kind that never raised.
+ if (!entry || entry.clearedAt || stalePending || (!entry.raisedAt && entry.kind !== signal.kind)) {
+ entry = {
+ service: signal.service,
+ kind: signal.kind,
+ since: at,
+ lastSeen: at,
+ count: 0,
+ evidence: { line: signal.line },
+ videos: [],
+ jobs: [],
+ };
+ state.services[signal.service] = entry;
+ }
+ entry.count += 1;
+ entry.lastSeen = at;
+ entry.evidence = {
+ line: signal.line,
+ ...(ctx.jobId ? { jobId: ctx.jobId } : {}),
+ ...(ctx.channel ? { channel: ctx.channel } : {}),
+ ...(signal.videoId ? { videoId: signal.videoId } : {}),
+ ...(ctx.url ? { url: ctx.url } : {}),
+ };
+ if (signal.videoId && !entry.videos.includes(signal.videoId)) {
+ entry.videos = [...entry.videos, signal.videoId].slice(-MAX_VIDEOS);
+ }
+ if (ctx.jobId && !entry.jobs.some((j) => j.id === ctx.jobId)) {
+ entry.jobs = [...entry.jobs, { id: ctx.jobId, ...(ctx.jobKind ? { kind: ctx.jobKind } : {}) }].slice(-MAX_JOBS);
+ }
+ let raisedNow = false;
+ if (!entry.raisedAt) {
+ const need = signalsToRaise(entry.kind);
+ const seen = entry.kind === "embed-403" ? entry.videos.length : entry.count;
+ if (seen >= need) {
+ entry.raisedAt = at;
+ raisedNow = true;
+ }
+ }
+ return { entry, raisedNow };
+}
+
+export type CleanEffect = "cleared" | "pending-dropped" | null;
+
+// A clean answer from the service (or a Recheck that came back clean, or the
+// operator's Dismiss, or a Connect that cleared the check). A raised alert is
+// CLEARED (kept a day, for the "OK again — re-run" line); a pending first
+// signal is forgotten (the streak is broken). Mutates `state`.
+export function applyServiceCookieClean(
+ state: ServiceCookieState,
+ service: string,
+ now: number,
+ by: NonNullable<ServiceCookieEntry["clearedBy"]> = "clean",
+): CleanEffect {
+ const entry = state.services[service];
+ if (!entry) return null;
+ if (!entry.raisedAt) {
+ delete state.services[service];
+ return "pending-dropped";
+ }
+ if (entry.clearedAt) return null;
+ entry.clearedAt = new Date(now).toISOString();
+ entry.clearedBy = by;
+ return "cleared";
+}
+
+// Remember the last clean request (what Recheck asks again). Answers whether
+// the state changed — at most once per LAST_GOOD_REFRESH_MS per service.
+export function noteLastGood(
+ state: ServiceCookieState,
+ service: string,
+ good: { url: string; channel?: string },
+ now: number,
+): boolean {
+ const prev = state.lastGood[service];
+ if (prev && now - Date.parse(prev.at) < LAST_GOOD_REFRESH_MS) return false;
+ state.lastGood[service] = { url: good.url, at: new Date(now).toISOString(), ...(good.channel ? { channel: good.channel } : {}) };
+ return true;
+}
+
+// Cleared alerts older than a day go. Answers whether anything was removed.
+export function pruneServiceCookieState(state: ServiceCookieState, now: number): boolean {
+ let changed = false;
+ for (const [k, e] of Object.entries(state.services)) {
+ const gone =
+ (e.clearedAt && now - Date.parse(e.clearedAt) > CLEARED_KEEP_MS) ||
+ (!e.raisedAt && now - Date.parse(e.lastSeen) > PENDING_SIGNAL_TTL_MS);
+ if (gone) {
+ delete state.services[k];
+ changed = true;
+ }
+ }
+ return changed;
+}
+
+// ── the view ──────────────────────────────────────────────────────────────
+
+export type ServiceCookieJobView = {
+ id: string;
+ kind?: string;
+ // The job's status as the registry or its sidecar says, when known.
+ status?: string;
+};
+
+export type ServiceCookieAlertView = {
+ service: string;
+ label: string;
+ family: ServiceFamily;
+ state: "stale" | "ok-again";
+ kind: ServiceCookieKind;
+ since: string;
+ raisedAt: string;
+ lastSeen: string;
+ count: number;
+ videos: string[];
+ evidence: ServiceCookieEvidence;
+ fix: string;
+ // The headline: "Rumble needs fresh cookies: …" / "Rumble cookies OK again".
+ headline: string;
+ detail: string;
+ clearedAt?: string;
+ clearedBy?: ServiceCookieEntry["clearedBy"];
+ // Recheck has something to ask (a last-good request, the evidence URL, or
+ // archive.today's session).
+ canRecheck: boolean;
+ // The jobs the alert stopped (failed or cancelled), not yet re-run.
+ stoppedJobs: ServiceCookieJobView[];
+ rerunAt?: string;
+ rerunJobIds?: string[];
+};
+
+export type ServiceCookieAlertsPayload = {
+ alerts: ServiceCookieAlertView[];
+ // Services with a first signal waiting for a second (not shown as a banner).
+ pending: { service: string; label: string; kind: ServiceCookieKind; videos: string[]; lastSeen: string }[];
+};
+
+const STOPPED_STATUSES = new Set(["failed", "cancelled"]);
+
+function hhmm(isoText: string): string {
+ return isoText.slice(11, 16);
+}
+
+function kindPhrase(kind: ServiceCookieKind, count: number, videos: number): string {
+ switch (kind) {
+ case "embed-403":
+ return `${videos} embed 403${videos === 1 ? "" : "s"} on different videos`;
+ case "bot-check":
+ return `${count} bot check${count === 1 ? "" : "s"}`;
+ case "challenge":
+ return `${count} challenge page${count === 1 ? "" : "s"}`;
+ case "check-page":
+ return `${count} check page${count === 1 ? "" : "s"}`;
+ }
+}
+
+// The dashboard's payload from the state and each job's status (`statusOf`
+// answers the registry's or the sidecar's; undefined when unknown).
+export function buildServiceCookieAlerts(
+ state: ServiceCookieState,
+ opts: {
+ now: number;
+ browser?: string;
+ statusOf?: (jobId: string) => string | undefined;
+ },
+): ServiceCookieAlertsPayload {
+ const alerts: ServiceCookieAlertView[] = [];
+ const pending: ServiceCookieAlertsPayload["pending"] = [];
+ for (const e of Object.values(state.services)) {
+ const label = serviceLabel(e.service);
+ if (!e.raisedAt) {
+ if (opts.now - Date.parse(e.lastSeen) <= PENDING_SIGNAL_TTL_MS) {
+ pending.push({ service: e.service, label, kind: e.kind, videos: e.videos, lastSeen: e.lastSeen });
+ }
+ continue;
+ }
+ if (e.clearedAt && opts.now - Date.parse(e.clearedAt) > CLEARED_KEEP_MS) continue;
+ const fix = serviceFixText(e.service, opts.browser);
+ const jobs = e.jobs.map((j) => {
+ const status = opts.statusOf?.(j.id);
+ return { ...j, ...(status ? { status } : {}) };
+ });
+ const stoppedJobs = e.rerunAt ? [] : jobs.filter((j) => j.status && STOPPED_STATUSES.has(j.status));
+ // "OK again" stays up for the day only while it has jobs to re-run;
+ // otherwise for a short while, so the clearing is seen.
+ if (e.clearedAt && stoppedJobs.length === 0 && opts.now - Date.parse(e.clearedAt) > OK_AGAIN_SHOW_MS) continue;
+ const what = kindPhrase(e.kind, e.count, e.videos.length);
+ const job = e.evidence.jobId ? jobs.find((j) => j.id === e.evidence.jobId) : undefined;
+ const detail =
+ `${what} since ${hhmm(e.since)} UTC` +
+ (job ? `, job ${job.kind ? `${job.kind} ` : ""}${job.id}` : "") +
+ (e.evidence.channel ? `, ${e.evidence.channel}` : "");
+ const stale = !e.clearedAt;
+ const n = stoppedJobs.length;
+ alerts.push({
+ service: e.service,
+ label,
+ family: serviceFamily(e.service),
+ state: stale ? "stale" : "ok-again",
+ kind: e.kind,
+ since: e.since,
+ raisedAt: e.raisedAt,
+ lastSeen: e.lastSeen,
+ count: e.count,
+ videos: e.videos,
+ evidence: e.evidence,
+ fix,
+ headline: stale
+ ? `${label} needs fresh cookies: ${fix}`
+ : `${label} cookies OK again` + (n > 0 ? ` — re-run the ${n} job${n === 1 ? "" : "s"} it stopped` : ""),
+ detail,
+ ...(e.clearedAt ? { clearedAt: e.clearedAt, clearedBy: e.clearedBy } : {}),
+ canRecheck:
+ serviceFamily(e.service) === "archive" ||
+ !!state.lastGood[e.service] ||
+ !!e.evidence.url,
+ stoppedJobs,
+ ...(e.rerunAt ? { rerunAt: e.rerunAt, rerunJobIds: e.rerunJobIds ?? [] } : {}),
+ });
+ }
+ // Stale first, then newest.
+ alerts.sort((a, b) =>
+ a.state !== b.state ? (a.state === "stale" ? -1 : 1) : b.lastSeen.localeCompare(a.lastSeen),
+ );
+ return { alerts, pending };
+}
diff --git a/common/views/names.ts b/common/views/names.ts
@@ -26,6 +26,7 @@ export const VIEW_NAMES = [
"widgetSync",
"widgetActionable",
"cleanable",
+ "cookieAlerts",
] as const;
export type ViewName = (typeof VIEW_NAMES)[number];
@@ -52,4 +53,5 @@ export const VIEW_CONTRACT: Record<ViewName, "observe" | "construct"> = {
widgetSync: "construct",
widgetActionable: "construct",
cleanable: "construct",
+ cookieAlerts: "construct",
};
diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts
@@ -516,7 +516,13 @@ function runOneYtdlp(
args: string[],
): Promise<AttemptOutcome> {
return runOneYtdlpRaw(
- { ytdlpBin: opts.paths.ytdlpBin, onLog: opts.onLog, signal: opts.signal },
+ {
+ ytdlpBin: opts.paths.ytdlpBin,
+ onLog: opts.onLog,
+ signal: opts.signal,
+ // Cookie refresh alerts: the service's answer is observed.
+ observe: { paths: opts.paths, url: opts.videoUrl, channel: opts.channelSlug },
+ },
cwd,
args,
);
diff --git a/common/ytdlp/fetchCopyManaged.ts b/common/ytdlp/fetchCopyManaged.ts
@@ -128,7 +128,12 @@ export async function fetchCopyManaged(opts: FetchCopyOpts): Promise<FetchCopyRe
await clearScratch(videoDir);
const args = fetchCopyArgs(videoDir, opts.copy, fmt);
const outcome = await runOneYtdlp(
- { ytdlpBin: opts.paths.ytdlpBin, onLog: opts.onLog, signal: opts.signal },
+ {
+ ytdlpBin: opts.paths.ytdlpBin,
+ onLog: opts.onLog,
+ signal: opts.signal,
+ observe: { paths: opts.paths, url: opts.copy.url },
+ },
videoDir,
args,
);
diff --git a/common/ytdlp/fetchWindowManaged.ts b/common/ytdlp/fetchWindowManaged.ts
@@ -501,6 +501,13 @@ async function fetchWindowOnce(opts: FetchWindowOpts, attempt: number): Promise<
ytdlpBin: opts.paths.ytdlpBin,
onLog: opts.onLog,
signal: opts.signal,
+ // Cookie refresh alerts: the service's answer is observed (the
+ // page's; a copy's URL is another service's request).
+ observe: {
+ paths: opts.paths,
+ url: opts.provenance.copy?.url ?? opts.videoUrl,
+ channel: opts.channelSlug,
+ },
},
opts.cwd ?? videoDir,
argsWith(cookies, retryArgs),
diff --git a/common/ytdlp/metadataScan.ts b/common/ytdlp/metadataScan.ts
@@ -33,6 +33,7 @@ import {
} from "../lib/cookiePolicy";
import { channelExtraArgs, pacingPlatformKey } from "./channelArgs";
import { recordPlatformClean } from "../jobs/downloadBackoff";
+import { noteServiceCookieClean, observeStderrServiceSignal } from "../lib/serviceCookies-server";
import type { Paths } from "../lib/paths";
import { getSettings } from "../lib/settings";
import { extractVideoId } from "../lib/videoId";
@@ -684,6 +685,12 @@ export async function runMetadataScan(
`${scannedTotal} video(s) were read and saved; the rest stay unscanned. A per-platform cooldown has been recorded — run the scan again once it lapses.\n`,
);
await opts.onPlatformBackoff?.("rate_limit");
+ // A bot check is the service's cookies, not only a pace: the cookie
+ // refresh alert (lib/serviceCookies.ts) says so on the dashboard.
+ await observeStderrServiceSignal(paths, stoppedMessage ?? "", {
+ platform: pacingPlatformKey(channelConfig),
+ channel: slug,
+ });
} else if (stopped === undefined && scannedTotal > 0 && !opts.signal.aborted) {
// A scan the source answered cleanly settles the platform like a clean
// probe — its backoff and any hold clear (release 17 review H2).
@@ -693,6 +700,9 @@ export async function runMetadataScan(
} catch {
/* shared-state write is best-effort */
}
+ // ... and a cookie refresh alert on it clears.
+ const cookieLine = await noteServiceCookieClean(paths, pacingPlatformKey(channelConfig));
+ if (cookieLine) opts.onLog(cookieLine);
}
const errorCount = Object.keys(errors).length;
diff --git a/common/ytdlp/runOneYtdlp.ts b/common/ytdlp/runOneYtdlp.ts
@@ -10,6 +10,8 @@
// log sink and an abort signal. That is the whole reason it lifts cleanly.
import { execa } from "execa";
+import type { Paths } from "../lib/paths";
+import { observeYtdlpServiceOutcome } from "../lib/serviceCookies-server";
export const STDERR_TAIL_BYTES = 64 * 1024;
@@ -29,6 +31,12 @@ export type YtdlpRunOpts = {
ytdlpBin: string;
onLog: (s: string) => void;
signal: AbortSignal;
+ // A yt-dlp request to a SERVICE (cookie refresh alerts,
+ // lib/serviceCookies-server.ts): its outcome is observed for the service
+ // the URL is on — a stale-cookie signal recorded, a clean answer clearing
+ // the service's alert. Absent (an ffmpeg run through this runner, a test) =
+ // nothing observed.
+ observe?: { paths: Pick<Paths, "transcriptsDir">; url: string; channel?: string };
};
export type AttemptOutcome = {
@@ -90,6 +98,15 @@ export async function runOneYtdlp(
const result = await child;
// Flush any final partial line.
scrape(stdoutBuf.trim());
+ if (opts.observe) {
+ await observeYtdlpServiceOutcome(opts.observe.paths, {
+ url: opts.observe.url,
+ ...(opts.observe.channel ? { channel: opts.observe.channel } : {}),
+ exitCode: result.exitCode ?? null,
+ stderrTail,
+ aborted: opts.signal.aborted,
+ });
+ }
return {
exitCode: result.exitCode ?? null,
stderrTail,
diff --git a/common/ytdlp/runYtdlp.ts b/common/ytdlp/runYtdlp.ts
@@ -85,6 +85,7 @@ import { hasSubtitleRateLimit } from "../lib/availability";
import { computeKeepWindow, type KeepWindow } from "../controller/keptVideos";
import { downloadOneManaged } from "./downloadOneManaged";
import { STDERR_TAIL_BYTES } from "./runOneYtdlp";
+import { observeStderrServiceSignal } from "../lib/serviceCookies-server";
import {
resolveDownloadFormatPreset,
resolveDownloadFormatSelector,
@@ -546,6 +547,12 @@ async function enumeratePlaylistUrls(
!opts.signal.aborted
) {
const stderr = String(result.stderr ?? "");
+ // A bot check on the listing is the service's cookies (cookie refresh
+ // alerts, lib/serviceCookies.ts), whatever else it is.
+ await observeStderrServiceSignal(opts.paths, stderr, {
+ url: opts.channelConfig.url,
+ channel: opts.channelSlug,
+ });
if (classifyDownloadFailure(stderr, undefined) === "rate_limit") {
throw new EnumerationIncompleteError(
result.exitCode,
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,7 @@
# Changelog
## [Unreleased]
+- **The dashboard says when a service's cookies have gone stale, and what to do.** When Rumble refuses its embeds with a 403 on two different videos in a row (one is not enough — a removed video answers 403 too), when YouTube asks to confirm you're not a bot, when Odysee answers with Cloudflare's check, when a forum's browser check or login wall stops a thread, or when archive.today answers with its check page, a banner at the top of the dashboard says so — "Rumble needs fresh cookies: open rumble.com in firefox" — with the jobs it happened in. **Recheck** asks the service once, through the same path and cookies the jobs use, and clears the banner when it answers; the next clean request clears it by itself too, and **Dismiss** clears it by hand. Once it is clear the banner says "OK again" and offers **Re-run stopped jobs**, which retries the jobs it stopped. The stopped job's log ends with the cause and the fix, `archilyzer doctor` lists it under "service cookies", and a Connect forum session or Connect archive session that ends on a cleared page clears the matching banner. From a terminal: `pnpm ops get services`, `recheck-service`, `rerun-service-jobs` and `dismiss-service`. Odysee's check is recognised by Cloudflare's own words beside a 403; no real Odysee sample has been seen yet. Needs a restart of the editor.
- **archive.today copies are page records too, like Wayback captures.** The channel kind is now **Archived pages** on the New channel form (paste an archive.today copy's URL, `archive.ph/newest/<page>`, and the channel's target is that page on archive.today), and each target says where its copies are looked for: the Wayback Machine, archive.today, or both. The channel page's **Import a capture** takes an archive.today copy's URL (`archive.ph/<id>`, or any of its other names), or the page's own URL, a date and **on archive.today** for the copy nearest that date; the copy is kept as archive.today served it and read without its header bar, links back to the pages they pointed at, so a tweet, a Tumblr post or an article gives the same records it would from the Wayback Machine — each saying it came from archive.today and linking that copy, its images archive.today's own copies. archive.today is asked one request at a time, eight seconds apart; when it says "too many requests" the import stops with a sentence and nothing more is asked of it for half an hour. When it answers with a CAPTCHA instead of the copy, the import is refused and never reads the CAPTCHA as a page: **Connect archive session** (on the channel page, and in Settings → Archive sources) opens a window on the editor's machine to pass the check once, and the next import reads through it; nothing is ever solved for you. **Look up a page** lists every copy each archive holds of a page, with an Import button on each. From a terminal: `pnpm ops import-page` takes `"source": "archive.today"`, `pnpm ops archive-lookup` lists the copies, and `pnpm archilyzer archive lookup <url>` runs without the editor. Needs a restart of the editor.
- **A page the Wayback Machine will not show says so.** When the Wayback Machine answers "forbidden" for one page while it answers others, that page is excluded from it, and Wayback lookups, page imports and archive lookups now say "excluded from the Wayback Machine (cause unknown)" instead of reporting an error.
- **Save an X search across accounts, and see who keeps saying it.** Paste an X search page's URL (as copied from X's search box) into the New channel form, or choose **X search** as the platform and type a query: it makes an X search channel whose records are the matching posts from any account. The query is X's own — OR, "quotes", -term, from:, to:, @name, url:, filter:, lang: — and its dates are the channel's **Since** and **Until** (a pasted URL's since:/until: are moved there; typed into the query they are refused with a sentence). Fetch posts searches backwards a window at a time (3 months, or your **Window**), newest first, at the older walk's pace and with its X login; a run cut short resumes where it stopped, later fetches search only the new days, and a new query starts afresh. The channel page's **Leads** lists the accounts by how many matching posts they made, with their first and last day and a sample: **Archive this account** creates `<handle>-x` on no site and starts its fetch, **Never archive** hides the account (Restore brings it back), and an account an X channel already archives says so. An X search channel is never put on a site. From a terminal: `pnpm ops create-channel` with the search URL, `pnpm ops fetch-posts`, `pnpm ops get channel <slug> --leads` and `pnpm ops x-search-lead`; the MCP has `x_search_leads`. Nothing calls a model. Needs a restart of the editor.
diff --git a/editor/app/api/ops/_writes.test.ts b/editor/app/api/ops/_writes.test.ts
@@ -98,6 +98,21 @@ test("clear-platform-hold refuses a name that is not a platform", async () => {
assert.equal(none.status, 400);
});
+test("the cookie alert's three writes refuse a name that is not a service; rerun refuses a service with no alert", async () => {
+ for (const name of ["recheck-service", "dismiss-service", "rerun-service-jobs"]) {
+ const res = await callPost(await route(name), { service: "you tube/../x" });
+ assert.equal(res.status, 400, name);
+ assert.match(String(res.body.error), /^Not a service: /, name);
+ const none = await callPost(await route(name), {});
+ assert.equal(none.status, 400, name);
+ const extra = await callPost(await route(name), { service: "rumble", platform: "rumble" });
+ assert.equal(extra.status, 400, name);
+ }
+ const rerun = await callPost(await route("rerun-service-jobs"), { service: "rumble" });
+ assert.equal(rerun.status, 400);
+ assert.match(String(rerun.body.error), /^Rumble has no cookie alert\./);
+});
+
test("workers: the op and the ids are checked at the door", async () => {
const workers = await route("workers");
const op = await callPost(workers, { op: "restart", ids: ["a"] });
diff --git a/editor/app/api/ops/dismiss-service/route.ts b/editor/app/api/ops/dismiss-service/route.ts
@@ -0,0 +1,17 @@
+import { NextResponse } from "next/server";
+import { dismissServiceCookiesAction } from "../../../operations/serviceCookiesActions";
+import { ops, opsFail, reqString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { service }
+//
+// The cookie refresh banner's Dismiss: the alert is cleared as if the service
+// had answered cleanly. Answers the sentence ({ ok, message }).
+export async function POST(request: Request) {
+ return ops(request, ["service"], async (body) => {
+ const res = await dismissServiceCookiesAction(reqString(body, "service"));
+ if (!res.ok) return opsFail(res.error);
+ return NextResponse.json({ ok: true, message: res.message });
+ });
+}
diff --git a/editor/app/api/ops/recheck-service/route.ts b/editor/app/api/ops/recheck-service/route.ts
@@ -0,0 +1,21 @@
+import { NextResponse } from "next/server";
+import { recheckServiceCookiesAction } from "../../../operations/serviceCookiesActions";
+import { ops, opsFail, reqString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { service: "rumble" | "youtube" | "odysee" | "archive.today" | <forum host> }
+//
+// The cookie refresh banner's Recheck: ONE request through the service's own
+// path (a yt-dlp metadata request for its last clean video; a forum page
+// through the host's profile; archive.today's request again), as a one-step
+// job (kind `recheck-service-cookies`) the answer waits for:
+// { ok, jobId, result: "clean" | "stale" | "failed", message }. "clean"
+// clears the alert.
+export async function POST(request: Request) {
+ return ops(request, ["service"], async (body) => {
+ const res = await recheckServiceCookiesAction(reqString(body, "service"));
+ if (!res.ok) return opsFail(res.error, 400, res.jobId ? { jobId: res.jobId } : {});
+ return NextResponse.json({ ok: true, jobId: res.jobId, result: res.result, message: res.message });
+ });
+}
diff --git a/editor/app/api/ops/rerun-service-jobs/route.ts b/editor/app/api/ops/rerun-service-jobs/route.ts
@@ -0,0 +1,19 @@
+import { NextResponse } from "next/server";
+import { rerunServiceStoppedJobsAction } from "../../../operations/serviceCookiesActions";
+import { ops, opsFail, reqString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { service }
+//
+// The "OK again" banner's Re-run stopped jobs: every job the service's cookie
+// alert stopped (failed or cancelled), retried from its replay descriptor
+// ahead of the queue, as /jobs' Retry. Refused while the cookies still look
+// stale. { ok, jobIds, skipped: [{id, error}], message }; --wait follows jobIds.
+export async function POST(request: Request) {
+ return ops(request, ["service"], async (body) => {
+ const res = await rerunServiceStoppedJobsAction(reqString(body, "service"));
+ if (!res.ok) return opsFail(res.error);
+ return NextResponse.json({ ok: true, jobIds: res.jobIds, skipped: res.skipped, message: res.message });
+ });
+}
diff --git a/editor/app/api/ops/services/route.ts b/editor/app/api/ops/services/route.ts
@@ -0,0 +1,15 @@
+import { loadCookieAlerts } from "../../../lib/cookieAlerts";
+import { readRoute } from "../_read";
+
+export const dynamic = "force-dynamic";
+
+// GET /api/ops/services
+//
+// The dashboard's cookie refresh alerts (`loadCookieAlerts`, the same payload
+// /api/view/cookieAlerts serves): each service whose cookies look stale
+// ("stale") or answered cleanly again within the day ("ok-again", with the
+// jobs the alert stopped), and the services with a first signal waiting for a
+// second (`pending` — Rumble's two-videos rule).
+export async function GET(request: Request) {
+ return readRoute(request, [], async () => ({ ...(await loadCookieAlerts()) }));
+}
diff --git a/editor/app/api/view/[name]/route.test.ts b/editor/app/api/view/[name]/route.test.ts
@@ -53,6 +53,10 @@ const PAIRS: Array<[string, string]> = [
["/api/widget/cleanable", "/api/view/cleanable"],
];
+// Views born after the consolidation: there is no old path to rewrite, so
+// they are served only at /api/view/<name>.
+const NEW_VIEWS = ["cookieAlerts"];
+
async function view(name: string): Promise<number> {
const res = await GET(new Request(`http://localhost/api/view/${name}`), {
params: Promise.resolve({ name }),
@@ -87,7 +91,7 @@ test("each old path is a rewrite to its view, and every view has one", async ()
}
assert.deepEqual(
[...VIEW_NAMES].sort(),
- PAIRS.map(([, v]) => v.slice("/api/view/".length)).sort(),
+ [...PAIRS.map(([, v]) => v.slice("/api/view/".length)), ...NEW_VIEWS].sort(),
);
});
diff --git a/editor/app/api/view/views.ts b/editor/app/api/view/views.ts
@@ -11,6 +11,7 @@ import { buildAutoQueueStatusPayload } from "../../operations/status";
import { buildSchedulerStatusPayload } from "../../scheduler/status";
import { widgetSyncInputs } from "../../widget/lib/syncInputs";
import { cleanableChannels } from "../../cleanup/lib/loadCleanup";
+import { loadCookieAlerts } from "../../lib/cookieAlerts";
import {
loadActionableSummary,
widgetActionableRows,
@@ -75,4 +76,9 @@ export const VIEWS: Record<ViewName, (req: Request) => Promise<Response>> = {
// snapshot read serving both, as before.
cleanable: async () =>
NextResponse.json(buildCleanablePayload(await cleanableChannels(getPaths()))),
+
+ // The dashboard's cookie refresh alerts: a service whose cookies look stale
+ // (or are OK again, with the jobs it stopped). One small file and each
+ // recorded job's status.
+ cookieAlerts: async () => NextResponse.json(await loadCookieAlerts(getPaths())),
};
diff --git a/editor/app/channels/[slug]/components/SocialChannelPanel.tsx b/editor/app/channels/[slug]/components/SocialChannelPanel.tsx
@@ -6,6 +6,7 @@
// Its only failure surfaces are "the fetch failed" and "we need credentials",
// which is exactly what the state sidecar records.
+import Link from "next/link";
import { useState, useTransition } from "react";
import {
checkPostAvailabilityAction,
@@ -411,6 +412,15 @@ export function SocialChannelPanel({
{forum
? "Needs the forum session: the forum showed a check (or a login) the headless browser could not get past. Use Connect forum session below, clear it in the window, close it, and fetch again."
: "Needs credentials: the fetcher could not authenticate. Configure cookies-from-browser for this channel (or globally) and re-run."}
+ {forum && (
+ <>
+ {" "}
+ <Link href="/" className="underline underline-offset-2">
+ The dashboard
+ </Link>{" "}
+ carries the forum's cookie alert, with Recheck.
+ </>
+ )}
</p>
)}
{state.lastError && (
diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts
@@ -71,6 +71,8 @@ import {
type ForumSessionStatus,
} from "yt-dlp-transcript-common/social/forumSession";
import { parseXenforoThreadUrl } from "yt-dlp-transcript-common/social/xenforoParse";
+import { noteServiceCookieClean } from "yt-dlp-transcript-common/lib/serviceCookies-server";
+import { forumServiceKey } from "yt-dlp-transcript-common/lib/serviceCookies";
// Switch which SocialFetcher drives this channel. The fetchers differ in what
// they can actually reach — for X, gallery-dl needs credentials for depth,
@@ -395,6 +397,11 @@ export async function connectForumSessionAction(
const record = await connectForumSession(getPaths(), ch.url, {
onLog: (line) => console.log(`[forum-session] ${line}`),
});
+ // A window that closed on the thread clears the forum's cookie refresh
+ // alert (the dashboard's banner).
+ if (record.cleared) {
+ await noteServiceCookieClean(getPaths(), forumServiceKey(ch.host), { url: ch.url, channel: slug }, { by: "connect" });
+ }
revalidatePath(`/channels/${slug}`);
return { ok: true, record };
} catch (e) {
diff --git a/editor/app/components/dashboard/CookieAlertsPanel.tsx b/editor/app/components/dashboard/CookieAlertsPanel.tsx
@@ -0,0 +1,133 @@
+"use client";
+
+// THE COOKIE REFRESH BANNERS (plans/cookie-refresh-alerts.md): one per service
+// whose cookies look stale — "Rumble needs fresh cookies: open rumble.com in
+// firefox" — with Recheck (one request through the service's own path) and
+// Dismiss; once the service answers cleanly again, "OK again" with Re-run for
+// the jobs it stopped. The dashboard's top slot, like the first-run checklist.
+
+import Link from "next/link";
+import { useState, useTransition } from "react";
+import type {
+ ServiceCookieAlertView,
+ ServiceCookieAlertsPayload,
+} from "yt-dlp-transcript-common/lib/serviceCookies";
+import {
+ dismissServiceCookiesAction,
+ recheckServiceCookiesAction,
+ rerunServiceStoppedJobsAction,
+} from "../../operations/serviceCookiesActions";
+
+const BUTTON =
+ "rounded-md border border-border bg-card px-2.5 py-1 text-xs hover:bg-muted disabled:opacity-50";
+
+function AlertCard({ alert, onChange }: { alert: ServiceCookieAlertView; onChange: () => void }) {
+ const [note, setNote] = useState<{ text: string; error: boolean } | null>(null);
+ const [pending, start] = useTransition();
+ const stale = alert.state === "stale";
+ const act = (fn: () => Promise<{ ok: boolean; message?: string; error?: string }>) =>
+ start(async () => {
+ setNote(null);
+ const r = await fn();
+ setNote(r.ok ? { text: r.message ?? "", error: false } : { text: r.error ?? "Failed.", error: true });
+ onChange();
+ });
+ const channel = alert.evidence.channel;
+ return (
+ <section
+ role="alert"
+ aria-label={`${alert.label} cookies`}
+ data-service={alert.service}
+ data-state={alert.state}
+ className={`rounded-md border bg-card px-4 py-3 ${stale ? "border-destructive/50" : "border-brand/40"}`}
+ >
+ <div className="flex flex-wrap items-start justify-between gap-3">
+ <div className="flex min-w-0 flex-col gap-1">
+ <p className={`text-sm font-medium ${stale ? "text-destructive" : "text-brand"}`}>{alert.headline}</p>
+ <p className="text-xs text-muted-foreground break-words">
+ {alert.detail}
+ {alert.family === "forum" && channel && (
+ <>
+ {" · "}
+ <Link href={`/channels/${channel}`} className="underline underline-offset-2 hover:text-foreground">
+ channel page
+ </Link>
+ </>
+ )}
+ {alert.family === "archive" && (
+ <>
+ {" · "}
+ <Link href="/settings" className="underline underline-offset-2 hover:text-foreground">
+ Settings
+ </Link>
+ </>
+ )}
+ </p>
+ {alert.evidence.line && (
+ <code className="block max-w-full truncate text-[11px] text-muted-foreground" title={alert.evidence.line}>
+ {alert.evidence.line}
+ </code>
+ )}
+ </div>
+ <div className="flex shrink-0 flex-wrap items-center gap-1.5">
+ {stale && alert.canRecheck && (
+ <button
+ type="button"
+ className={BUTTON}
+ disabled={pending}
+ onClick={() => act(() => recheckServiceCookiesAction(alert.service))}
+ >
+ {pending ? "Checking…" : "Recheck"}
+ </button>
+ )}
+ {!stale && alert.stoppedJobs.length > 0 && (
+ <button
+ type="button"
+ className={BUTTON}
+ disabled={pending}
+ onClick={() => act(() => rerunServiceStoppedJobsAction(alert.service))}
+ >
+ Re-run stopped jobs
+ </button>
+ )}
+ {stale && (
+ <button
+ type="button"
+ className={BUTTON}
+ disabled={pending}
+ onClick={() => act(() => dismissServiceCookiesAction(alert.service))}
+ >
+ Dismiss
+ </button>
+ )}
+ </div>
+ </div>
+ {note && (
+ <p
+ role="status"
+ aria-label={`${alert.label} cookies result`}
+ className={`mt-2 text-xs ${note.error ? "text-destructive" : "text-muted-foreground"}`}
+ >
+ {note.text}
+ </p>
+ )}
+ </section>
+ );
+}
+
+export function CookieAlertsPanel({
+ data,
+ onChange,
+}: {
+ data: ServiceCookieAlertsPayload;
+ onChange: () => void;
+}) {
+ if (data.alerts.length === 0) return null;
+ return (
+ <div className="flex flex-col gap-2" aria-label="Cookie refresh alerts">
+ {data.alerts.map((a) => (
+ <AlertCard key={a.service} alert={a} onChange={onChange} />
+ ))}
+ </div>
+ );
+}
diff --git a/editor/app/components/dashboard/DashboardCockpit.tsx b/editor/app/components/dashboard/DashboardCockpit.tsx
@@ -9,6 +9,8 @@ import { PipelineBand } from "./PipelineBand";
import { NeedsWorkPanel } from "./NeedsWorkPanel";
import { QuickAddPanel } from "./QuickAddPanel";
import { FirstRunPanel, type FirstRunState } from "./FirstRunPanel";
+import { CookieAlertsPanel } from "./CookieAlertsPanel";
+import type { ServiceCookieAlertsPayload } from "yt-dlp-transcript-common/lib/serviceCookies";
import type { ChannelRowView } from "yt-dlp-transcript-common/views/channelRow";
import { ChannelsTable } from "../../channels/components/ChannelsTable";
import {
@@ -36,8 +38,12 @@ export type DashboardCockpitInitial = {
changelogSource: string | null;
// Set while the corpus has no channel (app/page.tsx): the first-run checklist.
firstRun?: FirstRunState | null;
+ // The cookie refresh alerts (lib/cookieAlerts.ts), polled SLOW after this.
+ cookieAlerts?: ServiceCookieAlertsPayload;
};
+const EMPTY_COOKIE_ALERTS: ServiceCookieAlertsPayload = { alerts: [], pending: [] };
+
// The mission-control cockpit. A server component (app/page.tsx) SSRs the
// initial payloads for a flicker-free first paint; this client shell then polls
// the same /api endpoints the widget uses so the whole surface updates in place.
@@ -73,10 +79,21 @@ export function DashboardCockpit({
SLOW_MS,
initial.sync,
);
+ const { data: cookieAlerts, refetch: refetchCookieAlerts } =
+ usePolledPayload<ServiceCookieAlertsPayload>(
+ "/api/view/cookieAlerts",
+ true,
+ SLOW_MS,
+ initial.cookieAlerts ?? EMPTY_COOKIE_ALERTS,
+ );
return (
<div className="flex flex-col gap-6">
<h1 className="sr-only">Dashboard</h1>
+ <CookieAlertsPanel
+ data={cookieAlerts ?? EMPTY_COOKIE_ALERTS}
+ onChange={() => void refetchCookieAlerts()}
+ />
{initial.firstRun && <FirstRunPanel state={initial.firstRun} />}
<PipelineBand
jobs={jobs}
diff --git a/editor/app/lib/cookieAlerts.ts b/editor/app/lib/cookieAlerts.ts
@@ -0,0 +1,45 @@
+// THE DASHBOARD'S COOKIE REFRESH ALERTS (plans/cookie-refresh-alerts.md): the
+// state file read, each recorded job's status asked of the registry (else its
+// sidecar), and the pure builder (lib/serviceCookies.ts) over both. Served as
+// the `cookieAlerts` view and SSR-seeded by app/page.tsx.
+
+import { getPaths, type Paths } from "yt-dlp-transcript-common/lib/paths";
+import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
+import { readJobMeta } from "yt-dlp-transcript-common/jobs/jobMeta";
+import {
+ buildServiceCookieAlerts,
+ type ServiceCookieAlertsPayload,
+} from "yt-dlp-transcript-common/lib/serviceCookies";
+import {
+ configuredCookieBrowser,
+ readServiceCookieState,
+} from "yt-dlp-transcript-common/lib/serviceCookies-server";
+
+export async function loadCookieAlerts(
+ paths: Paths = getPaths(),
+ now: number = Date.now(),
+): Promise<ServiceCookieAlertsPayload> {
+ const state = await readServiceCookieState(paths);
+ const ids = new Set<string>();
+ for (const e of Object.values(state.services)) {
+ if (!e.raisedAt) continue;
+ for (const j of e.jobs) ids.add(j.id);
+ }
+ // Only a job that can be retried (it carries a replay descriptor) is one
+ // "Re-run stopped jobs" can offer: a lane's unit or a one-off without a spec
+ // has no status here, so it is never listed as stopped.
+ const statuses = new Map<string, string>();
+ const registry = getRegistry();
+ for (const id of ids) {
+ const live = registry.get(id);
+ const meta = live ? null : await readJobMeta(paths, id);
+ const status = live?.status ?? meta?.status;
+ const replayable = Boolean(live?.spec ?? meta?.spec);
+ if (status && replayable) statuses.set(id, status);
+ }
+ return buildServiceCookieAlerts(state, {
+ now,
+ browser: configuredCookieBrowser(),
+ statusOf: (id) => statuses.get(id),
+ });
+}
diff --git a/editor/app/lib/safeRevalidate.test.ts b/editor/app/lib/safeRevalidate.test.ts
@@ -163,6 +163,18 @@ test("the real revalidatePath does throw here (the premise of the helper)", asyn
);
});
+test("a job revalidating inside a request that is rendering is a skip, not a failure", () => {
+ assert.equal(
+ runGuarded(() => {
+ throw new Error(
+ 'Route / used "revalidatePath /channels/test-youtube/videos/embed403a" during render which is unsupported. ' +
+ "To ensure revalidation is performed consistently it must always happen outside of renders and cached functions.",
+ );
+ }),
+ true,
+ );
+});
+
test("any other error is rethrown; a revalidation that runs is not a skip", () => {
assert.throws(
() =>
diff --git a/editor/app/lib/safeRevalidate.ts b/editor/app/lib/safeRevalidate.ts
@@ -23,9 +23,17 @@ import { revalidatePath, revalidateTag } from "next/cache";
export type RevalidateTarget = string | [string, "page" | "layout"];
const MISSING_STORE = /static generation store missing/;
+// THE OTHER WAY A JOB MEETS A STORE IT CANNOT USE (cookie refresh alerts,
+// 2026-10-21): a job that STARTED at once inside a server action carries that
+// request's store with it, and when the action also revalidated, Next renders
+// the page in the same request — a revalidation the job makes after that
+// finds the store in its render phase and throws `Route / used
+// "revalidatePath …" during render which is unsupported`. Same answer: the
+// page re-reads disk on its next request; skipped, never a failed job.
+const DURING_RENDER = /used "revalidate(?:Path|Tag)[^"]*" during render which is unsupported/;
function isMissingStore(err: unknown): boolean {
- return err instanceof Error && MISSING_STORE.test(err.message);
+ return err instanceof Error && (MISSING_STORE.test(err.message) || DURING_RENDER.test(err.message));
}
function describe(target: RevalidateTarget): string {
diff --git a/editor/app/operations/serviceCookiesActions.ts b/editor/app/operations/serviceCookiesActions.ts
@@ -0,0 +1,112 @@
+"use server";
+
+// THE COOKIE REFRESH ALERT'S BUTTONS (plans/cookie-refresh-alerts.md), shared
+// by the dashboard banner and `/api/ops/service-cookies`:
+//
+// Recheck ONE request through the service's own path, as a one-step job
+// (kind `recheck-service-cookies`, its own queue) that the click
+// waits for — the alert clears when it comes back clean.
+// Dismiss the operator's word: the alert is cleared as if the service
+// had answered.
+// Re-run every job the alert stopped (failed or cancelled), retried
+// from its replay descriptor ahead of the queue, as /jobs' Retry.
+
+// No revalidatePath here: the banner refetches its own view after each click
+// (CookieAlertsPanel's onChange), and the page is not re-rendered under a job
+// that started inside this request.
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { runManagedFunction } from "yt-dlp-transcript-common/jobs/streamCommand";
+import { isServiceKey, serviceLabel } from "yt-dlp-transcript-common/lib/serviceCookies";
+import {
+ dismissServiceCookieAlert,
+ markServiceCookieRerun,
+} from "yt-dlp-transcript-common/lib/serviceCookies-server";
+import {
+ recheckServiceCookies,
+ type RecheckOutcome,
+} from "yt-dlp-transcript-common/controller/recheckServiceCookies";
+import { retryJobAction } from "../jobs/actions";
+import { loadCookieAlerts } from "../lib/cookieAlerts";
+
+function refuse(service: string): string | null {
+ return isServiceKey(service) ? null : `Not a service: ${service}`;
+}
+
+export async function recheckServiceCookiesAction(
+ service: string,
+): Promise<
+ | { ok: true; jobId: string; result: RecheckOutcome["result"]; message: string }
+ | { ok: false; error: string; jobId?: string }
+> {
+ const bad = refuse(service);
+ if (bad) return { ok: false, error: bad };
+ const paths = getPaths();
+ let outcome: RecheckOutcome | null = null;
+ const res = await runManagedFunction({
+ kind: "recheck-service-cookies",
+ queueKey: `service-cookies:${service}`,
+ paths,
+ fn: async (onLog, signal) => {
+ outcome = await recheckServiceCookies({ paths, service, onLog, signal });
+ },
+ });
+ if (!res.ok) return { ok: false, error: res.error };
+ void res.stream.cancel();
+ const done = await res.done;
+ const o = outcome as RecheckOutcome | null;
+ if (done.status !== "done" || !o) {
+ return { ok: false, jobId: res.jobId, error: `The ${serviceLabel(service)} recheck ended ${done.status}.` };
+ }
+ return { ok: true, jobId: res.jobId, result: o.result, message: o.message };
+}
+
+export async function dismissServiceCookiesAction(
+ service: string,
+): Promise<{ ok: true; message: string } | { ok: false; error: string }> {
+ const bad = refuse(service);
+ if (bad) return { ok: false, error: bad };
+ const had = await dismissServiceCookieAlert(getPaths(), service);
+ return {
+ ok: true,
+ message: had
+ ? `${serviceLabel(service)}'s cookie alert dismissed.`
+ : `${serviceLabel(service)} had no cookie alert to dismiss.`,
+ };
+}
+
+export async function rerunServiceStoppedJobsAction(
+ service: string,
+): Promise<
+ | { ok: true; jobIds: string[]; skipped: { id: string; error: string }[]; message: string }
+ | { ok: false; error: string }
+> {
+ const bad = refuse(service);
+ if (bad) return { ok: false, error: bad };
+ const paths = getPaths();
+ const alert = (await loadCookieAlerts(paths)).alerts.find((a) => a.service === service);
+ if (!alert) return { ok: false, error: `${serviceLabel(service)} has no cookie alert.` };
+ if (alert.state === "stale") {
+ return { ok: false, error: `${serviceLabel(service)}'s cookies still look stale — Recheck first.` };
+ }
+ const jobIds: string[] = [];
+ const skipped: { id: string; error: string }[] = [];
+ for (const j of alert.stoppedJobs) {
+ const res = await retryJobAction(j.id);
+ if (res.ok) {
+ void res.stream.cancel();
+ jobIds.push(res.jobId);
+ } else {
+ skipped.push({ id: j.id, error: res.error });
+ }
+ }
+ await markServiceCookieRerun(paths, service, jobIds);
+ return {
+ ok: true,
+ jobIds,
+ skipped,
+ message:
+ `Re-ran ${jobIds.length} job${jobIds.length === 1 ? "" : "s"} ${serviceLabel(service)}'s cookies stopped` +
+ (skipped.length ? `; ${skipped.length} could not be (${skipped.map((s) => `${s.id}: ${s.error}`).join("; ")})` : "") +
+ ".",
+ };
+}
diff --git a/editor/app/page.tsx b/editor/app/page.tsx
@@ -19,6 +19,7 @@ import { buildWorkersPayload } from "./workers/buildWorkers";
import { buildWidgetSyncPayload } from "yt-dlp-transcript-common/views/widgetSync";
import { widgetSyncInputs } from "./widget/lib/syncInputs";
import { DashboardCockpit } from "./components/dashboard/DashboardCockpit";
+import { loadCookieAlerts } from "./lib/cookieAlerts";
import {
buildChannelRowView,
channelVolumeOf,
@@ -133,9 +134,10 @@ export default async function Dashboard({
// active site for the SSR seed.
const actionable = buildWidgetActionablePayload(widgetActionableRows(rows));
- const [jobs, sync] = await Promise.all([
+ const [jobs, sync, cookieAlerts] = await Promise.all([
buildActiveJobsPayload(),
widgetSyncInputs().then(buildWidgetSyncPayload),
+ loadCookieAlerts(paths),
]);
const workers = buildWorkersPayload();
const changelogSource = loadChangelog();
@@ -150,6 +152,7 @@ export default async function Dashboard({
channels,
changelogSource,
firstRun: summary.rows.length === 0 ? firstRunState(paths) : null,
+ cookieAlerts,
}}
/>
);
diff --git a/editor/app/settings/archiveSessionActions.ts b/editor/app/settings/archiveSessionActions.ts
@@ -20,6 +20,8 @@ import {
import { isArchiveTodayUrl } from "yt-dlp-transcript-common/lib/archives/mementos";
import { sanitizeArchives, type ArchivesSettings } from "yt-dlp-transcript-common/lib/archives/settings";
import { saveSettings } from "./saveSettings";
+import { noteServiceCookieClean } from "yt-dlp-transcript-common/lib/serviceCookies-server";
+import { ARCHIVE_TODAY_SERVICE } from "yt-dlp-transcript-common/lib/serviceCookies";
export async function archiveSessionStatusAction(): Promise<ArchiveSessionStatus> {
return readArchiveSessionStatus(getPaths());
@@ -36,6 +38,11 @@ export async function connectArchiveSessionAction(
const record = await connectArchiveSession(getPaths(), at, {
onLog: (line) => console.log(`[archive-session] ${line}`),
});
+ // A window that closed on a page that is not a check clears the cookie
+ // refresh alert for archive.today (the dashboard's banner).
+ if (record.cleared) {
+ await noteServiceCookieClean(getPaths(), ARCHIVE_TODAY_SERVICE, undefined, { by: "connect" });
+ }
revalidatePath("/settings");
return { ok: true, record };
} catch (e) {
diff --git a/editor/e2e/cookie-alerts.spec.ts b/editor/e2e/cookie-alerts.spec.ts
@@ -0,0 +1,136 @@
+// COOKIE REFRESH ALERTS (plans/cookie-refresh-alerts.md), end to end.
+//
+// The 2026-10-21 case in miniature: a fetch-windows batch on Rumble whose
+// embeds 403 (the browser's Cloudflare clearance cookie had gone stale). The
+// fake yt-dlp answers `embed403` URLs with the real RumbleEmbed 403 line until
+// the spec drops `fake-ytdlp.fresh-cookies` in the channel dir — the operator
+// opening rumble.com in the browser. Two different videos refused in a row
+// raise the banner; Recheck (one metadata request) clears it once the fake
+// answers; "Re-run stopped jobs" retries the batch it stopped.
+//
+// Same token as /api/ops/* (WORKER_TOKEN=test-worker-token on the test server).
+
+import { readFile, writeFile } from "node:fs/promises";
+import { test, expect, type APIRequestContext } from "@playwright/test";
+import { resetData, resolvePath, testPaths, writeSettings } from "./helpers";
+import { baseUrl } from "./baseUrl";
+
+const AUTH = { authorization: "Bearer test-worker-token" };
+const SLUG = "test-youtube";
+const channelRel = (p: string) => `${testPaths().transcriptsDir}/channels/${SLUG}/${p}`;
+
+async function jobStatus(request: APIRequestContext, jobId: string): Promise<string> {
+ const r = await request.get(`${baseUrl}/api/ops/job/${jobId}`, { headers: AUTH });
+ const body = (await r.json()) as { job?: { status?: string } };
+ return body.job?.status ?? "";
+}
+
+async function waitJob(request: APIRequestContext, jobId: string, timeout = 90_000): Promise<string> {
+ let status = "";
+ await expect
+ .poll(
+ async () => {
+ status = await jobStatus(request, jobId);
+ return status;
+ },
+ { timeout },
+ )
+ .not.toMatch(/^(queued|running|)$/);
+ return status;
+}
+
+test.beforeEach(async () => {
+ await resetData("youtube-with-playlist");
+ await writeSettings({ minFreeDiskGB: 0 });
+});
+
+test("two Rumble embeds refused raise the banner; Recheck with fresh cookies clears it; the stopped batch re-runs", async ({
+ page,
+ request,
+}) => {
+ test.setTimeout(180_000);
+ const items = [
+ { slug: SLUG, id: "embed403a", webpageUrl: "https://rumble.com/vembed403a-first.html", from: 5, to: 10, clipId: "c01" },
+ { slug: SLUG, id: "embed403b", webpageUrl: "https://rumble.com/vembed403b-second.html", from: 5, to: 10, clipId: "c02" },
+ ];
+ const post = await request.post(`${baseUrl}/api/ops/fetch-windows`, {
+ headers: AUTH,
+ data: { requestedBy: "umtool", manifest: "cookie-alerts", items },
+ });
+ expect(post.status()).toBe(200);
+ const body = (await post.json()) as { jobs: { platform: string; jobId: string }[] };
+ expect(body.jobs).toHaveLength(1);
+ expect(body.jobs[0].platform).toBe("rumble");
+ const batchId = body.jobs[0].jobId;
+ expect(await waitJob(request, batchId)).toBe("failed");
+
+ // The stopping job's log names the cause and the fix.
+ const log = await readFile(resolvePath(`${testPaths().transcriptsDir}/.jobs/${batchId}.log`), "utf8");
+ expect(log).toMatch(/a removed video does this too; a second video refused in a row raises the cookie alert/);
+ expect(log).toMatch(/stopped: Rumble cookies look stale — open rumble\.com in .*, then Recheck on the dashboard\./);
+
+ // The read side says the same.
+ const services = await request.get(`${baseUrl}/api/ops/services`, { headers: AUTH });
+ expect(services.status()).toBe(200);
+ const s = (await services.json()) as { alerts: { service: string; state: string; stoppedJobs: { id: string }[] }[] };
+ expect(s.alerts.map((a) => [a.service, a.state])).toEqual([["rumble", "stale"]]);
+
+ // The banner, top of the dashboard.
+ await page.goto(`${baseUrl}/`);
+ const banner = page.getByRole("alert", { name: "Rumble cookies" });
+ await expect(banner).toContainText("Rumble needs fresh cookies: open rumble.com in");
+ await expect(banner).toContainText("2 embed 403s on different videos");
+
+ // Recheck while the cookies are still stale: it stays.
+ await banner.getByRole("button", { name: "Recheck" }).click();
+ await expect(page.getByRole("status", { name: "Rumble cookies result" })).toContainText("still refused", {
+ timeout: 30_000,
+ });
+ await expect(banner).toHaveAttribute("data-state", "stale");
+
+ // The operator opens rumble.com in the browser; Recheck clears it.
+ await writeFile(resolvePath(channelRel("fake-ytdlp.fresh-cookies")), "fresh");
+ await banner.getByRole("button", { name: "Recheck" }).click();
+ await expect(banner).toHaveAttribute("data-state", "ok-again", { timeout: 30_000 });
+ await expect(banner).toContainText("Rumble cookies OK again — re-run the 1 job it stopped");
+ const invocations = await readFile(resolvePath(channelRel("fake-ytdlp.invocations")), "utf8");
+ expect(invocations).toContain("recheck:https://rumble.com/vembed403b-second.html");
+
+ // Re-run the batch it stopped: the windows fetch now.
+ await banner.getByRole("button", { name: "Re-run stopped jobs" }).click();
+ await expect(page.getByRole("status", { name: "Rumble cookies result" })).toContainText("Re-ran 1 job", {
+ timeout: 30_000,
+ });
+ const after = (await (await request.get(`${baseUrl}/api/ops/services`, { headers: AUTH })).json()) as {
+ alerts: { service: string; rerunJobIds?: string[] }[];
+ };
+ const rerun = after.alerts.find((a) => a.service === "rumble")?.rerunJobIds ?? [];
+ expect(rerun).toHaveLength(1);
+ const rerunStatus = await waitJob(request, rerun[0]);
+ const tail = await request.get(`${baseUrl}/api/ops/job/${rerun[0]}?tail=40`, { headers: AUTH });
+ expect(rerunStatus, ((await tail.json()) as { tail?: string[] }).tail?.join("\n")).toBe("done");
+});
+
+test("ops: get services is behind the token; recheck-service refuses a name that is not a service", async ({ request }) => {
+ expect((await request.get(`${baseUrl}/api/ops/services`)).status()).toBe(401);
+ const empty = await request.get(`${baseUrl}/api/ops/services`, { headers: AUTH });
+ expect(empty.status()).toBe(200);
+ expect(await empty.json()).toMatchObject({ ok: true, alerts: [], pending: [] });
+ const bad = await request.post(`${baseUrl}/api/ops/recheck-service`, {
+ headers: AUTH,
+ data: { service: "you tube/../x" },
+ });
+ expect(bad.status()).toBe(400);
+ const nothing = await request.post(`${baseUrl}/api/ops/recheck-service`, {
+ headers: AUTH,
+ data: { service: "odysee" },
+ });
+ // Nothing recorded for Odysee: the probe has nothing to ask, and says so.
+ expect(nothing.status()).toBe(200);
+ expect(await nothing.json()).toMatchObject({ ok: true, result: "failed" });
+ const dismiss = await request.post(`${baseUrl}/api/ops/dismiss-service`, {
+ headers: AUTH,
+ data: { service: "youtube" },
+ });
+ expect(await dismiss.json()).toMatchObject({ ok: true, message: "YouTube had no cookie alert to dismiss." });
+});
diff --git a/editor/e2e/fixtures/bin/fake-ytdlp.mjs b/editor/e2e/fixtures/bin/fake-ytdlp.mjs
@@ -71,6 +71,25 @@ function failCookieGate(url) {
process.exit(1);
}
+// The `embed403` sentinel: Rumble's embed JSON metadata refused with a 403 —
+// what a stale Cloudflare clearance cookie looks like — until the spec writes
+// `fake-ytdlp.fresh-cookies` into the cwd (the channel dir): the operator
+// having opened rumble.com in the browser.
+function embed403Blocked(url) {
+ return (url ?? "").toLowerCase().includes("embed403") && !existsSync("fake-ytdlp.fresh-cookies");
+}
+
+function failEmbed403(url) {
+ // The embed id differs per video, as Rumble's does (v<page id> → e<…>).
+ const embed = `e${(urlIdYouTube(url) ?? "x").replace(/[^A-Za-z0-9]/g, "").slice(0, 10)}`;
+ process.stderr.write(`[RumbleEmbed] Extracting URL: https://rumble.com/embed/${embed}\n`);
+ process.stderr.write(`[RumbleEmbed] ${embed}: Downloading JSON metadata\n`);
+ process.stderr.write(
+ `ERROR: [RumbleEmbed] ${embed}: Unable to download JSON metadata: HTTP Error 403: Forbidden (caused by <HTTPError 403: Forbidden>)\n`,
+ );
+ process.exit(1);
+}
+
function urlIdYouTube(u) {
try {
const parsed = new URL(u);
@@ -553,6 +572,17 @@ async function main() {
process.exit(101);
}
+ // THE COOKIE RECHECK (controller/recheckServiceCookies.ts): one metadata
+ // request, `--skip-download --print id`, nothing written. Branched before
+ // everything else that passes --skip-download.
+ if (has("--skip-download") && arg("--print") === "id") {
+ const url = lastNonFlag() ?? "";
+ await appendFile("fake-ytdlp.invocations", `recheck:${url} cookies=${cookieArg()} argv=${argv.join(" ")}\n`);
+ if (embed403Blocked(url)) failEmbed403(url);
+ process.stdout.write(`${urlIdYouTube(url)}\n`);
+ return;
+ }
+
// CLIP WINDOW (fetchWindowManaged): --download-sections *<from>-<to> with an
// absolute -o. Branched FIRST because nothing else passes --download-sections
// and because its -o is a dotfile .part under data/<id>/clips/, which no
@@ -582,6 +612,10 @@ async function main() {
);
process.exit(1);
}
+ // `embed403`: Rumble's embed JSON refused while the browser's Cloudflare
+ // cookie is stale — the cookie refresh alert's signal (2026-10-21) —
+ // until the spec drops `fake-ytdlp.fresh-cookies` in the channel dir.
+ if (embed403Blocked(url)) failEmbed403(url);
// `win403`: Rumble's Cloudflare / googlevideo refusing the media request —
// a `network` failure, which the fetch-windows batch counts toward its
// two-in-a-row backoff.
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -11483,3 +11483,63 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
`pageRecords`. Editor route `GET /api/channels/<slug>/posts-media/<id>/<name>` serves a capture's images.
- **The fake:** `PAGE_SPLIT_URL`/`PAGE_SPLIT_TS` (a Tumblr-themed index, two fixed-width posts, one image) served by
default, and `/web/<ts>im_/<image url>` → a 2×2 PNG (`IMAGE_PNG`).
+
+## Cookie refresh alerts: one state per service (verified 2026-10-21, branch `lane/cookie-alerts`)
+
+- **The name is `serviceCookies`** / "cookie refresh alert": "hold", "cooldown", `needsCookies` and a bare "session"
+ were all taken. A per-channel `needsCookies` (posts-state.json, the needsCookies bucket) is unchanged and unrelated.
+- **The state** is `<transcriptsDir>/.service-cookies.json` (`common/lib/serviceCookies-server.ts`
+ `serviceCookiesFile`; NOT a `Paths` field — tests that build `Paths` by hand are untouched): `{version: 1,
+ services: {<key>: {service, kind: embed-403|bot-check|challenge|check-page, since, lastSeen, count, evidence:
+ {jobId?, channel?, videoId?, url?, line}, videos[], raisedAt?, jobs: [{id, kind?}], clearedAt?, clearedBy?:
+ clean|recheck|dismiss|connect, rerunAt?, rerunJobIds?}}, lastGood: {<key>: {url, channel?, at}}}`. Keys:
+ `rumble`, `youtube`, `odysee`, `archive.today`, or a forum's host (`forumServiceKey`: lowercased, no www.).
+ `coerceServiceCookieState` drops what it cannot read; every write is `withJsonFileLock` + `writeJsonAtomic`
+ (`mutate`), and every recorder swallows its own errors — no job fails on the bookkeeping.
+- **The rules** (pure, `common/lib/serviceCookies.ts`): an entry is PENDING until `raisedAt`. `embed-403` needs 2
+ DISTINCT `videos` (a removed Rumble video 403s too; prefetch + download of one video is one); every other kind 1.
+ A pending entry is dropped by any clean request to the service and forgotten after 1 h
+ (`PENDING_SIGNAL_TTL_MS`). A raised one is CLEARED by a clean request, kept 24 h (`CLEARED_KEEP_MS`) for "OK
+ again — re-run the N jobs it stopped"; with no job left to re-run, the view shows it only 15 min
+ (`OK_AGAIN_SHOW_MS`). A signal after the clearing starts a fresh entry. `lastGood` refreshes at most every 10 min.
+- **The signals** (`serviceCookieSignalFromStderr`): `[RumbleEmbed] <id>: Unable to download … HTTP Error 403`
+ (the embed id is the video); `isBotCheck` → youtube; Odysee = a 403 on an `[lbry|odysee]` line (or an odysee URL)
+ AND Cloudflare's words (`just a moment|cloudflare|cf-mitigated|cf-chl|anti-bot challenge`) — NO REAL SAMPLE yet.
+ `classifyDownloadFailure` is unchanged (the embed 403 is still `network`). Real samples:
+ `common/lib/__fixtures__/rumble-{embed-403.download,fetch-windows-stopped}.log` (paths scrubbed).
+- **Where they are recorded:** `runOneYtdlp` takes `observe: {paths, url, channel?}` and, after the child exits,
+ calls `observeYtdlpServiceOutcome` (exit 0 on a yt-dlp service = clean; else the signal). Passed by
+ `downloadOneManaged`'s wrapper, `fetchWindowManaged`'s yt-dlp run (NOT its ffmpeg stored-URL cut, which goes
+ through the same runner), `fetchCopyManaged`, `refreshVideoMetadata`, `fetchLiveChat`. Without `observe` nothing
+ is observed. Batch stops call `observeStderrServiceSignal`: `metadataScan` (a block that survived its cookie
+ retry; a clean scan clears), `checkAvailability` (blocked), `runYtdlp`'s enumeration (any non-zero exit). Forum:
+ `fetchPosts.fetchTimeline` → `noteForumServiceOutcome` (challenge/captcha/login = signal; no block and no error =
+ clean). archive.today: `ArchiveTodayClientDeps.observe` (the process client in `lib/archives/index.ts` →
+ `noteArchiveTodayOutcome`): a check that stood (`challenged`) = signal, a timemap/copy/404 (`answered`) = clean.
+ Connect forum/archive session with `record.cleared` → clean, `by: "connect"`.
+- **The job context:** `common/lib/jobContext.ts` — an `AsyncLocalStorage` on globalThis; `runManagedFunction`
+ runs `fn` inside `runInJobContext({jobId, kind, channelSlug?, onLog, staleServices})`. The recorder adds the job to
+ the entry's `jobs` and, once the alert is up, writes `serviceStoppedLine` into that job's log once per service
+ (`stopped: Rumble cookies look stale — open rumble.com in <browser>…, then Recheck on the dashboard.`); a job that
+ then FAILS repeats it after its `[error]` line. "Stopped jobs" = the entry's jobs that carry a replay descriptor
+ (`spec`) and whose status (registry, else `.meta.json`) is failed or cancelled. A `recheck-service-cookies` job is
+ never recorded against the alert.
+- **Recheck** (`common/controller/recheckServiceCookies.ts`, job kind `recheck-service-cookies` on queue
+ `service-cookies:<service>`): yt-dlp services → `recheckYtdlpArgs` (`--skip-download --print id`, the channel's
+ `channelExtraArgs` with `authRetryCookies`, the window fetch's refusals after them) for `lastGood`, else the
+ evidence URL, cwd the channel dir; clean also calls `recordPlatformClean` (the 403 streak's network backoff would
+ otherwise refuse the re-run). Forum → one page through `browserForumLoader` + `classifyForumPage`. archive.today →
+ the evidence request again through `archiveTodayClient` (timemap → `listCaptures`, else `getCapture`).
+- **Surfaces:** view `cookieAlerts` (`VIEW_NAMES`; `editor/app/lib/cookieAlerts.ts` `loadCookieAlerts`; the first
+ view with no old-path rewrite — `route.test.ts` `NEW_VIEWS`), SSR-seeded and polled SLOW by `DashboardCockpit`
+ above `FirstRunPanel` (`CookieAlertsPanel`, `role="alert"` named "<Label> cookies", `data-state`). Actions:
+ `editor/app/operations/serviceCookiesActions.ts`. Ops: `GET /api/ops/services` (`pnpm ops get services`), POST
+ `recheck-service`, `dismiss-service`, `rerun-service-jobs` (`{service}`). Doctor section "service cookies". The
+ e2e fake answers `embed403` URLs with the RumbleEmbed 403 until `fake-ytdlp.fresh-cookies` is in its cwd, and
+ `--skip-download --print id` is its recheck branch (`e2e/cookie-alerts.spec.ts`).
+- **`safeRevalidate` also skips `used "revalidatePath …" during render which is unsupported`** (found by this
+ lane's e2e): a job STARTED at once inside a server action carries that request's store; when the action (or
+ `retryJobAction`, which revalidates `/jobs`) triggers a re-render of the page in the same request, a revalidation
+ the job makes later finds the store in its render phase and threw — the job's work was done and it ended
+ `failed`. Counted as a skip like the missing store. The cookie actions do not revalidate at all (the banner
+ refetches its view).
diff --git a/plans/cookie-refresh-alerts.md b/plans/cookie-refresh-alerts.md
@@ -0,0 +1,107 @@
+# Cookie refresh alerts — one state per service, one banner on the dashboard
+
+Operator, 2026-10-21 (after Rumble embeds 403'd mid-fetch and cleared once rumble.com was opened in Firefox):
+"make this state a first class feature for all sources that shows an alert on the dash that cookies need to be
+refreshed for that service, either rumble, odysee, or KF".
+
+## What happened (the case this answers)
+
+A `fetch-windows` job for the Huck timeline stopped twice with `stopped: network`. Rumble answered
+`[RumbleEmbed] <id>: Unable to download JSON metadata: HTTP Error 403: Forbidden` on some embeds and not others.
+Nothing in the editor said why; the fix was the operator opening rumble.com in Firefox (fresh `cf_clearance`),
+after which the same windows fetched. Today `classifyDownloadFailure` files a bare 403 as "network"
+(`common/lib/availability.ts`), the backoff stores only `{until, fails}` (`common/jobs/platformBackoff.ts`), and the
+Kiwi Farms block lives per channel (`needsCookies` in `fetchPosts.ts`) — no service-level "your session is stale".
+
+## Shape
+
+**State** — a service-keyed record, its own small file `<transcriptsDir>/.service-sessions.json`
+(`common/lib/serviceSessions.ts`, atomic write, coerce-tolerant):
+`{ [service]: { since, lastSeen, count, kind: "embed-403"|"bot-check"|"challenge"|"check-page", evidence: {jobId?,
+channel?, videoId?, line}, clearedAt? } }`. Services: `rumble`, `youtube`, `odysee`, `kiwifarms` (any xenforo host,
+keyed by host), `archive.today`. Not "hold", not `needsCookies`, not "session" alone (naming hazards: all taken).
+
+**Signals** (a classifier beside `isBotCheck` in `availability.ts`, exported, unit-tested on real stderr):
+- Rumble: the RumbleEmbed JSON-metadata 403, on 2 different videos in a row (a removed page 403s too — one is not
+ enough). Odysee: its Cloudflare 403/"Just a moment" signature (collect a real sample first; if none exists yet,
+ ship the hook with the YouTube/Rumble ones and add Odysee's pattern when one is seen).
+- YouTube: the bot check ("Sign in to confirm you're not a bot") — today a rate_limit; also record it here.
+- Kiwi Farms / xenforo: `classifyForumPage` → `challenge` (already `needsCookies=true` per channel) → also the
+ service record.
+- archive.today: `ArchiveRefusal "challenge"` → the record, its action "Connect archive session" (existing flow).
+
+**Clearing** — automatic on the next clean request for that service: `recordPlatformClean`
+(`common/jobs/downloadBackoff.ts`) and the forum/archive success paths; manual "Dismiss" too. A cleared alert keeps
+`clearedAt` for a day so the dashboard can say "Rumble cookies OK again — re-run the 2 jobs it stopped".
+
+**Surfaces**
+- Dashboard (`DashboardCockpit`, top slot like `FirstRunPanel`): a banner per stale service — "Rumble needs fresh
+ cookies: open rumble.com in Firefox (2 embed 403s since 17:02, job fetch-windows …)" with **Recheck** (one cheap
+ probe request through the service's own path; clears on success) and **Re-run stopped jobs** (the jobs the alert
+ stopped, via job retry) once clear. New view `cookieAlerts` (`common/views/cookieAlerts.ts`, `VIEW_NAMES`,
+ `/api/view`), polled SLOW.
+- A failing job's log line names it: "stopped: Rumble cookies look stale — open rumble.com in Firefox, then Recheck".
+- `archilyzer doctor`: a "service cookies" section; `pnpm ops get services` (read) and `pnpm ops recheck-service
+ {"service"}` (COMMANDS.md regenerated).
+- The channel page's existing per-channel `needsCookies` stays; it links to the service banner.
+
+## Tests and gates
+
+Unit: classifier on captured stderr (Rumble embed 403 vs removed-page 403, YouTube bot check, KF challenge HTML,
+archive.today check page); state coerce/clear; two-in-a-row rule. Editor e2e: a fake yt-dlp that 403s twice → banner
+appears with the right text → Recheck with the fake now succeeding → banner clears, "re-run" offered. Docs:
+OPERATING.md (recipe), FACTS. Full gates + editor restart (operator rule: no ask, mind the memory gate).
+
+## Shipped (2026-10-21, branch `lane/cookie-alerts`)
+
+What: a cookie refresh alert per service — Rumble, YouTube, Odysee, archive.today and each forum host — raised
+where the app already meets the service, shown as a banner at the top of the dashboard with Recheck, Dismiss and
+(once clear) Re-run stopped jobs; the stopped job's log names the cause and the fix; `archilyzer doctor` has a
+"service cookies" section; `pnpm ops get services`, `recheck-service`, `dismiss-service`, `rerun-service-jobs`.
+
+Files:
+- `common/lib/serviceCookies.ts` (pure: signal classifier, rules, coercion, the view builder, the sentences),
+ `common/lib/serviceCookies-server.ts` (the file, the locked writer, the yt-dlp / forum / archive.today hooks),
+ `common/lib/jobContext.ts` (the running job as an AsyncLocalStorage; `runManagedFunction` wraps every `fn`).
+- Hooks: `ytdlp/runOneYtdlp.ts` (`observe`), its callers `downloadOneManaged`, `fetchWindowManaged`,
+ `fetchCopyManaged`, `refreshVideoMetadata`, `fetchLiveChat`; `metadataScan`, `checkAvailability`, `runYtdlp`'s
+ enumeration; `controller/fetchPosts.ts`; `lib/archives/archiveTodayClient.ts` (`observe` dep) +
+ `lib/archives/index.ts`; Connect forum/archive session actions.
+- `common/controller/recheckServiceCookies.ts` + job kind `recheck-service-cookies`.
+- Editor: `app/lib/cookieAlerts.ts`, view `cookieAlerts`, `components/dashboard/CookieAlertsPanel.tsx`,
+ `operations/serviceCookiesActions.ts`, `api/ops/{services,recheck-service,dismiss-service,rerun-service-jobs}`;
+ the forum channel panel's needsCookies note links the dashboard. `bin/doctor.ts` "service cookies".
+- Docs: OPERATING.md ("Cookies gone stale"), COMMANDS.md (regenerated), plans/FACTS.md, editor CHANGELOG.
+
+Tests: `common/lib/serviceCookies.test.ts` (15: the real Rumble samples — `lib/__fixtures__/rumble-*.log`, scrubbed —
+the two-videos rule, a removed page's and a media 403, the same video twice, the streak broken by a clean request,
+the pending TTL, YouTube's bot check, Odysee with and without Cloudflare's words, clearing/pruning, coercion, the
+view), `common/lib/serviceCookies-server.test.ts` (8: the job's log line, the yt-dlp hook both ways, no-op writes,
+the lock, a torn file, Kiwi Farms' challenge page, archive.today's check page through the client and its fake,
+dismiss/rerun), `common/controller/recheckServiceCookies.test.ts` (3: Rumble's probe argv and both answers, a
+forum page, archive.today), `bin/doctor.test.ts`, `scripts/archilyzer-ops.test.mjs`,
+`editor/app/api/ops/_writes.test.ts`, `editor/app/api/view/[name]/route.test.ts`, and e2e
+`editor/e2e/cookie-alerts.spec.ts` (fake yt-dlp `embed403` → two 403s → banner → Recheck stale → fresh cookies →
+Recheck clean → "OK again — re-run the 1 job it stopped" → Re-run → the batch finishes `done`).
+
+Decisions (where the plan was refined against the code):
+- The file is `.service-cookies.json` and the module `serviceCookies`, not `serviceSessions` — "session" is taken
+ (forum/archive/X sessions). The view is `cookieAlerts`, as planned.
+- The yt-dlp signal is observed in `runOneYtdlp` (every single-video yt-dlp run, opt-in per caller), not at the
+ `recordDownloadBackoff` call sites — those do not carry stderr. `classifyDownloadFailure` is unchanged: the embed
+ 403 is still a `network` failure for the backoff; the alert is additional.
+- The two-in-a-row rule is kept ACROSS jobs in the state (a pending entry with its distinct videos), not inside
+ fetch-windows' own streak, so a download lane meeting the 403 on two units raises it too. One video refused twice
+ (prefetch + download) counts once.
+- Clearing: any clean request to the service clears it (`clearedBy: clean`), Recheck (`recheck`), Dismiss
+ (`dismiss`), a Connect that ended on a cleared page (`connect`). A successful Recheck of a yt-dlp service also
+ settles the platform's backoff (`recordPlatformClean`), else the re-run would be refused by the cooldown the 403
+ streak left.
+- "Stopped jobs" = the alert's recorded jobs that carry a replay descriptor and ended failed or cancelled; a
+ Recheck's own job is never recorded. "OK again" stays a day while there are jobs to re-run, else 15 min.
+- Odysee: no real sample exists; the hook needs a 403 AND Cloudflare's challenge words. Widen it when one is seen.
+- The forum signal comes from fetchPosts' walk only (not the post capture's login wall).
+- Found on the way (e2e): a job started at once inside a server action whose page then re-rendered threw from its
+ own `safeRevalidate` ("used revalidatePath … during render") after its work was done, and ended `failed` — the
+ re-run batch did. `editor/app/lib/safeRevalidate.ts` now skips that like a missing store (+ unit test); the cookie
+ actions do not revalidate at all.
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -101,6 +101,8 @@
// pnpm ops fetch-windows --json '{"siteId":"demo-site","dryRun":true}'
// pnpm ops fetch-windows --file windows.json --wait
// pnpm ops get tags eva-collab
+// pnpm ops get services
+// pnpm ops recheck-service --json '{"service":"rumble"}'
// pnpm ops cut-release --json '{"workspace":"all","version":"next","commit":true}'
// pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150}' --wait
// pnpm ops transcribe --json '{"path":"/abs/a.wav","workerId":"parakeet-cpu","out":"/tmp/a.json"}' --wait
@@ -244,6 +246,9 @@ const GETTERS = {
"auto-queue": () => "/api/ops/auto-queue",
// The sync scheduler: each channel's schedule, the tick log.
scheduler: () => "/api/ops/scheduler",
+ // The dashboard's cookie refresh alerts: each service whose cookies look
+ // stale (or are OK again, with the jobs the alert stopped).
+ services: () => "/api/ops/services",
// One channel's cleanup row: what each sweep would reclaim, what holds the rest.
cleanup: (slug) => `/api/ops/cleanup/${encodeURIComponent(slug)}`,
// What a channel holds, by date, and its gaps (release 19 A9): each video
@@ -291,6 +296,7 @@ const GET_ARG_OPTIONAL = new Set([
"workers",
"auto-queue",
"scheduler",
+ "services",
"generation-usage",
]);
@@ -444,6 +450,12 @@ const ACTIONS = [
// ({slug, sweep}).
"settings",
"clear-platform-hold",
+ // COOKIE REFRESH ALERTS: a service's alert rechecked with one request
+ // through its own path ({service}), dismissed ({service}), or the jobs it
+ // stopped re-run once it is OK again ({service}).
+ "recheck-service",
+ "dismiss-service",
+ "rerun-service-jobs",
"workers",
"transcribe-one",
"delete-file",
@@ -901,6 +913,7 @@ export function usage() {
" pnpm ops job wait <id>... [--wait-timeout <seconds>]",
" pnpm ops get settings [<key>]",
" pnpm ops get storage | sites | workers | auto-queue | scheduler",
+ " pnpm ops get services",
" pnpm ops get cleanup <slug>",
" pnpm ops get remote-listing <slug> [--wait-timeout <seconds>]",
" pnpm ops get transcript <videoId> [--slug <slug>]",
@@ -941,6 +954,10 @@ export function usage() {
" is the status.)",
"get workers, get auto-queue and get scheduler are /workers, the four lanes",
" of /operations, and /operations/sync — the payloads those pages poll.",
+ "get services is the dashboard's cookie refresh alerts: each service",
+ " (rumble, youtube, odysee, archive.today, a forum host) whose cookies look",
+ " stale, or are OK again with the jobs the alert stopped; \"pending\" lists",
+ " a first Rumble embed 403 waiting for a second video.",
"get cleanup <slug> is one channel's /cleanup row: what each sweep would",
" reclaim (they overlap — never add them), what holds the rest, and the",
" failed-transcriptions count. measured: false means unknown, not zero.",
@@ -1023,6 +1040,15 @@ export function usage() {
'clear-platform-hold clears a platform\'s rate-limit hold, backoff and raised',
' pace, as the lane strip\'s Clear hold: {"platform"}. Answers the sentence.',
"",
+ 'recheck-service asks a service whose cookie refresh alert is up ONE request',
+ ' through its own path, as the dashboard banner\'s Recheck: {"service"}',
+ ' ("rumble", "youtube", "odysee", "archive.today" or a forum host). Waits',
+ ' for it: {jobId, result: "clean" | "stale" | "failed", message}; "clean"',
+ " clears the alert (and a yt-dlp service's backoff, as any clean request).",
+ 'dismiss-service clears a service\'s cookie alert by hand: {"service"}.',
+ 'rerun-service-jobs retries every job a service\'s cookie alert stopped, once',
+ ' it is OK again: {"service"} -> {jobIds, skipped}. --wait follows them.',
+ "",
'workers switches transcription workers as /workers does: {"op": "enable" |',
' "disable" | "drain", "ids": [...]} — the live pool; a restart restores',
' the launch default. An unknown id is named; the others still apply.',
diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs
@@ -824,6 +824,20 @@ test("the archival writes are POSTs to their routes, each named in the usage", (
assert.match(usage(), /"publish", "enabled"\?, "held"\?, "action"\?/);
});
+// COOKIE REFRESH ALERTS: the read side and the banner's three buttons.
+test("get services is a GET on its route; recheck/dismiss/rerun are POSTs named in the usage", () => {
+ const g = parseArgs(["get", "services"]);
+ assert.equal(g.method, "GET");
+ assert.equal(g.path, "/api/ops/services");
+ assert.match(usage(), /pnpm ops get services/);
+ for (const action of ["recheck-service", "dismiss-service", "rerun-service-jobs"]) {
+ const p = parseArgs([action, "--json", '{"service":"rumble"}']);
+ assert.equal(p.method, "POST", action);
+ assert.equal(p.path, `/api/ops/${action}`, action);
+ assert.match(usage(), new RegExp(`^${action} `, "m"), action);
+ }
+});
+
// RELEASE 36 LANE A: the clip finder's chain and one video's chat replay.
test("fetch-chat and find-clips are POSTs named in the usage; find-clips --wait carries its marker", () => {
for (const action of ["fetch-chat", "find-clips"]) {