commit 39b82e85c3aeede0dfb8b5b5f316350fec90a2dc
parent 70e85ecd80886114c1b7be24deb28814e6d72905
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 31 Oct 2026 23:55:12 -0400
common: X cookie banner like Rumble's — gallery-dl lines classified (challenge / login failure / rate limit / one account), the fresh-jar rule raises an X "jar-age" alert, its age read from disk by name
- social/xGalleryDlSignals.ts: one classifier for gallery-dl's real messages. AuthRequired ("authenticated cookies needed"), AuthenticationError, "Could not authenticate you", 401, an API 403 and a locked account are a login failure (new alert kind auth-failure); a 429 / rate limit is pacing and never raises the alert; a protected or blocking account, an NSFW/protected tweet and a twimg.com media 403 are one account's refusal, not the login (they used to raise X's alert and stop every X job).
- serviceCookies: kinds auth-failure and jar-age; a raised jar-age escalates to a real challenge (keeping its jobs); isBlockingAlert (jar-age never refuses by itself).
- networkGuard: a fresh-jar refusal raises the jar-age banner (the job refused at its start is recorded for Re-run stopped jobs); a jar that passes clears it.
- social/xJarAge.ts: the profile jar's mtime, or Firefox's x.com auth_token lastAccessed selected by name only (never the value) from a private copy of cookies.sqlite + WAL.
- Recheck for a jar-age alert re-reads the age; no request to X.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
12 files changed, 874 insertions(+), 47 deletions(-)
diff --git a/common/controller/recheckServiceCookies.test.ts b/common/controller/recheckServiceCookies.test.ts
@@ -161,3 +161,75 @@ test("Recheck (X): no request to X — stale until the login is renewed after th
await rm(paths.transcriptsDir, { recursive: true, force: true });
}
});
+
+test("Recheck (X, jar-age): the jar's age on disk, no request — stale while old, clean once fresh; a challenge is never overwritten by it", async () => {
+ const paths = await tmpPaths();
+ try {
+ const { noteXJarStale, noteXJarFresh, noteXServiceOutcome } = await import("../lib/serviceCookies-server");
+ assert.equal(await noteXJarStale(paths, { line: "X cookies were last refreshed 3 h ago (limit 60 min): …", channel: "ember-x", job: { id: "J1", kind: "fetch-posts" } }), true);
+ let x = (await readServiceCookieState(paths)).services.x;
+ assert.equal(x?.kind, "jar-age");
+ assert.deepEqual(x?.jobs, [{ id: "J1", kind: "fetch-posts" }]);
+ const asked: string[] = [];
+ let fresh = false;
+ const deps = {
+ runYtdlp: async () => {
+ asked.push("yt-dlp");
+ return { exitCode: 0, stderrTail: "", archiveLine: null };
+ },
+ xLogin: async () => {
+ asked.push("login");
+ return { source: "profile" as const, loggedIn: true };
+ },
+ xJar: async () => ({
+ source: "profile" as const,
+ at: new Date().toISOString(),
+ ageMinutes: fresh ? 1 : 180,
+ maxAgeMinutes: 60,
+ loggedIn: true,
+ fresh,
+ readAt: new Date().toISOString(),
+ summary: fresh ? "The X cookie jar was written 1 min ago (limit 60 min)." : "The X cookie jar was written 3 h ago (limit 60 min): press Refresh cookies (or Connect X account) on /settings.",
+ }),
+ };
+ const stale = await recheckServiceCookies({ paths, service: "x", deps });
+ assert.equal(stale.result, "stale");
+ assert.match(stale.message, /3 h ago .*Recheck sends X no request\.$/);
+ fresh = true;
+ const clean = await recheckServiceCookies({ paths, service: "x", deps });
+ assert.equal(clean.result, "clean");
+ x = (await readServiceCookieState(paths)).services.x;
+ assert.equal(x?.clearedBy, "recheck");
+ assert.deepEqual(asked, [], "neither yt-dlp nor the challenge path was asked");
+ // Nothing raised: fresh is a no-op.
+ assert.equal(await noteXJarFresh(paths), null);
+
+ // A challenge is up: the jar-age path records the job but never replaces it.
+ await noteXServiceOutcome(paths, { challengeLine: "[twitter][warning] Cloudflare challenge", kind: "challenge" });
+ assert.equal(await noteXJarStale(paths, { line: "old jar", job: { id: "J2" } }), true);
+ x = (await readServiceCookieState(paths)).services.x;
+ assert.equal(x?.kind, "challenge");
+ assert.equal(x?.evidence.line, "[twitter][warning] Cloudflare challenge");
+ assert.deepEqual(x?.jobs.map((j) => j.id), ["J2"]);
+ assert.equal(await noteXJarFresh(paths), null, "a fresh jar does not clear a challenge");
+ assert.equal(isAlertRaised((await readServiceCookieState(paths)).services.x), true);
+ } finally {
+ await rm(paths.transcriptsDir, { recursive: true, force: true });
+ }
+});
+
+test("X's login failure is its own kind: an auth-failure alert, worded so", async () => {
+ const paths = await tmpPaths();
+ try {
+ const { noteXServiceOutcome } = await import("../lib/serviceCookies-server");
+ await noteXServiceOutcome(paths, { challengeLine: "[twitter][error] AuthRequired: authenticated cookies needed to access this timeline", kind: "auth-failure" });
+ const x = (await readServiceCookieState(paths)).services.x;
+ assert.equal(x?.kind, "auth-failure");
+ assert.equal(isAlertRaised(x), true);
+ const { buildServiceCookieAlerts } = await import("../lib/serviceCookies");
+ const view = buildServiceCookieAlerts(await readServiceCookieState(paths), { now: Date.now() });
+ assert.match(view.alerts[0]?.detail ?? "", /^1 login failure since /);
+ } finally {
+ await rm(paths.transcriptsDir, { recursive: true, force: true });
+ }
+});
diff --git a/common/controller/recheckServiceCookies.ts b/common/controller/recheckServiceCookies.ts
@@ -22,6 +22,9 @@
// on /settings) 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
@@ -43,8 +46,10 @@ import {
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";
@@ -77,6 +82,8 @@ export type RecheckDeps = {
// 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<XJarStatusView>;
};
const defaultDeps = (paths: Paths): RecheckDeps => ({
@@ -116,6 +123,12 @@ const defaultDeps = (paths: Paths): RecheckDeps => ({
...(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
@@ -217,6 +230,20 @@ export async function recheckServiceCookies(opts: {
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<ReturnType<RecheckDeps["xLogin"]>>;
try {
diff --git a/common/jobs/networkGuard.ts b/common/jobs/networkGuard.ts
@@ -30,6 +30,8 @@ import { serviceFixText, X_SERVICE } from "../lib/serviceCookies";
import {
configuredCookieBrowser,
noteServiceStoppedJob,
+ noteXJarFresh,
+ noteXJarStale,
raisedServiceAlert,
} from "../lib/serviceCookies-server";
import {
@@ -150,6 +152,11 @@ function e2eDefaultMaxAge(): number | undefined {
return Number.isFinite(n) && n >= 0 ? Math.floor(n) : undefined;
}
+// social.x.maxCookieAgeMinutes as every X reader applies it (0 = off).
+export function resolvedXMaxCookieAgeMinutes(settings: Pick<SiteSettings, "social"> | null): number {
+ return settings?.social?.x?.maxCookieAgeMinutes ?? e2eDefaultMaxAge() ?? xMaxCookieAgeMinutes(settings?.social?.x);
+}
+
function settingsNow(): SiteSettings | null {
try {
return getSettings();
@@ -214,8 +221,7 @@ export async function xSessionReport(opts: {
browserSpec: settings ? await channelCookieSpec(opts.paths, opts.channelSlug, settings) : undefined,
profileConnected: status.looksAuthenticated,
});
- const maxAgeMinutes =
- settings?.social?.x?.maxCookieAgeMinutes ?? e2eDefaultMaxAge() ?? xMaxCookieAgeMinutes(settings?.social?.x);
+ const maxAgeMinutes = resolvedXMaxCookieAgeMinutes(settings);
const ageMinutes = status.cookiesUpdatedAt
? Math.max(0, Math.floor((now - Date.parse(status.cookiesUpdatedAt)) / 60_000))
: null;
@@ -233,15 +239,19 @@ export async function xSessionReport(opts: {
maxAgeMinutes,
ageChecked: resolved.source === "profile" && maxAgeMinutes > 0,
};
+ // A raised jar-age alert does not refuse by itself: it IS the fresh-jar
+ // rule's banner, and the rule below decides (and clears it once the jar is
+ // fresh — guardNetworkJob).
const raised = await raisedServiceAlert(opts.paths, X_SERVICE);
- if (raised) {
+ if (raised && raised.kind !== "jar-age") {
const at = (raised.raisedAt ?? raised.since).slice(11, 16);
+ const what = raised.kind === "auth-failure" ? "a login failure" : "a challenge";
return {
...base,
alert: { raisedAt: raised.raisedAt ?? raised.since, line: raised.evidence.line },
allowed: false,
reason:
- `X answered with a challenge at ${at} UTC (${raised.evidence.line}) and its cookie alert is up, ` +
+ `X answered with ${what} at ${at} UTC (${raised.evidence.line}) and its cookie alert is up, ` +
`so no X job starts: ${serviceFixText(X_SERVICE, configuredCookieBrowser())}, then Recheck on the dashboard.`,
};
}
@@ -280,9 +290,22 @@ export async function guardNetworkJob(
const platform = await networkJobPlatform(opts);
if (platform !== "twitter") return { ok: true, notes: [] };
const x = await xJobGuard({ paths: opts.paths, channelSlug: opts.channelSlug });
- if (x.ok) return { ok: true, notes: x.note ? [x.note] : [] };
+ if (x.ok) {
+ // The jar passed: a jar-age banner from an earlier refusal clears.
+ await noteXJarFresh(opts.paths);
+ return { ok: true, notes: x.note ? [x.note] : [] };
+ }
if (x.alert && opts.job) {
await noteServiceStoppedJob(opts.paths, X_SERVICE, { id: opts.job.id, kind: opts.kind });
+ } else if (!x.alert) {
+ // The fresh-jar rule refused it: X's cookie banner says so on the
+ // dashboard (kind jar-age), and a job refused at its start is offered for
+ // "Re-run stopped jobs" once the jar is fresh.
+ await noteXJarStale(opts.paths, {
+ line: x.message,
+ ...(opts.channelSlug ? { channel: opts.channelSlug } : {}),
+ ...(opts.job ? { job: { id: opts.job.id, kind: opts.kind } } : {}),
+ });
}
return { ok: false, error: x.message };
}
diff --git a/common/jobs/pacingGuard.test.ts b/common/jobs/pacingGuard.test.ts
@@ -234,6 +234,59 @@ test("a stale jar is refused at enqueue, and at the start of a job queued while
assert.match(c.ok ? "" : c.error, /holds no login/);
});
+test("the fresh-jar rule raises X's jar-age banner (the job refused at its start is on it); a fresh jar clears it; a challenge escalates it", async () => {
+ await reset();
+ const { buildServiceCookieAlerts, isBlockingAlert } = await import("../lib/serviceCookies");
+ // Refused at enqueue: the banner goes up, no job to re-run.
+ await writeJar(3 * 60 * 60_000);
+ const refused = await fetchJob(SLUGS[0], new Map());
+ assert.equal(refused.ok, false);
+ let x = (await readServiceCookieState(paths)).services.x;
+ assert.ok(x?.raisedAt && !x.clearedAt, "the X banner is up");
+ assert.equal(x.kind, "jar-age");
+ assert.equal(isBlockingAlert(x), false, "jar-age does not itself refuse X jobs");
+ assert.match(x.evidence.line, /^X cookies were last refreshed 3 h ago \(limit 60 min\)/);
+ assert.equal(x.evidence.channel, SLUGS[0]);
+ assert.deepEqual(x.jobs, []);
+
+ // Queued while fresh, refused at its start: recorded on the banner.
+ await writeJar(5 * 60_000);
+ let release!: () => void;
+ const held = new Promise<void>((r) => (release = r));
+ const a = await runManagedFunction({ kind: "fetch-posts", queueKey: "platform:twitter", paths, channelSlug: SLUGS[0], fn: () => held });
+ assert.ok(a.ok);
+ // The guard let job a through on a fresh jar: the banner is OK again.
+ x = (await readServiceCookieState(paths)).services.x;
+ assert.equal(x?.clearedBy, "clean");
+ const b = await fetchJob(SLUGS[1], new Map());
+ assert.ok(b.ok);
+ await writeJar(2 * 60 * 60_000);
+ release();
+ await a.done;
+ const bDone = await b.done;
+ assert.equal(bDone.status, "failed");
+ x = (await readServiceCookieState(paths)).services.x;
+ assert.ok(x?.raisedAt && !x.clearedAt);
+ assert.equal(x.kind, "jar-age");
+ assert.deepEqual(x.jobs.map((j) => j.id), [bDone.jobId]);
+ const view = buildServiceCookieAlerts(await readServiceCookieState(paths), { now: Date.now(), browser: "firefox" });
+ assert.match(view.alerts[0]?.headline ?? "", /^X needs fresh cookies: press Refresh cookies \(or Connect X account\) on \/settings/);
+ assert.match(view.alerts[0]?.headline ?? "", /open x\.com in firefox/);
+
+ // A real challenge from X while the jar-age banner is up escalates it to a
+ // blocking alert, keeping the job it holds.
+ const { noteXServiceOutcome } = await import("../lib/serviceCookies-server");
+ await noteXServiceOutcome(paths, { challengeLine: "[twitter][warning] Cloudflare challenge", kind: "challenge" });
+ x = (await readServiceCookieState(paths)).services.x;
+ assert.equal(x?.kind, "challenge");
+ assert.equal(isBlockingAlert(x), true);
+ assert.deepEqual(x!.jobs.map((j) => j.id), [bDone.jobId]);
+ // And the jar-age path cannot overwrite it.
+ await writeJar(5 * 60_000);
+ await fetchJob(SLUGS[2], new Map());
+ assert.equal((await readServiceCookieState(paths)).services.x?.kind, "challenge");
+});
+
test("get x-session reports what the guard would answer: source, age, limit, allowed", async () => {
await reset();
const { xSessionReport, xJobGuard } = await import("./networkGuard");
diff --git a/common/lib/serviceCookies-server.ts b/common/lib/serviceCookies-server.ts
@@ -24,6 +24,7 @@ import {
coerceServiceCookieState,
forumServiceKey,
isAlertRaised,
+ isBlockingAlert,
isYtdlpCookieService,
noteLastGood,
pruneServiceCookieState,
@@ -115,7 +116,7 @@ export async function noteServiceCookieSignal(
);
if (res.raised && job && !job.staleServices.has(signal.service)) {
job.staleServices.add(signal.service);
- job.onLog(`${serviceStoppedLine(signal.service, opts.browser ?? configuredCookieBrowser())}\n`);
+ 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 ` +
@@ -312,13 +313,13 @@ export async function markServiceCookieRerun(
// throws. Answers the line for the job log when a clean request cleared it.
export async function noteXServiceOutcome(
paths: Pick<Paths, "transcriptsDir">,
- outcome: { challengeLine?: string; url?: string; channel?: string },
+ outcome: { challengeLine?: string; kind?: "challenge" | "auth-failure"; url?: string; channel?: string },
): Promise<string | null> {
try {
if (outcome.challengeLine) {
await noteServiceCookieSignal(
paths,
- { service: X_SERVICE, kind: "challenge", line: outcome.challengeLine.trim().slice(0, 300) },
+ { service: X_SERVICE, kind: outcome.kind ?? "challenge", line: outcome.challengeLine.trim().slice(0, 300) },
{
...(outcome.url ? { url: outcome.url } : {}),
...(outcome.channel ? { channel: outcome.channel } : {}),
@@ -376,3 +377,75 @@ export async function noteServiceStoppedJob(
// 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<Paths, "transcriptsDir">,
+ info: { line: string; channel?: string; job?: { id: string; kind?: string } },
+ now: number = Date.now(),
+): Promise<boolean> {
+ 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<Paths, "transcriptsDir">,
+ opts: { now?: number; by?: "clean" | "recheck" } = {},
+): Promise<string | null> {
+ 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;
+ }
+}
diff --git a/common/lib/serviceCookies.ts b/common/lib/serviceCookies.ts
@@ -22,13 +22,21 @@
import { isBotCheck } from "./availability";
-export type ServiceCookieKind = "embed-403" | "bot-check" | "challenge" | "check-page";
+// "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).
+export type ServiceCookieKind = "embed-403" | "bot-check" | "challenge" | "check-page" | "auth-failure" | "jar-age";
export const SERVICE_COOKIE_KINDS: readonly ServiceCookieKind[] = [
"embed-403",
"bot-check",
"challenge",
"check-page",
+ "auth-failure",
+ "jar-age",
];
// The yt-dlp services: their requests go through yt-dlp with the browser
@@ -91,8 +99,14 @@ export function serviceLabel(service: string): string {
// 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 {
+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 /settings 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)`;
@@ -121,8 +135,8 @@ function browserName(spec: string | undefined): string {
}
// 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.`;
+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 ────────────────────────────────────────────────────────────
@@ -317,6 +331,13 @@ 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
+// only): 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;
@@ -336,9 +357,14 @@ export function applyServiceCookieSignal(
let entry = state.services[signal.service];
const stalePending =
entry && !entry.raisedAt && now - Date.parse(entry.lastSeen) > PENDING_SIGNAL_TTL_MS;
+ // 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 || (!entry.raisedAt && entry.kind !== signal.kind)) {
+ if (!entry || entry.clearedAt || stalePending || escalate || (!entry.raisedAt && entry.kind !== signal.kind)) {
entry = {
service: signal.service,
kind: signal.kind,
@@ -347,7 +373,7 @@ export function applyServiceCookieSignal(
count: 0,
evidence: { line: signal.line },
videos: [],
- jobs: [],
+ jobs: [...carriedJobs],
};
state.services[signal.service] = entry;
}
@@ -467,10 +493,43 @@ export type ServiceCookieAlertView = {
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"]);
@@ -489,6 +548,10 @@ function kindPhrase(kind: ServiceCookieKind, count: number, videos: number): str
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";
}
}
@@ -513,7 +576,7 @@ export function buildServiceCookieAlerts(
continue;
}
if (e.clearedAt && opts.now - Date.parse(e.clearedAt) > CLEARED_KEEP_MS) continue;
- const fix = serviceFixText(e.service, opts.browser);
+ 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 } : {}) };
diff --git a/common/social/__fixtures__/firefoxCookieStore.ts b/common/social/__fixtures__/firefoxCookieStore.ts
@@ -16,6 +16,8 @@ export type FixtureCookie = {
expiry?: number;
// PRTime: microseconds since the epoch.
lastAccessed?: number;
+ // PRTime; absent: lastAccessed.
+ creationTime?: number;
isSecure?: 0 | 1;
isHttpOnly?: 0 | 1;
sameSite?: number;
@@ -58,7 +60,7 @@ export function insertFixtureCookies(db: SqliteDb, cookies: ReadonlyArray<Fixtur
c.path ?? "/",
c.expiry ?? Math.floor(Date.now() / 1000) + 86_400 * 365,
c.lastAccessed ?? nowUs,
- c.lastAccessed ?? nowUs,
+ c.creationTime ?? c.lastAccessed ?? nowUs,
c.isSecure ?? 1,
c.isHttpOnly ?? 1,
c.sameSite ?? 0,
diff --git a/common/social/xGalleryDlFetcher.ts b/common/social/xGalleryDlFetcher.ts
@@ -31,6 +31,7 @@ import type { Readable } from "node:stream";
import { execa } from "execa";
import { getPaths } from "../lib/paths";
import { noteXServiceOutcome } from "../lib/serviceCookies-server";
+import { looksLikeXAuthFailure, xBlockKind, xBlockLine } from "./xGalleryDlSignals";
import { cookieArgs } from "../lib/cookiePolicy";
import type { Post } from "../lib/posts";
import type { OlderBackfillPosition } from "../lib/posts-server";
@@ -70,40 +71,22 @@ import {
type OnePostFetchResult,
} from "./fetchers";
-// Substrings in gallery-dl's stderr that mean "we are not authenticated" (or no
-// longer are). Mapped to needsCookies so the channel lands in the existing
+// "Are we still logged in?" — classified line by line in xGalleryDlSignals.ts
+// (pure, unit-tested on gallery-dl's real messages): a challenge, a login
+// failure, a rate limit (pacing, never cookies) or one account's refusal
+// (protected, blocked, suspended; a media file's 403 on twimg.com). An auth
+// failure maps to needsCookies so the channel lands in the existing
// Needs-cookies bucket instead of looking like a generic crash.
-const AUTH_ERROR_PATTERNS = [
- "401",
- "403",
- "authorization",
- "unauthorized",
- "login required",
- "requires authentication",
- "no username",
- "bad credentials",
- "could not log in",
-];
-
-function looksLikeAuthFailure(text: string): boolean {
- const lower = text.toLowerCase();
- return AUTH_ERROR_PATTERNS.some((p) => lower.includes(p));
-}
-
+//
// X STOPPED ANSWERING (plans/pacing-guard.md). On 2026-10-23 gallery-dl
// printed `[twitter][warning] Cloudflare challenge`, EXITED 0, read nothing,
// and the job ended `done` — the next twelve fetches went straight on. A
-// challenge word on any stderr line, or an auth failure (AUTH_ERROR_PATTERNS)
-// on a warning or error line, now stops the run whatever the exit code: the
-// fetch fails (posts read so far kept) and the X cookie alert is raised, which
-// refuses every X job until it is cleared (jobs/networkGuard.ts).
-const X_CHALLENGE_LINE = /cloudflare|\bchallenge\b|just a moment|captcha/i;
-const LEVEL_LINE = /\]\[(warning|error)\]/i;
-
-export function xBlockLine(line: string): boolean {
- if (X_CHALLENGE_LINE.test(line)) return true;
- return LEVEL_LINE.test(line) && looksLikeAuthFailure(line);
-}
+// challenge on any stderr line, or a login failure on a warning or error line,
+// now stops the run whatever the exit code: the fetch fails (posts read so far
+// kept) and the X cookie alert is raised, which refuses every X job until it
+// is cleared (jobs/networkGuard.ts).
+const looksLikeAuthFailure = looksLikeXAuthFailure;
+export { xBlockLine };
export function xBlockedError(line: string): string {
return (
@@ -122,7 +105,7 @@ async function noteXOutcome(
): Promise<void> {
if (challengeLine) onLog?.(`[auth] ${xBlockedError(challengeLine)}`);
const cleared = await noteXServiceOutcome(getPaths(), {
- ...(challengeLine ? { challengeLine } : {}),
+ ...(challengeLine ? { challengeLine, kind: xBlockKind(challengeLine) } : {}),
...(url ? { url } : {}),
...(channel ? { channel } : {}),
});
diff --git a/common/social/xGalleryDlSignals.test.ts b/common/social/xGalleryDlSignals.test.ts
@@ -0,0 +1,76 @@
+// What a gallery-dl stderr line says about X's login (xGalleryDlSignals.ts),
+// on the messages gallery-dl 1.32's twitter extractor and job runner really
+// print (extractor/twitter.py, extractor/common.py, exception.py, job.py):
+// a challenge and a login failure raise X's cookie alert; a rate limit is
+// pacing; one account's or one media file's refusal is not the login.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/xGalleryDlSignals.test.ts
+
+import test from "node:test";
+import assert from "node:assert/strict";
+import {
+ classifyXStderrLine,
+ looksLikeXAuthFailure,
+ xBlockKind,
+ xBlockLine,
+} from "./xGalleryDlSignals";
+
+const CASES: Array<[string, ReturnType<typeof classifyXStderrLine>]> = [
+ // Challenges — any level, one is enough.
+ ["[twitter][warning] Cloudflare challenge", "challenge"],
+ ["[twitter][error] ChallengeError: Cloudflare challenge (403 Forbidden) for 'https://x.com/i/api/graphql/abc/UserTweets'", "challenge"],
+ ["[twitter][warning] Cloudflare CAPTCHA", "challenge"],
+ ["[twitter][warning] DDoS-Guard challenge", "challenge"],
+ // The login gone or refused.
+ ["[twitter][error] AuthRequired: authenticated cookies needed to access this timeline", "auth"],
+ ["[twitter][error] AuthenticationError: Invalid login credentials", "auth"],
+ ["[twitter][error] 'Could not authenticate you'", "auth"],
+ ["[twitter][error] HttpError: '401 Unauthorized' for 'https://x.com/i/api/graphql/abc/UserTweets'", "auth"],
+ ["[twitter][error] HTTP redirect to login page (401 Unauthorized)", "auth"],
+ ["[twitter][error] 403 Forbidden (Forbidden)", "auth"],
+ ["[twitter][error] AuthorizationError: Account temporarily locked", "auth"],
+ // Pacing, never cookies.
+ ["[twitter][info] Waiting for 14 minutes until 03:12:44 (rate limit)", "rate-limit"],
+ ["[twitter][info] Waiting for 60 seconds until 03:12:44 (429 Too Many Requests)", "rate-limit"],
+ ["[twitter][error] Rate limit exceeded", "rate-limit"],
+ ["[twitter][error] HttpError: '429 Too Many Requests' for 'https://x.com/i/api/graphql/403abc/UserTweets'", "rate-limit"],
+ // One account, one post, one media file: the login is fine.
+ ["[twitter][error] AuthorizationError: someone's Tweets are protected", "account"],
+ ["[twitter][error] AuthorizationError: someone blocked your account", "account"],
+ ["[twitter][error] AuthRequired: Protected Tweet", "account"],
+ ["[twitter][error] AuthRequired: NSFW Tweet", "account"],
+ ["[twitter][error] NotFoundError: Requested user could not be found", "account"],
+ ["[download][warning] HttpError: '403 Forbidden' for 'https://video.twimg.com/ext_tw_video/1/pu/vid/720x1280/a.mp4'", "account"],
+ // Nothing.
+ ["[twitter][debug] Cursor: DAABCgABG", null],
+ ["[twitter][debug] HttpError: '401 Unauthorized' (debug lines never count)", null],
+ ["[twitter][info] Requesting guest token", null],
+ ["", null],
+ // A login phrase on an untagged line counts only for a failed run's tail.
+ ["401 Unauthorized", null],
+];
+
+test("each real gallery-dl line is classified: challenge, auth, rate limit, one account, or nothing", () => {
+ for (const [line, want] of CASES) {
+ assert.equal(classifyXStderrLine(line), want, line);
+ }
+});
+
+test("xBlockLine stops a run (and raises X's alert) only on a challenge or a login failure", () => {
+ assert.equal(xBlockLine("[twitter][warning] Cloudflare challenge"), true);
+ assert.equal(xBlockLine("[twitter][error] AuthRequired: authenticated cookies needed to access this timeline"), true);
+ assert.equal(xBlockLine("[twitter][info] Waiting for 14 minutes until 03:12:44 (rate limit)"), false);
+ assert.equal(xBlockLine("[twitter][error] HttpError: '429 Too Many Requests' for 'https://x.com/i/api/x'"), false);
+ assert.equal(xBlockLine("[twitter][error] AuthorizationError: someone's Tweets are protected"), false);
+ assert.equal(xBlockLine("[download][warning] HttpError: '403 Forbidden' for 'https://pbs.twimg.com/media/a.jpg'"), false);
+ assert.equal(xBlockKind("[twitter][warning] Cloudflare challenge"), "challenge");
+ assert.equal(xBlockKind("[twitter][error] 'Could not authenticate you'"), "auth-failure");
+});
+
+test("a failed run's tail: a login failure (even untagged) is Needs-cookies; a rate limit or a protected account is not", () => {
+ assert.equal(looksLikeXAuthFailure("some progress\n401 Unauthorized"), true);
+ assert.equal(looksLikeXAuthFailure("[twitter][error] AuthRequired: authenticated cookies needed to access this timeline"), true);
+ assert.equal(looksLikeXAuthFailure("[twitter][error] Rate limit exceeded"), false);
+ assert.equal(looksLikeXAuthFailure("[twitter][error] AuthorizationError: someone's Tweets are protected"), false);
+ assert.equal(looksLikeXAuthFailure("[twitter][error] AbortExtraction: 404 Not Found (GraphQL query id rotated)"), false);
+});
diff --git a/common/social/xGalleryDlSignals.ts b/common/social/xGalleryDlSignals.ts
@@ -0,0 +1,114 @@
+// WHAT ONE gallery-dl STDERR LINE SAYS ABOUT X (plans/pacing-guard.md,
+// plans/cookie-refresh-alerts.md). Pure and client-safe: the X fetcher
+// (xGalleryDlFetcher.ts) asks it of every stderr line, and the answer decides
+// whether X's cookie alert goes up — which refuses EVERY X job until it is
+// cleared (jobs/networkGuard.ts). So the classes are drawn carefully:
+//
+// "challenge" Cloudflare's (or DDoS-Guard's) check or a captcha. One is
+// enough: the next request after it is the one that gets the
+// account locked.
+// "auth" the login itself is gone or refused: gallery-dl's
+// AuthRequired ("authenticated cookies needed to access this
+// timeline" — what X answers a logged-out timeline with),
+// AuthenticationError, "Could not authenticate you", a 401, a
+// 403 from X's API, an account X has temporarily locked. The
+// COOKIES are the fix (counted only on a warning or error line).
+// "rate-limit" a 429, "Too Many Requests", "rate limit" — PACING, never
+// cookies: gallery-dl waits it out itself, and fresh cookies
+// would not help.
+// "account" about ONE account or post, not the login: a protected
+// account, one that blocked ours, a suspended or missing one,
+// an NSFW or protected tweet, a media file's 403/404 on
+// twimg.com. Not a cookie signal — raising X's alert for it
+// would stop every other X job for nothing.
+// null anything else (progress, debug, an unrelated error).
+//
+// The order matters: a ChallengeError line carries "403" too
+// ("Cloudflare challenge (403 Forbidden) for '…'"), and a 429 line may carry
+// a URL with digits in it, so challenge is asked first, then the rate limit,
+// then the per-account phrases, and only then the login.
+
+export type XStderrClass = "challenge" | "auth" | "rate-limit" | "account";
+
+const DEBUG_LINE = /\]\[debug\]/i;
+// "[twitter][warning] …", "[twitter][error] …", "[download][error] …".
+const LEVEL_LINE = /\]\[(warning|error)\]/i;
+
+const CHALLENGE = /cloudflare|\bchallenge\b|just a moment|captcha|ddos-guard/i;
+const RATE_LIMIT = /\b429\b|too many requests|rate[- ]?limit/i;
+// One account's or one post's refusal: the login is fine.
+const ACCOUNT_SCOPED = new RegExp(
+ [
+ "tweets are protected",
+ "blocked your account",
+ "protected tweet",
+ "nsfw tweet",
+ "age-restricted",
+ "account (?:is )?suspended",
+ "user (?:is )?suspended",
+ "user not found",
+ "could not be found",
+ "notfounderror",
+ "does not exist",
+ // A media file on X's CDN: a removed video or picture, not the login.
+ "twimg\\.com",
+ ].join("|"),
+ "i",
+);
+const AUTH = new RegExp(
+ [
+ "authrequired",
+ "authenticationerror",
+ "authorizationerror",
+ "authenticated cookies needed",
+ "account credentials required",
+ "invalid login credentials",
+ "could not authenticate you",
+ "login required",
+ "requires authentication",
+ "redirect to (?:the )?login",
+ "no username",
+ "bad credentials",
+ "could not log in",
+ "unauthorized",
+ "account temporarily locked",
+ "\\b401\\b",
+ "\\b403\\b",
+ ].join("|"),
+ "i",
+);
+
+// `anyLevel`: count a login phrase on a line with no [warning]/[error] tag
+// too — for the tail of a run that already EXITED non-zero, where the failure
+// is not in doubt and only its cause is asked.
+export function classifyXStderrLine(line: string, opts: { anyLevel?: boolean } = {}): XStderrClass | null {
+ const l = line.trim();
+ if (!l || DEBUG_LINE.test(l)) return null;
+ if (CHALLENGE.test(l)) return "challenge";
+ if (RATE_LIMIT.test(l)) return "rate-limit";
+ const levelled = opts.anyLevel || LEVEL_LINE.test(l);
+ if (ACCOUNT_SCOPED.test(l)) return levelled ? "account" : null;
+ if (AUTH.test(l)) return levelled ? "auth" : null;
+ return null;
+}
+
+// The lines that stop an X run and raise its cookie alert: a challenge on any
+// line, a login failure on a warning or error line.
+export function xBlockLine(line: string): boolean {
+ const c = classifyXStderrLine(line);
+ return c === "challenge" || c === "auth";
+}
+
+// The alert's kind for a blocking line.
+export function xBlockKind(line: string): "challenge" | "auth-failure" {
+ return classifyXStderrLine(line) === "challenge" ? "challenge" : "auth-failure";
+}
+
+// A failed run's stderr tail: does it say the LOGIN failed (the Needs-cookies
+// bucket), as opposed to a rate limit, one protected account, or a crash?
+export function looksLikeXAuthFailure(text: string): boolean {
+ return text.split("\n").some((l) => {
+ const c = classifyXStderrLine(l, { anyLevel: true });
+ return c === "auth" || c === "challenge";
+ });
+}
diff --git a/common/social/xJarAge.test.ts b/common/social/xJarAge.test.ts
@@ -0,0 +1,117 @@
+// X's jar age, from disk (xJarAge.ts): the profile jar's mtime, or the
+// browser's x.com auth_token last-sent time read BY NAME from a Firefox
+// cookies.sqlite. Every store is a fixture written through node:sqlite under a
+// temp HOME (__fixtures__/firefoxCookieStore.ts) — no test reads a real
+// browser profile, and nothing asks X.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/xJarAge.test.ts
+
+import { test, after } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync } from "node:fs";
+import { mkdir, readdir, rm, utimes, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import { readFirefoxXAuthTimes, readXJarAge, xJarStatusFrom } from "./xJarAge";
+import { writeFirefoxCookieStore, type FixtureCookie } from "./__fixtures__/firefoxCookieStore";
+
+const TMP = mkdtempSync(path.join(os.tmpdir(), "xjarage-"));
+after(() => rm(TMP, { recursive: true, force: true }));
+let n = 0;
+const fresh = (label: string) => path.join(TMP, `${label}-${++n}`);
+
+const NOW = Date.UTC(2026, 9, 31, 23, 0, 0);
+const us = (msAgo: number) => (NOW - msAgo) * 1000;
+const SECRET = "fixture-auth-value-never-read";
+
+function login(lastUsedMsAgo: number, extra: FixtureCookie[] = []): FixtureCookie[] {
+ return [
+ { host: ".x.com", name: "auth_token", value: SECRET, lastAccessed: us(lastUsedMsAgo), creationTime: us(30 * 86_400_000) },
+ { host: ".x.com", name: "ct0", value: "csrf" },
+ { host: "notx.com", name: "auth_token", value: "lookalike", lastAccessed: us(0) },
+ ...extra,
+ ];
+}
+
+function pathsAt(dir: string): Paths {
+ return { transcriptsDir: dir } as unknown as Paths;
+}
+
+test("the name-only read: the x.com auth_token's times, its value never selected", async () => {
+ const { file } = await writeFirefoxCookieStore(fresh("ff"), login(30 * 60_000));
+ const t = await readFirefoxXAuthTimes(file, { tmpRoot: TMP });
+ assert.equal(t.found, true);
+ assert.equal(t.lastAccessedMs, NOW - 30 * 60_000);
+ assert.equal(t.creationMs, NOW - 30 * 86_400_000);
+ assert.equal(JSON.stringify(t).includes(SECRET), false);
+ // The private copy is gone.
+ assert.deepEqual((await readdir(TMP)).filter((f) => f.startsWith("archilyzer-xjar-")), []);
+});
+
+test("a login only Firefox's write-ahead log holds counts; one in an unread container does not", async () => {
+ const { file, db } = await writeFirefoxCookieStore(fresh("wal"), login(5 * 60_000), { keepOpen: true });
+ try {
+ assert.equal((await readFirefoxXAuthTimes(file, { tmpRoot: TMP })).found, true);
+ } finally {
+ db?.close();
+ }
+ const { file: f2 } = await writeFirefoxCookieStore(fresh("container"), [
+ { host: ".x.com", name: "auth_token", value: SECRET, lastAccessed: us(60_000), originAttributes: "^userContextId=2" },
+ ]);
+ assert.equal((await readFirefoxXAuthTimes(f2, { tmpRoot: TMP })).found, false);
+ assert.equal((await readFirefoxXAuthTimes(f2, { tmpRoot: TMP, container: "all" })).found, true);
+});
+
+test("browser source: fresh within the limit, stale past it, no limit at 0; cached between reads unless asked fresh", async () => {
+ const home = fresh("home");
+ const profile = path.join(home, ".mozilla", "firefox", "abc.default-release");
+ await writeFirefoxCookieStore(profile, login(30 * 60_000));
+ const settings = { cookiesFromBrowser: "firefox", social: { x: { cookieSource: "browser" as const } } };
+ const p = pathsAt(fresh("transcripts"));
+ const ok = await readXJarAge(p, settings, { maxAgeMinutes: 60, now: NOW, home, tmpRoot: TMP, fresh: true });
+ assert.equal(ok.source, "browser");
+ assert.equal(ok.loggedIn, true);
+ assert.equal(ok.ageMinutes, 30);
+ assert.equal(ok.fresh, true);
+ assert.match(ok.summary, /last used 30 min ago \(limit 60 min\)\.$/);
+ assert.equal(JSON.stringify(ok).includes(SECRET), false);
+
+ const stale = await readXJarAge(p, settings, { maxAgeMinutes: 20, now: NOW, home, tmpRoot: TMP, fresh: true });
+ assert.equal(stale.fresh, false);
+ assert.match(stale.summary, /open x\.com in that browser/);
+ assert.equal((await readXJarAge(p, settings, { maxAgeMinutes: 0, now: NOW, home, tmpRoot: TMP, fresh: true })).fresh, true);
+
+ // The store changes (the operator opened x.com) — a cached read does not see
+ // it; a fresh read does.
+ await rm(profile, { recursive: true, force: true });
+ await writeFirefoxCookieStore(profile, login(60_000));
+ const cached = await readXJarAge(p, settings, { maxAgeMinutes: 60, now: NOW + 60_000, home, tmpRoot: TMP });
+ assert.equal(cached.ageMinutes, 31, "re-derived from the cached reading at the new time");
+ const reread = await readXJarAge(p, settings, { maxAgeMinutes: 60, now: NOW, home, tmpRoot: TMP, fresh: true });
+ assert.equal(reread.ageMinutes, 1);
+});
+
+test("profile source: the exported jar's mtime and its auth_token", async () => {
+ const dir = fresh("transcripts");
+ const jar = path.join(dir, ".x-session", "cookies.txt");
+ await mkdir(path.join(dir, ".x-session", "profile"), { recursive: true });
+ await writeFile(jar, "# Netscape HTTP Cookie File\n.x.com\tTRUE\t/\tTRUE\t0\tauth_token\tv\n");
+ const t = new Date(NOW - 3 * 3600_000);
+ await utimes(jar, t, t);
+ const settings = { social: { x: { cookieSource: "profile" as const } } };
+ const v = await readXJarAge(pathsAt(dir), settings, { maxAgeMinutes: 60, now: NOW });
+ assert.equal(v.source, "profile");
+ assert.equal(v.ageMinutes, 180);
+ assert.equal(v.fresh, false);
+ assert.match(v.summary, /^The X cookie jar was written 3 h ago \(limit 60 min\): press Refresh cookies/);
+ await utimes(jar, new Date(NOW - 60_000), new Date(NOW - 60_000));
+ assert.equal((await readXJarAge(pathsAt(dir), settings, { maxAgeMinutes: 60, now: NOW })).fresh, true);
+});
+
+test("the verdict, pure: no login is never fresh; an unreadable source says why", () => {
+ assert.equal(xJarStatusFrom({ source: "profile", at: null, loggedIn: false, maxAgeMinutes: 0, now: NOW }).fresh, false);
+ const u = xJarStatusFrom({ source: "browser", at: null, loggedIn: null, maxAgeMinutes: 60, now: NOW, unreadable: "No Firefox cookie store found." });
+ assert.equal(u.fresh, false);
+ assert.equal(u.summary, "No Firefox cookie store found.");
+});
diff --git a/common/social/xJarAge.ts b/common/social/xJarAge.ts
@@ -0,0 +1,224 @@
+// HOW FRESH IS X'S LOGIN — read from disk, never from X (plans/cookie-refresh-
+// alerts.md, "X's jar age"). The X fetchers' login comes from one of two
+// sources (social/xCookieSource.ts):
+//
+// "profile" the session broker's exported jar (`.x-session/cookies.txt`):
+// fresh = the file was written (Connect X account / Refresh
+// cookies) within `social.x.maxCookieAgeMinutes`, and it holds an
+// auth_token. A stat and a substring test.
+// "browser" the operator's Firefox, named by cookiesFromBrowser: fresh =
+// Firefox SENT its x.com auth_token (moz_cookies.lastAccessed —
+// the operator had x.com open) within the limit. Read BY NAME:
+// the query selects the cookie's host, name and times only —
+// never its value — from a private copy of the store (the store
+// and its write-ahead log, so a login Firefox has not
+// checkpointed yet counts), in a 0700 temp dir removed after.
+//
+// Nothing here asks X anything, and nothing refreshes the jar: a refresh is a
+// human click (refreshXCookies loads x.com/home — itself a request to X).
+//
+// The browser read copies a small SQLite file, so its answer is cached for a
+// few minutes (the dashboard polls); `fresh: true` reads again (the recheck
+// timer, Recheck).
+
+import { copyFile, mkdir, mkdtemp, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import type { XJarStatusView } from "../lib/serviceCookies";
+import { loadSqlite } from "./nodeSqlite";
+import { readXSessionStatus } from "./xSessionBroker";
+import {
+ X_AUTH_COOKIE,
+ findFirefoxCookieDb,
+ firefoxContainerScope,
+ inContainerScope,
+ isXComHost,
+ resolveXCookieSourceFor,
+ type XLoginSettings,
+} from "./xBrowserLogin";
+import { parseBrowserSpec, SELF_READ_BROWSERS } from "./xCookieSource";
+
+export const X_JAR_BROWSER_CACHE_MS = 5 * 60_000;
+
+export type FirefoxAuthTimes = {
+ // The newest x.com auth_token in scope: when Firefox last sent it and when
+ // it was set (ms since the epoch).
+ lastAccessedMs?: number;
+ creationMs?: number;
+ // Any x.com auth_token in scope at all.
+ found: boolean;
+};
+
+// PRTime (microseconds) → ms; a value already in ms is kept.
+function prtimeMs(v: unknown): number | undefined {
+ const n = typeof v === "bigint" ? Number(v) : typeof v === "number" ? v : NaN;
+ if (!Number.isFinite(n) || n <= 0) return undefined;
+ return Math.floor(n > 1e14 ? n / 1000 : n);
+}
+
+// THE NAME-ONLY READ: the x.com auth_token's times from a Firefox
+// cookies.sqlite, in the container scope gallery-dl reads (`container` as in
+// a cookiesFromBrowser spec: absent/"none", "all", or a name). The value column
+// is never selected.
+export async function readFirefoxXAuthTimes(
+ dbFile: string,
+ opts: { container?: string; tmpRoot?: string } = {},
+): Promise<FirefoxAuthTimes> {
+ const { DatabaseSync } = await loadSqlite();
+ const scope = await firefoxContainerScope(dbFile, opts.container);
+ const tmp = await mkdtemp(path.join(opts.tmpRoot ?? os.tmpdir(), "archilyzer-xjar-"));
+ try {
+ const copy = path.join(tmp, "store", "cookies.sqlite");
+ await mkdir(path.dirname(copy));
+ await copyFile(dbFile, copy);
+ await copyFile(`${dbFile}-wal`, `${copy}-wal`).catch((err: NodeJS.ErrnoException) => {
+ if (err.code !== "ENOENT") throw err;
+ });
+ const db = new DatabaseSync(copy);
+ try {
+ const rows = db
+ .prepare(
+ "SELECT host, name, lastAccessed, creationTime, originAttributes FROM moz_cookies WHERE name = ?",
+ )
+ .all(X_AUTH_COOKIE) as Array<Record<string, unknown>>;
+ let best: FirefoxAuthTimes = { found: false };
+ for (const r of rows) {
+ if (typeof r.host !== "string" || !isXComHost(r.host)) continue;
+ const attrs = typeof r.originAttributes === "string" ? r.originAttributes : "";
+ if (!inContainerScope(attrs, scope)) continue;
+ const last = prtimeMs(r.lastAccessed);
+ const created = prtimeMs(r.creationTime);
+ if (!best.found || (last ?? 0) > (best.lastAccessedMs ?? 0)) {
+ best = {
+ found: true,
+ ...(last ? { lastAccessedMs: last } : {}),
+ ...(created ? { creationMs: created } : {}),
+ };
+ }
+ }
+ return best;
+ } finally {
+ db.close();
+ }
+ } finally {
+ await rm(tmp, { recursive: true, force: true });
+ }
+}
+
+function ageText(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`;
+}
+
+// The verdict from what was read, pure.
+export function xJarStatusFrom(input: {
+ source: "profile" | "browser";
+ at: string | null;
+ loggedIn: boolean | null;
+ maxAgeMinutes: number;
+ now: number;
+ // What could not be read, when nothing could (browser source).
+ unreadable?: string;
+}): XJarStatusView {
+ const readAt = new Date(input.now).toISOString();
+ const ageMinutes = input.at ? Math.max(0, Math.floor((input.now - Date.parse(input.at)) / 60_000)) : null;
+ const within = input.maxAgeMinutes <= 0 || (ageMinutes !== null && ageMinutes <= input.maxAgeMinutes);
+ const fresh = input.loggedIn === true && within;
+ const limit = input.maxAgeMinutes > 0 ? ` (limit ${input.maxAgeMinutes} min)` : " (no age limit)";
+ let summary: string;
+ if (input.unreadable) summary = input.unreadable;
+ else if (input.source === "profile") {
+ summary = !input.at
+ ? "No X cookie jar has been exported: press Connect X account on /settings."
+ : input.loggedIn !== true
+ ? "The X cookie jar holds no login (no auth_token): press Connect X account on /settings."
+ : `The X cookie jar was written ${ageText(ageMinutes!)} ago${limit}` +
+ (fresh ? "." : ": press Refresh cookies (or Connect X account) on /settings.");
+ } else {
+ summary = input.loggedIn !== true
+ ? "No X login in the browser cookiesFromBrowser names (no x.com auth_token): log in to x.com there."
+ : !input.at
+ ? "The browser holds an X login; when it was last used could not be read."
+ : `The browser's X login was last used ${ageText(ageMinutes!)} ago${limit}` +
+ (fresh ? "." : ": open x.com in that browser.");
+ }
+ return {
+ source: input.source,
+ at: input.at,
+ ageMinutes,
+ maxAgeMinutes: input.maxAgeMinutes,
+ loggedIn: input.loggedIn,
+ fresh,
+ readAt,
+ summary,
+ };
+}
+
+type Cache = { key: string; at: number; view: XJarStatusView };
+const CACHE_KEY = Symbol.for("archilyzer.xJarAge.cache");
+function cache(): { last?: Cache } {
+ const g = globalThis as unknown as Record<symbol, { last?: Cache }>;
+ return (g[CACHE_KEY] ??= {});
+}
+
+export async function readXJarAge(
+ paths: Paths,
+ settings: XLoginSettings,
+ opts: { maxAgeMinutes: number; now?: number; fresh?: boolean; home?: string; tmpRoot?: string },
+): Promise<XJarStatusView> {
+ const now = opts.now ?? Date.now();
+ const resolved = await resolveXCookieSourceFor(paths, settings);
+ if (resolved.source === "profile") {
+ const st = await readXSessionStatus(paths);
+ return xJarStatusFrom({
+ source: "profile",
+ at: st.cookiesUpdatedAt ?? null,
+ loggedIn: st.hasCookies ? st.looksAuthenticated : false,
+ maxAgeMinutes: opts.maxAgeMinutes,
+ now,
+ });
+ }
+ const spec = resolved.browserSpec?.trim() ?? "";
+ const key = `browser:${spec}`;
+ const c = cache();
+ if (!opts.fresh && c.last && c.last.key === key && now - c.last.at < X_JAR_BROWSER_CACHE_MS) {
+ // Re-derive the age at `now` from the cached reading.
+ return xJarStatusFrom({
+ source: "browser",
+ at: c.last.view.at,
+ loggedIn: c.last.view.loggedIn,
+ maxAgeMinutes: opts.maxAgeMinutes,
+ now,
+ });
+ }
+ const unreadable = (why: string) =>
+ xJarStatusFrom({ source: "browser", at: null, loggedIn: null, maxAgeMinutes: opts.maxAgeMinutes, now, unreadable: why });
+ const parsed = spec ? parseBrowserSpec(spec) : null;
+ if (!parsed) return unreadable("cookiesFromBrowser names no browser to read an X login from.");
+ if (!SELF_READ_BROWSERS.includes(parsed.browser)) {
+ return unreadable(`${parsed.browser}'s cookie store is encrypted; only Firefox's X login age can be read here.`);
+ }
+ let view: XJarStatusView;
+ try {
+ const found = await findFirefoxCookieDb(parsed, opts.home ?? os.homedir());
+ if (!found.file) return unreadable("No Firefox cookie store found.");
+ const t = await readFirefoxXAuthTimes(found.file, {
+ ...(parsed.container ? { container: parsed.container } : {}),
+ ...(opts.tmpRoot ? { tmpRoot: opts.tmpRoot } : {}),
+ });
+ const atMs = t.lastAccessedMs ?? t.creationMs;
+ view = xJarStatusFrom({
+ source: "browser",
+ at: atMs ? new Date(atMs).toISOString() : null,
+ loggedIn: t.found,
+ maxAgeMinutes: opts.maxAgeMinutes,
+ now,
+ });
+ } catch (err) {
+ return unreadable(`Could not read Firefox's cookie store: ${(err as Error).message}`);
+ }
+ c.last = { key, at: now, view };
+ return view;
+}