Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 1289b8770348d72e547016c6ef179e8e6e00dab2
parent f957c5df364d552c5c7a92baf6351388c9f059dc
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 21 Oct 2026 18:04:56 -0400

serviceCookies: one cookie refresh alert per service, recorded where yt-dlp, the forum walk and archive.today meet it

A Rumble embed 403 on two different videos in a row, YouTube's bot check,
Odysee's Cloudflare 403, a forum's check or login wall and archive.today's
check page raise <transcripts>/.service-cookies.json's alert; the next clean
request clears it. runManagedFunction runs every job in an async context so
the alert records the jobs it stopped and the job's log names the cause and
the fix. Recheck is one request through the service's own path.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mcommon/controller/checkAvailability.ts | 3+++
Mcommon/controller/fetchLiveChat.ts | 12+++++++++++-
Mcommon/controller/fetchPosts.ts | 12++++++++++++
Acommon/controller/recheckServiceCookies.ts | 213+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/refreshVideoMetadata.ts | 7++++++-
Mcommon/jobs/jobKinds.ts | 12++++++++++++
Mcommon/jobs/streamCommand.ts | 21++++++++++++++++++++-
Acommon/lib/__fixtures__/rumble-embed-403.download.log | 19+++++++++++++++++++
Acommon/lib/__fixtures__/rumble-fetch-windows-stopped.log | 38++++++++++++++++++++++++++++++++++++++
Mcommon/lib/archives/archiveTodayClient.ts | 48++++++++++++++++++++++++++++++++++++++++--------
Mcommon/lib/archives/index.ts | 3+++
Acommon/lib/jobContext.ts | 40++++++++++++++++++++++++++++++++++++++++
Acommon/lib/serviceCookies-server.test.ts | 265+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/serviceCookies-server.ts | 303+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/serviceCookies.test.ts | 250+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/serviceCookies.ts | 548+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/ytdlp/downloadOneManaged.ts | 8+++++++-
Mcommon/ytdlp/fetchCopyManaged.ts | 7++++++-
Mcommon/ytdlp/fetchWindowManaged.ts | 7+++++++
Mcommon/ytdlp/metadataScan.ts | 10++++++++++
Mcommon/ytdlp/runOneYtdlp.ts | 17+++++++++++++++++
Mcommon/ytdlp/runYtdlp.ts | 7+++++++
22 files changed, 1837 insertions(+), 13 deletions(-)

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.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,265 @@ +// Cookie refresh alerts — the file, the job's log line, the yt-dlp hook, the +// forum and archive.today paths, and Recheck (plans/cookie-refresh-alerts.md). +// 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 { recheckServiceCookies } from "../controller/recheckServiceCookies"; +import { ArchiveTodayClient } from "./archives/archiveTodayClient"; +import { startFakeArchiveToday, AT_CHECKED_ID, AT_ARTICLE_URL } from "../testing/web/fakeArchiveToday.mjs"; + +const FIX = path.join(path.dirname(fileURLToPath(import.meta.url)), "__fixtures__"); +const EMBED_403 = readFileSync(path.join(FIX, "rumble-embed-403.download.log"), "utf8"); +const embed403For = (id: string) => EMBED_403.replaceAll("v7ez8hg", id); + +async function tmpPaths() { + const transcriptsDir = await mkdtemp(path.join(os.tmpdir(), "service-cookies-")); + return { transcriptsDir, channelsDir: path.join(transcriptsDir, "channels") }; +} + +function jobCtx(jobId: string, kind = "fetch-windows"): JobContext & { lines: string[] } { + const lines: string[] = []; + return { jobId, kind, onLog: (l) => lines.push(l), staleServices: new Set(), lines }; +} + +test("two embed 403s on different videos inside a job: the alert is raised, the job recorded, its log says the cause and the fix once", async () => { + const paths = await tmpPaths(); + try { + const ctx = jobCtx("JOB1"); + await runInJobContext(ctx, async () => { + await observeYtdlpServiceOutcome(paths, { url: "https://rumble.com/v7fdzwe-x.html", channel: "huck", exitCode: 1, stderrTail: embed403For("v7d7myw") }); + await observeYtdlpServiceOutcome(paths, { url: "https://rumble.com/v7f8yuw-y.html", channel: "huck", exitCode: 1, stderrTail: embed403For("v7d2lxe") }); + await observeYtdlpServiceOutcome(paths, { url: "https://rumble.com/v7f8yuw-y.html", channel: "huck", exitCode: 1, stderrTail: embed403For("v7d2lxe") }); + }); + const state = await readServiceCookieState(paths); + assert.equal(isAlertRaised(state.services.rumble), true); + assert.deepEqual(state.services.rumble.jobs, [{ id: "JOB1", kind: "fetch-windows" }]); + assert.equal(state.services.rumble.evidence.channel, "huck"); + assert.equal(state.services.rumble.evidence.url, "https://rumble.com/v7f8yuw-y.html"); + assert.deepEqual([...ctx.staleServices], ["rumble"]); + const stopped = ctx.lines.filter((l) => l.startsWith("stopped: Rumble cookies look stale")); + assert.equal(stopped.length, 1, ctx.lines.join("")); + assert.match(ctx.lines[0], /a removed video does this too/); + // The file is JSON on disk. + JSON.parse(await readFile(serviceCookiesFile(paths), "utf8")); + } finally { + await rm(paths.transcriptsDir, { recursive: true, force: true }); + } +}); + +test("a clean yt-dlp run clears the alert, remembers the request, and an aborted run is not observed", async () => { + const paths = await tmpPaths(); + try { + await noteServiceCookieSignal(paths, { service: "youtube", kind: "bot-check", line: "x" }); + await observeYtdlpServiceOutcome(paths, { url: "https://www.youtube.com/watch?v=abc", exitCode: 0, stderrTail: "", aborted: true }); + assert.equal(isAlertRaised((await readServiceCookieState(paths)).services.youtube), true); + const ctx = jobCtx("JOB2", "download-one"); + await runInJobContext(ctx, () => + observeYtdlpServiceOutcome(paths, { url: "https://www.youtube.com/watch?v=abc", channel: "c", exitCode: 0, stderrTail: "" }), + ); + const state = await readServiceCookieState(paths); + assert.equal(state.services.youtube.clearedBy, "clean"); + assert.deepEqual(state.lastGood.youtube && [state.lastGood.youtube.url, state.lastGood.youtube.channel], ["https://www.youtube.com/watch?v=abc", "c"]); + assert.deepEqual(ctx.lines, ["YouTube answered cleanly: its cookie alert is cleared.\n"]); + } finally { + await rm(paths.transcriptsDir, { recursive: true, force: true }); + } +}); + +test("a clean run of a platform with nothing recorded and a fresh lastGood writes nothing", async () => { + const paths = await tmpPaths(); + try { + await observeYtdlpServiceOutcome(paths, { url: "https://rumble.com/a", exitCode: 0, stderrTail: "" }); + const first = await readFile(serviceCookiesFile(paths), "utf8"); + await observeYtdlpServiceOutcome(paths, { url: "https://rumble.com/b", exitCode: 0, stderrTail: "" }); + assert.equal(await readFile(serviceCookiesFile(paths), "utf8"), first); + // A platform that is not a cookie service is never written. + await observeYtdlpServiceOutcome(paths, { url: "https://www.twitch.tv/videos/1", exitCode: 0, stderrTail: "" }); + assert.equal(JSON.parse(await readFile(serviceCookiesFile(paths), "utf8")).lastGood.twitch, undefined); + } finally { + await rm(paths.transcriptsDir, { recursive: true, force: true }); + } +}); + +test("two services meeting their signals at once are both recorded (the lock)", async () => { + const paths = await tmpPaths(); + try { + await Promise.all([ + noteServiceCookieSignal(paths, { service: "youtube", kind: "bot-check", line: "y" }), + noteServiceCookieSignal(paths, { service: "odysee", kind: "challenge", line: "o" }), + noteServiceCookieSignal(paths, { service: "archive.today", kind: "check-page", line: "a" }), + ]); + assert.deepEqual(Object.keys((await readServiceCookieState(paths)).services).sort(), ["archive.today", "odysee", "youtube"]); + } finally { + await rm(paths.transcriptsDir, { recursive: true, force: true }); + } +}); + +test("a file that is not JSON reads as empty and is replaced by the next write", async () => { + const paths = await tmpPaths(); + try { + await writeFile(serviceCookiesFile(paths), "{ torn"); + assert.deepEqual((await readServiceCookieState(paths)).services, {}); + await noteServiceCookieSignal(paths, { service: "youtube", kind: "bot-check", line: "y" }); + assert.ok((await readServiceCookieState(paths)).services.youtube); + } finally { + await rm(paths.transcriptsDir, { recursive: true, force: true }); + } +}); + +test("Kiwi Farms: a challenge page that stopped the walk raises the forum host's alert; a clean walk clears it", async () => { + const paths = await tmpPaths(); + try { + const url = "https://kiwifarms.st/threads/some-thread.123/"; + assert.equal(classifyForumPage(CHALLENGE_PAGE)?.kind, "challenge"); + assert.equal(classifyForumPage(LOGIN_PAGE)?.kind, "login"); + await noteForumServiceOutcome(paths, url, { block: "challenge", error: "kiwifarms.st kept its browser check", channel: "kf-thread" }); + let state = await readServiceCookieState(paths); + assert.equal(isAlertRaised(state.services["kiwifarms.st"]), true); + assert.equal(state.services["kiwifarms.st"].evidence.url, url); + // A refusal (403/429) is not the session's cookies. + await noteForumServiceOutcome(paths, url, { block: "blocked", error: "refused" }); + const line = await noteForumServiceOutcome(paths, url, { channel: "kf-thread" }); + assert.match(line ?? "", /Kiwi Farms \(kiwifarms\.st\) answered cleanly/); + state = await readServiceCookieState(paths); + assert.equal(state.services["kiwifarms.st"].clearedBy, "clean"); + } finally { + await rm(paths.transcriptsDir, { recursive: true, force: true }); + } +}); + +test("archive.today: the client's check refusal raises the alert; a copy read clears it", async () => { + const paths = await tmpPaths(); + const at = await startFakeArchiveToday({ challenge: [AT_CHECKED_ID] }); + try { + let t = 1_000_000; + const c = new ArchiveTodayClient({ + fetch: at.fetch, + now: () => t, + sleep: async (ms: number) => { + t += ms; + }, + random: () => 0, + observe: (o) => noteArchiveTodayOutcome(paths, o), + }); + await assert.rejects(c.getCapture(`https://archive.ph/${AT_CHECKED_ID}`), /Connect archive session/); + let state = await readServiceCookieState(paths); + assert.equal(isAlertRaised(state.services["archive.today"]), true); + assert.equal(state.services["archive.today"].kind, "check-page"); + await c.listCaptures(AT_ARTICLE_URL); + state = await readServiceCookieState(paths); + assert.equal(state.services["archive.today"].clearedBy, "clean"); + } finally { + await at.close(); + await rm(paths.transcriptsDir, { recursive: true, force: true }); + } +}); + +test("dismiss and re-run marks", async () => { + const paths = await tmpPaths(); + try { + assert.equal(await dismissServiceCookieAlert(paths, "youtube"), false); + await noteServiceCookieSignal(paths, { service: "youtube", kind: "bot-check", line: "y" }); + assert.equal(await dismissServiceCookieAlert(paths, "youtube"), true); + let state = await readServiceCookieState(paths); + assert.equal(state.services.youtube.clearedBy, "dismiss"); + await markServiceCookieRerun(paths, "youtube", ["N1"]); + state = await readServiceCookieState(paths); + assert.deepEqual(state.services.youtube.rerunJobIds, ["N1"]); + assert.equal(await noteServiceCookieClean(paths, "youtube"), null, "already cleared"); + } finally { + await rm(paths.transcriptsDir, { recursive: true, force: true }); + } +}); + +test("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()), ytdlpBin: "yt-dlp" } as Parameters<typeof recheckServiceCookies>[0]["paths"]; + 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()), ytdlpBin: "yt-dlp" } as Parameters<typeof recheckServiceCookies>[0]["paths"]; + 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 }); + } +}); diff --git a/common/lib/serviceCookies-server.ts b/common/lib/serviceCookies-server.ts @@ -0,0 +1,303 @@ +// 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> { + const job = currentJobContext(); + 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/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,