// 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, X's challenge or login // wall (plans/pacing-guard.md). 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"; import type { ChannelConfig } from "./channelConfig"; import { RUMBLE_NEEDS_TEXT, rumbleMissingKeys } from "./rumbleDefaults"; // "auth-failure": X's login refused or gone (gallery-dl's AuthRequired, a 401, // "Could not authenticate you" — social/xGalleryDlSignals.ts). "jar-age": X's // cookie jar older than `social.x.maxCookieAgeMinutes` while X work wants to // run (an X job refused for it, or X jobs queued) — the one kind that is NOT a // request's answer, raised from a clock and a file's age, and the one X kind // that does not itself refuse X jobs (the fresh-jar rule already does). // "refusal": Instagram answered a read with a 401 or a 403 (its "please wait a // few minutes"). ONE is a rate limit and holds Instagram for an hour; a // SECOND with no clean read between raises the alert — an account being // refused hour after hour needs a person, not another hourly try. export type ServiceCookieKind = "embed-403" | "bot-check" | "challenge" | "check-page" | "auth-failure" | "jar-age" | "refusal"; export const SERVICE_COOKIE_KINDS: readonly ServiceCookieKind[] = [ "embed-403", "bot-check", "challenge", "check-page", "auth-failure", "jar-age", "refusal", ]; // 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"; // X (plans/pacing-guard.md): a Cloudflare challenge, a 401/403 or a login wall // in gallery-dl's output. Unlike every other service, WHILE ITS ALERT IS UP NO // X JOB STARTS (common/jobs/networkGuard.ts) — X answered a burst with a // human verification on the account once, and the next request after a // challenge is the one that gets an account locked. export const X_SERVICE = "x"; // Instagram (lane instagram): a redirect to its login, challenge or checkpoint // page in gallery-dl's output. Like X's, WHILE ITS ALERT IS UP NO INSTAGRAM // JOB STARTS (common/jobs/networkGuard.ts) — and unlike every other service // nothing clears it but a person: Recheck (or Dismiss) on the dashboard, which // sends Instagram no request. The recheck timer never asks it. export const INSTAGRAM_SERVICE = "instagram"; export type ServiceFamily = "ytdlp" | "forum" | "archive" | "x" | "instagram"; 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 || s === X_SERVICE || s === INSTAGRAM_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"; if (service === X_SERVICE) return "x"; if (service === INSTAGRAM_SERVICE) return "instagram"; 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"; case X_SERVICE: return "X"; case INSTAGRAM_SERVICE: return "Instagram"; 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, kind?: ServiceCookieKind): string { const b = browserName(browser); if (service === X_SERVICE && kind === "jar-age") { return ( "press Refresh cookies (or Connect X account) on /cookies for a fresh X cookie jar — with the browser " + `login, open x.com in ${b} — then Recheck; nothing is asked of X until then` ); } 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 on /cookies and pass the check once in the window (it opens on the editor's machine)"; case X_SERVICE: return ( "pass X's check by hand — Connect X account on /cookies and clear it in the window (with the " + "browser login: open x.com in that browser) — then press Refresh cookies there; no X job starts until then" ); case INSTAGRAM_SERVICE: return ( "pass Instagram's check by hand, in the browser (or with the cookies file's account) the channel's " + "cookie source names, then press Recheck on the dashboard; no Instagram job starts until then, and " + "Recheck sends Instagram no request" ); 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, kind?: ServiceCookieKind): string { return `stopped: ${serviceLabel(service)} cookies look stale — ${serviceFixText(service, browser, kind)}, 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; } // ── a Rumble channel missing the config Rumble needs ───────────────────── // Any Rumble extractor's 403 ([RumbleChannel] a listing, [RumbleEmbed] an embed, // [Rumble] a page). A 403 alone is ambiguous (a removed video answers it too), // so this never raises an alert: it only NAMES the channel's own missing config // when there is some, in place of a bare exit code. The channel's config is the // source of truth (rumbleMissingKeys). const RUMBLE_ANY_403 = /\[Rumble(?:Channel|Embed)?\][^\n]*HTTP Error 403/; export function rumbleMissingConfigLine( stderr: string, slug: string, config: Pick | null | undefined, ): string | null { if (!stderr || !config || !RUMBLE_ANY_403.test(stderr)) return null; const missing = rumbleMissingKeys(config); if (missing.length === 0) return null; return `Rumble refused (HTTP 403): ${slug} has ${missing.join(", ")}; ${RUMBLE_NEEDS_TEXT} (Configure → Cookies from browser, Cookie mode, Extra yt-dlp args).`; } // ── 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 — and the one // before it for a DIFFERENT URL (`prev`): the proactive timer's second, // different known-good video when the first answers Rumble's ambiguous 403. export type ServiceCookieLastGood = { url: string; channel?: string; at: string; prev?: { url: string; channel?: string; at: string }; }; // The last press on a service's own button (the /cookies screen's Refresh, // Connect or Check again; the dashboard's Recheck; settings' Refresh cookies): // what was pressed, when, and how it ended. Written by the one guard every // such press goes through (editor/app/lib/cookieRefreshGuard.ts). export type ServiceCookieActionKind = "refresh" | "connect" | "recheck"; export const SERVICE_COOKIE_ACTION_KINDS: readonly ServiceCookieActionKind[] = ["refresh", "connect", "recheck"]; export type ServiceCookieAction = { at: string; action: ServiceCookieActionKind; ok: boolean; // A recheck's answer. result?: "clean" | "stale" | "failed"; message: string; jobId?: string; }; export type ServiceCookieState = { version: 1; services: Record; lastGood: Record; // Absent until a press is recorded (an older file has none). actions?: Record; }; export const PENDING_SIGNAL_TTL_MS = 60 * 60_000; // A pending refusal outlives the hour's hold it came with, or its second // could never be "in a row". export const PENDING_REFUSAL_TTL_MS = 24 * 60 * 60_000; export function pendingSignalTtlMs(kind: ServiceCookieKind): number { return kind === "refusal" ? PENDING_REFUSAL_TTL_MS : PENDING_SIGNAL_TTL_MS; } 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" || kind === "refusal" ? 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; const services = r.services && typeof r.services === "object" ? (r.services as Record) : {}; for (const [key, v] of Object.entries(services)) { if (!isServiceKey(key) || !v || typeof v !== "object") continue; const e = v as Record; 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) : {}; 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) : {}; for (const [key, v] of Object.entries(lastGood)) { if (!isServiceKey(key) || !v || typeof v !== "object") continue; const g = v as Record; const url = str(g.url); const at = iso(g.at); if (!url || !at) continue; const channel = str(g.channel, 200); const p = g.prev && typeof g.prev === "object" ? (g.prev as Record) : null; const prevUrl = p ? str(p.url) : undefined; const prevAt = p ? iso(p.at) : undefined; const prevChannel = p ? str(p.channel, 200) : undefined; out.lastGood[key] = { url, at, ...(channel ? { channel } : {}), ...(prevUrl && prevAt && prevUrl !== url ? { prev: { url: prevUrl, at: prevAt, ...(prevChannel ? { channel: prevChannel } : {}) } } : {}), }; } const actions = r.actions && typeof r.actions === "object" ? (r.actions as Record) : null; if (actions) { for (const [key, v] of Object.entries(actions)) { if (!isServiceKey(key) || !v || typeof v !== "object") continue; const a = v as Record; const at = iso(a.at); const action = SERVICE_COOKIE_ACTION_KINDS.includes(a.action as ServiceCookieActionKind) ? (a.action as ServiceCookieActionKind) : null; if (!at || !action) continue; const result = a.result === "clean" || a.result === "stale" || a.result === "failed" ? a.result : undefined; const jobId = str(a.jobId, 200); (out.actions ??= {})[key] = { at, action, ok: a.ok === true, message: str(a.message, 600) ?? "", ...(result ? { result } : {}), ...(jobId ? { jobId } : {}), }; } } return out; } export function isAlertRaised(e: ServiceCookieEntry | undefined): boolean { return !!e?.raisedAt && !e.clearedAt; } // A raised alert that REFUSES the service's jobs (jobs/networkGuard.ts — X // and Instagram): every raised kind but jar-age, whose refusal is the fresh-jar rule's // own and which clears the moment the jar is fresh. export function isBlockingAlert(e: ServiceCookieEntry | undefined): boolean { return isAlertRaised(e) && e!.kind !== "jar-age"; } 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) > pendingSignalTtlMs(entry.kind); // A raised jar-age alert that meets a real answer from X (a challenge, a // login wall) is ESCALATED to it — that kind refuses every X job, jar-age // does not — keeping the jobs it already holds for "Re-run stopped jobs". const escalate = !!entry?.raisedAt && !entry.clearedAt && entry.kind === "jar-age" && signal.kind !== "jar-age"; const carriedJobs = escalate ? entry!.jobs : []; // 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 || escalate || (!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: [...carriedJobs], }; 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 = "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; const older = prev && prev.url !== good.url ? { url: prev.url, at: prev.at, ...(prev.channel ? { channel: prev.channel } : {}) } : prev?.prev; state.lastGood[service] = { url: good.url, at: new Date(now).toISOString(), ...(good.channel ? { channel: good.channel } : {}), ...(older ? { prev: older } : {}), }; 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) > pendingSignalTtlMs(e.kind)); 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[]; // Drawn as headline + `fix` (one action line) + `detail` when it is not // empty — no evidence line (X's jar-age banner). compact?: boolean; rerunAt?: string; rerunJobIds?: string[]; }; // X's cookie jar, read from disk (no request): the profile's exported jar's // mtime, or — with the browser login — when Firefox last sent its x.com // auth_token (social/xJarAge.ts). Served beside the alerts whether or not one // is up, so `pnpm ops get services` always says how fresh X's login is. export type XJarStatusView = { source: "profile" | "browser"; // When the login was last renewed (ISO), when it could be read. at: string | null; ageMinutes: number | null; // social.x.maxCookieAgeMinutes, resolved (0 = no limit). maxAgeMinutes: number; // An auth_token is in the source (null: the source could not be read). loggedIn: boolean | null; // Within the limit (or no limit) and logged in: an X job may start on it. fresh: boolean; readAt: string; summary: string; }; // The proactive recheck timer (controller/serviceCookieTimer.ts), when this // process armed it. export type ServiceCookieTimerView = { // settings.serviceCookies.recheckIntervalMinutes (0 = off). intervalMinutes: number; armed: boolean; lastTickAt?: string; nextTickAt?: string; // What the last tick did, per service it looked at. last?: { service: string; action: string; message: 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 }[]; x?: XJarStatusView; timer?: ServiceCookieTimerView; }; const STOPPED_STATUSES = new Set(["failed", "cancelled"]); // "45 min", "3 h", "16 days". function jarAgeText(min: number): string { if (min < 120) return `${min} min`; const h = Math.floor(min / 60); return h < 48 ? `${h} h` : `${Math.floor(h / 24)} days`; } 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"}`; case "auth-failure": return `${count} login failure${count === 1 ? "" : "s"}`; case "jar-age": return "cookie jar past its age limit"; case "refusal": return `${count} refusal${count === 1 ? "" : "s"} (401/403) in a row`; } } // 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; // X's jar as read from disk: a jar-age banner's headline says its age, and // its one action line matches the login source in use. xJar?: Pick; }, ): 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) <= pendingSignalTtlMs(e.kind)) { 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, e.kind); 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; // X's jar-age banner is THREE SHORT LINES, no lead paragraph (operator's UI // rule): how old the jar is, the one thing to do for the login source in // use, and which job it refused when it refused one. if (stale && e.kind === "jar-age") { const jar = opts.xJar; const age = jar?.ageMinutes != null ? jarAgeText(jar.ageMinutes) : null; const limit = jar && jar.maxAgeMinutes > 0 ? ` (limit ${jar.maxAgeMinutes} min)` : ""; const action = jar?.source === "browser" ? `Open x.com in ${browserName(opts.browser).replace(/^[a-z]/, (c) => c.toUpperCase())} — then Recheck.` : "Refresh cookies (or Connect X account) on /cookies — then Recheck."; const queued = /^(\d+ X jobs? (?:is|are) queued)/.exec(e.evidence.line)?.[1]; const refused = job ? `Refused ${job.kind ? `${job.kind} ` : ""}${job.id}${e.evidence.channel ? ` (${e.evidence.channel})` : ""}.` : e.evidence.channel ? `Refused an X job on ${e.evidence.channel}.` : queued ? `${queued}.` : ""; alerts.push({ service: e.service, label, family: serviceFamily(e.service), state: "stale", kind: e.kind, since: e.since, raisedAt: e.raisedAt, lastSeen: e.lastSeen, count: e.count, videos: e.videos, evidence: e.evidence, fix: action, headline: age ? `${label} cookies are ${age} old${limit}` : `${label} cookies are past their age limit${limit}`, detail: refused, compact: true, canRecheck: true, stoppedJobs, }); continue; } 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" || serviceFamily(e.service) === "x" || serviceFamily(e.service) === "instagram" || !!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 }; }