// COOKIE REFRESH ALERTS — the file (plans/cookie-refresh-alerts.md): // `/.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 type { ChannelConfig } from "./channelConfig"; import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "./jsonFile-server"; import { currentJobContext } from "./jobContext"; import { getSettings } from "./settings"; import { detectPlatform } from "./platform"; import { ARCHIVE_TODAY_SERVICE, INSTAGRAM_SERVICE, X_SERVICE, applyServiceCookieClean, applyServiceCookieSignal, coerceServiceCookieState, forumServiceKey, isAlertRaised, isBlockingAlert, isYtdlpCookieService, noteLastGood, pruneServiceCookieState, rumbleMissingConfigLine, serviceCookieSignalFromStderr, serviceLabel, serviceStoppedLine, type ServiceCookieAction, type ServiceCookieEntry, type ServiceCookieSignal, type ServiceCookieState, type SignalContext, } from "./serviceCookies"; export const SERVICE_COOKIES_FILE = ".service-cookies.json"; export function serviceCookiesFile(paths: Pick): string { return path.join(paths.transcriptsDir, SERVICE_COOKIES_FILE); } export async function readServiceCookieState( paths: Pick, ): Promise { 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( paths: Pick, fn: (state: ServiceCookieState, now: number) => { changed: boolean; out: T }, now: number = Date.now(), ): Promise { 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, signal: ServiceCookieSignal, ctx: Omit = {}, opts: { now?: number; browser?: string } = {}, ): Promise { // A Recheck's own job is not one the alert stopped: it is the question. const ctxJob = currentJobContext(); const job = ctxJob?.kind === "recheck-service-cookies" ? undefined : ctxJob; try { const res = await mutate( paths, (state, now) => { const r = applyServiceCookieSignal( state, signal, { ...ctx, ...(job ? { jobId: job.jobId, jobKind: job.kind } : {}), ...(ctx.channel || !job?.channelSlug ? {} : { channel: job.channelSlug }), }, now, ); return { changed: true, out: { ...r, raised: isAlertRaised(r.entry) } }; }, opts.now, ); if (res.raised && job && !job.staleServices.has(signal.service)) { job.staleServices.add(signal.service); job.onLog(`${serviceStoppedLine(signal.service, opts.browser ?? configuredCookieBrowser(), res.entry.kind)}\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, service: string, good?: { url: string; channel?: string }, opts: { now?: number; by?: NonNullable } = {}, ): Promise { 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, service: string, now: number, ): Promise { 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. // A Rumble 403 on a channel whose config lacks what Rumble needs: the job's // log names the missing keys (rumbleMissingConfigLine) instead of a bare exit // code. Reads the channel's config.json beside the transcripts; never throws. async function logRumbleConfigProblem( paths: Pick, stderr: string, platform: string | null | undefined, channel: string | undefined, ): Promise { if (platform !== "rumble" || !channel) return; try { const read = await readJsonFile(path.join(paths.transcriptsDir, "channels", channel, "config.json")); if (!read.ok || typeof read.value !== "object" || read.value === null) return; const line = rumbleMissingConfigLine(stderr, channel, read.value as ChannelConfig); if (line) currentJobContext()?.onLog(line); } catch { // bookkeeping only } } export async function observeYtdlpServiceOutcome( paths: Pick, run: { url: string; channel?: string; exitCode: number | null; stderrTail: string; aborted?: boolean }, ): Promise { 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; } await logRumbleConfigProblem(paths, run.stderrTail, platform, run.channel); 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, stderr: string, ctx: { url?: string; channel?: string; platform?: string | null } = {}, ): Promise { const platform = ctx.platform ?? (ctx.url ? detectPlatform(ctx.url) : null); await logRumbleConfigProblem(paths, stderr, platform, ctx.channel); const signal = serviceCookieSignalFromStderr(stderr, platform); 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, threadUrl: string, outcome: { block?: string; error?: string; channel?: string }, ): Promise { 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, outcome: { challenge: true; url: string; line: string } | { challenge: false; url: string }, ): Promise { 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, service: string, now: number = Date.now(), ): Promise { 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, service: string, jobIds: string[], now: number = Date.now(), ): Promise { 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, ); } // The last press on a service's own button and how it ended (the /cookies // screen's "last result"). Never throws: a press is not failed by its // bookkeeping. export async function noteServiceCookieAction( paths: Pick, service: string, action: Omit, now: number = Date.now(), ): Promise { await mutate( paths, (state, at) => { (state.actions ??= {})[service] = { at: new Date(at).toISOString(), ...action, message: action.message.slice(0, 600) }; return { changed: true, out: undefined }; }, now, ).catch(() => undefined); } // ── X (plans/pacing-guard.md) ───────────────────────────────────────────── // One gallery-dl run against X: a challenge or login-wall line raises the X // alert (one is enough); a run that read without one is a clean request. Never // throws. Answers the line for the job log when a clean request cleared it. export async function noteXServiceOutcome( paths: Pick, outcome: { challengeLine?: string; kind?: "challenge" | "auth-failure"; url?: string; channel?: string }, ): Promise { return noteBlockingServiceOutcome(paths, X_SERVICE, outcome); } // One gallery-dl run against Instagram, the same way: a redirect to its // login, challenge or checkpoint page raises Instagram's alert (one is // enough), which refuses every Instagram job until a person's Recheck. export async function noteInstagramServiceOutcome( paths: Pick, outcome: { challengeLine?: string; kind?: "challenge" | "auth-failure" | "refusal"; url?: string; channel?: string }, ): Promise { return noteBlockingServiceOutcome(paths, INSTAGRAM_SERVICE, outcome); } async function noteBlockingServiceOutcome( paths: Pick, service: string, outcome: { challengeLine?: string; kind?: "challenge" | "auth-failure" | "refusal"; url?: string; channel?: string }, ): Promise { try { if (outcome.challengeLine) { await noteServiceCookieSignal( paths, { service, kind: outcome.kind ?? "challenge", line: outcome.challengeLine.trim().slice(0, 300) }, { ...(outcome.url ? { url: outcome.url } : {}), ...(outcome.channel ? { channel: outcome.channel } : {}), }, ); return null; } const now = Date.now(); if (!(await cleanWouldChange(paths, service, now))) return null; return await noteServiceCookieClean( paths, service, outcome.url ? { url: outcome.url, ...(outcome.channel ? { channel: outcome.channel } : {}) } : undefined, { now }, ); } catch { return null; } } // The raised (not cleared) alert of `service`, or null. Never throws. export async function raisedServiceAlert( paths: Pick, service: string, ): Promise { try { const e = (await readServiceCookieState(paths)).services[service]; return isAlertRaised(e) ? e! : null; } catch { return null; } } // A job the raised alert REFUSED before it started (common/jobs/networkGuard.ts): // recorded against the alert, without counting as a signal, so "Re-run stopped // jobs" offers it once the alert clears. Never throws. export async function noteServiceStoppedJob( paths: Pick, service: string, job: { id: string; kind?: string }, now: number = Date.now(), ): Promise { try { await mutate( paths, (state) => { const e = state.services[service]; if (!isAlertRaised(e) || e!.jobs.some((j) => j.id === job.id)) return { changed: false, out: undefined }; e!.jobs = [...e!.jobs, { id: job.id, ...(job.kind ? { kind: job.kind } : {}) }].slice(-20); return { changed: true, out: undefined }; }, now, ); } catch { // bookkeeping only } } // ── X's jar age (the fresh-jar rule as a banner) ────────────────────────── // X WORK WAS REFUSED, OR IS WAITING, ON AN OLD JAR: the fresh-jar rule refused // an X job (jobs/networkGuard.ts — at enqueue, or at its start: then `job` is // recorded for "Re-run stopped jobs"), or the recheck timer found X jobs // queued on a jar past its limit. Raises (or keeps) X's "jar-age" alert — one // is enough. A no-op while a BLOCKING X alert (a challenge, a login failure) is // up: that one already says more, and its sentence must not be overwritten. // Never throws; answers whether the alert is up after it. export async function noteXJarStale( paths: Pick, info: { line: string; channel?: string; job?: { id: string; kind?: string } }, now: number = Date.now(), ): Promise { try { return await mutate( paths, (state, at) => { const e = state.services[X_SERVICE]; if (isBlockingAlert(e)) { if (info.job && !e!.jobs.some((j) => j.id === info.job!.id)) { e!.jobs = [...e!.jobs, { id: info.job.id, ...(info.job.kind ? { kind: info.job.kind } : {}) }].slice(-20); return { changed: true, out: true }; } return { changed: false, out: true }; } const r = applyServiceCookieSignal( state, { service: X_SERVICE, kind: "jar-age", line: info.line.trim().slice(0, 300) }, { ...(info.job ? { jobId: info.job.id, ...(info.job.kind ? { jobKind: info.job.kind } : {}) } : {}), ...(info.channel ? { channel: info.channel } : {}), }, at, ); return { changed: true, out: isAlertRaised(r.entry) }; }, now, ); } catch { return false; } } // X's jar is FRESH again (the guard let an X job through, the timer or a // Recheck re-read it): a raised jar-age alert clears — "OK again", with the // jobs it stopped offered for re-run. Any other X alert is left alone (only // Recheck, Dismiss or a clean gallery-dl run clears a challenge). A cheap // unlocked peek first, so the guard's every X job costs one read. Never // throws; answers the job-log line when it cleared one. export async function noteXJarFresh( paths: Pick, opts: { now?: number; by?: "clean" | "recheck" } = {}, ): Promise { try { const peek = (await readServiceCookieState(paths)).services[X_SERVICE]; if (!isAlertRaised(peek) || peek!.kind !== "jar-age") return null; return await mutate( paths, (state, now) => { const e = state.services[X_SERVICE]; if (!isAlertRaised(e) || e!.kind !== "jar-age") return { changed: false, out: null }; applyServiceCookieClean(state, X_SERVICE, now, opts.by ?? "clean"); return { changed: true, out: "X's cookie jar is fresh again: its cookie alert is cleared.\n" }; }, opts.now, ); } catch { return null; } }