// 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). // x NO REQUEST (plans/pacing-guard.md): after a // challenge the next request to X is the one // that gets an account locked. Clean when the // login was renewed AFTER the alert was raised — // the profile's jar re-exported (Refresh cookies // on /cookies) with a login in it, or, with the // browser source, the browser's x.com auth_token // last sent since — read from disk only. // A "jar-age" alert (the fresh-jar rule's // banner) is clean when the jar is within // social.x.maxCookieAgeMinutes again. // // 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, noteXJarFresh, readServiceCookieState, } from "../lib/serviceCookies-server"; import type { XJarStatusView } from "../lib/serviceCookies"; import { recordPlatformClean } from "../jobs/downloadBackoff"; import { runOneYtdlp, type AttemptOutcome } from "../ytdlp/runOneYtdlp"; import { channelExtraArgs, configForVideoUrl, pacedPlatformArgs, withBrowserUserAgent } 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; // 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; readChannelConfig: (paths: Paths, slug: string) => Promise; cookieSpec: (config: ChannelConfig | null) => string | undefined; recordPlatformClean: (platform: string, paths: Paths) => Promise; // X's login, read from disk (no request): the source in use, when it was // last renewed, and whether it holds a login. xLogin: (paths: Paths) => Promise<{ source: "browser" | "profile"; renewedAt?: string; loggedIn: boolean; browser?: string }>; // X's jar age against the limit, read from disk (social/xJarAge.ts). xJar: (paths: Paths) => Promise; }; 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), xLogin: async (p) => { const { readXLoginStatus } = await import("../social/xBrowserLogin"); const login = await readXLoginStatus(p, getSettings()); return { source: login.source, ...(login.lastSeenAt ? { renewedAt: login.lastSeenAt } : {}), loggedIn: login.authTokenVisible === true, ...(login.browserSpec ? { browser: login.browserSpec } : {}), }; }, xJar: async (p) => { const { readXJarAge } = await import("../social/xJarAge"); const { resolvedXMaxCookieAgeMinutes } = await import("../jobs/networkGuard"); const settings = getSettings(); return readXJarAge(p, settings, { maxAgeMinutes: resolvedXMaxCookieAgeMinutes(settings), fresh: true }); }, }); // 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) : withBrowserUserAgent([...cookieArgs(cookies), ...pacedPlatformArgs(platform)], 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; // Ask THIS request instead of the last clean one (the timer's second, // different known-good video — controller/serviceCookieTimer.ts). target?: { url: string; channel?: string }; }): Promise { 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 = opts.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 => { 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}` + (opts.target ? " (an earlier clean request)" : 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 "x": { if (entry?.kind === "jar-age" && !entry.clearedAt) { let jar: XJarStatusView; try { jar = await deps.xJar(paths); } catch (e) { return out("failed", `Could not read X's cookie jar: ${(e as Error).message}. The alert stays.`); } log(`Rechecking ${label}: the cookie jar's age on disk, no request to X.`); if (jar.fresh) { await noteXJarFresh(paths, { by: "recheck" }); return out("clean", `${label}'s cookie jar is fresh (${jar.summary}) — its cookie alert is cleared; no request sent.`); } return out("stale", `${jar.summary} Recheck sends X no request.`); } const raisedAt = entry?.raisedAt ?? entry?.since; let login: Awaited>; try { login = await deps.xLogin(paths); } catch (e) { return out("failed", `Could not read X's login: ${(e as Error).message}. The alert stays.`); } log(`Rechecking ${label}: the login on disk, no request to X (the ${login.source === "profile" ? "connected profile's cookie jar" : "browser's cookie store"}).`); const renewed = !!login.renewedAt && (!raisedAt || Date.parse(login.renewedAt) > Date.parse(raisedAt)); if (login.loggedIn && renewed) { return clean(`login renewed ${login.renewedAt!.slice(11, 16)} UTC, after the challenge; no request sent`); } const at = raisedAt ? ` at ${raisedAt.slice(11, 16)} UTC` : ""; return out( "stale", login.source === "profile" ? `${label}'s cookie jar has not been re-exported with a login since the challenge${at}: pass X's check by hand ` + "(Connect X account on /cookies), press Refresh cookies there, then Recheck. Recheck sends X no request." : `The browser's X login has not been used since the challenge${at}: open x.com in ` + `${login.browser ?? "the browser cookiesFromBrowser names"}, pass its check, then Recheck. Recheck sends X no request.`, ); } case "instagram": { // THE OPERATOR'S WORD, and no request: nothing on disk says whether // Instagram's check is passed (slice 1 keeps no Instagram jar), so a // Recheck is a person saying it is. The timer never comes here // (serviceCookieTimer.ts holdBack). if (!entry?.raisedAt || entry.clearedAt) { return out("clean", `${label} has no cookie alert up. Recheck sends Instagram no request.`); } log(`Rechecking ${label}: your word that its check is passed, no request to Instagram.`); return clean("on your word; no request sent. If the check was not passed, the next Instagram job raises it again"); } 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); } } }