// 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 { 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>; 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 /cookies." : input.loggedIn !== true ? "The X cookie jar holds no login (no auth_token): press Connect X account on /cookies." : `The X cookie jar was written ${ageText(ageMinutes!)} ago${limit}` + (fresh ? "." : ": press Refresh cookies (or Connect X account) on /cookies."); } 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; return (g[CACHE_KEY] ??= {}); } export async function readXJarAge( paths: Paths, settings: XLoginSettings, opts: { maxAgeMinutes: number; now?: number; fresh?: boolean; home?: string; tmpRoot?: string }, ): Promise { 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; }