// HOW FRESH A yt-dlp SERVICE'S BROWSER COOKIES ARE — read from disk, never from // the service (the /cookies screen, plans/cookie-screen.md). Rumble, YouTube // and Odysee are fetched by yt-dlp with `--cookies-from-browser `: their // "jar" IS the browser's cookie store, and a refresh is the operator opening // the site in that browser. So the age shown is what the store says: // // rumble, odysee Cloudflare's `cf_clearance` for the site — when it was // issued (creationTime: the check passed) and when it // expires. // youtube the sign-in cookies — when Firefox last SENT one // (lastAccessed: youtube.com was open, signed in). // // THE SAME DISCIPLINE AS X's (social/xJarAge.ts readFirefoxXAuthTimes): a // private copy of the store and its write-ahead log in a 0700 temp dir removed // after; the query selects host, name and the three times ONLY — never the // value (BROWSER_COOKIE_TIMES_SQL; a test fails if it ever does); nothing here // logs a cookie's name. Firefox only (Chromium stores are encrypted). A // `file:` spec (an exported cookies.txt) is aged by the file's mtime. // // Cached for a few minutes per spec (the page polls); `fresh: true` reads again // (Check again). A read that fails is an answer — `unknown` with the reason — // never a throw. import { copyFile, mkdir, mkdtemp, readdir, rm, stat } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { loadSqlite } from "../social/nodeSqlite"; import { findFirefoxCookieDb, firefoxContainerScope, inContainerScope } from "../social/xBrowserLogin"; import { parseBrowserSpec, SELF_READ_BROWSERS } from "../social/xCookieSource"; import { cookieFileOf } from "./cookiePolicy"; export const BROWSER_COOKIE_AGE_CACHE_MS = 5 * 60_000; export type BrowserCookieService = "rumble" | "youtube" | "odysee"; export const BROWSER_COOKIE_SERVICES: readonly BrowserCookieService[] = ["rumble", "youtube", "odysee"]; type Want = { domain: string; names: readonly string[]; basis: "clearance" | "login-used" }; // What each service's freshness is read from. export const BROWSER_COOKIE_WANTS: Record = { rumble: { domain: "rumble.com", names: ["cf_clearance"], basis: "clearance" }, odysee: { domain: "odysee.com", names: ["cf_clearance"], basis: "clearance" }, youtube: { domain: "youtube.com", names: ["SID", "__Secure-3PSID", "LOGIN_INFO"], basis: "login-used" }, }; // THE NAME-ONLY QUERY. Never add `value` here. export const BROWSER_COOKIE_TIMES_SQL = "SELECT host, name, creationTime, lastAccessed, expiry, originAttributes FROM moz_cookies WHERE name IN ("; export type BrowserCookieAge = { service: BrowserCookieService; // "clearance": `at` is when the clearance was issued; "login-used": when the // browser last sent the sign-in; "file": the exported cookies file's mtime. basis: "clearance" | "login-used" | "file"; // A cookie for the service is in the store (null: the store could not be read). found: boolean | null; at: string | null; expiresAt?: string; // Why nothing could be read, when nothing could. unknown?: string; }; export type BrowserCookieAges = { spec: string; readAt: string; services: Record; }; // PRTime (µs) → 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); } function secondsMs(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 > 1e11 ? n : n * 1000); } function onDomain(host: string, domain: string): boolean { const h = host.replace(/^\./, "").toLowerCase(); return h === domain || h.endsWith(`.${domain}`); } function allUnknown(why: string, basis?: BrowserCookieAge["basis"]): Record { const out = {} as Record; for (const s of BROWSER_COOKIE_SERVICES) { out[s] = { service: s, basis: basis ?? BROWSER_COOKIE_WANTS[s].basis, found: null, at: null, unknown: why }; } return out; } const TMP_PREFIX = "archilyzer-cookieage-"; // A private copy older than this was left by a read that never finished (the // process died mid-read): it holds cookie values, so it goes. export const STALE_COPY_MS = 10 * 60_000; // Remove this module's own leftover copies under `tmpRoot`. Never throws. export async function sweepStaleCookieCopies(tmpRoot: string, now: number = Date.now()): Promise { let removed = 0; const names = await readdir(tmpRoot).catch(() => [] as string[]); for (const name of names) { if (!name.startsWith(TMP_PREFIX)) continue; const dir = path.join(tmpRoot, name); const st = await stat(dir).catch(() => null); if (!st?.isDirectory() || now - st.mtimeMs < STALE_COPY_MS) continue; await rm(dir, { recursive: true, force: true }).then( () => removed++, () => undefined, ); } return removed; } // One read of a Firefox cookies.sqlite for every service (`container` as in a // cookiesFromBrowser spec). export async function readFirefoxServiceCookieTimes( dbFile: string, opts: { container?: string; tmpRoot?: string } = {}, ): Promise> { const { DatabaseSync } = await loadSqlite(); const scope = await firefoxContainerScope(dbFile, opts.container); const names = [...new Set(BROWSER_COOKIE_SERVICES.flatMap((s) => BROWSER_COOKIE_WANTS[s].names))]; const tmpRoot = opts.tmpRoot ?? os.tmpdir(); await sweepStaleCookieCopies(tmpRoot); const tmp = await mkdtemp(path.join(tmpRoot, TMP_PREFIX)); try { const copy = path.join(tmp, "store", "cookies.sqlite"); await mkdir(path.dirname(copy), { mode: 0o700 }); 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); let rows: Array>; try { rows = db .prepare(`${BROWSER_COOKIE_TIMES_SQL}${names.map(() => "?").join(", ")})`) .all(...names) as Array>; } finally { db.close(); } const out = {} as Record; for (const s of BROWSER_COOKIE_SERVICES) { const want = BROWSER_COOKIE_WANTS[s]; let best: { at?: number; exp?: number } | null = null; for (const r of rows) { if (typeof r.host !== "string" || typeof r.name !== "string") continue; if (!want.names.includes(r.name) || !onDomain(r.host, want.domain)) continue; const attrs = typeof r.originAttributes === "string" ? r.originAttributes : ""; if (!inContainerScope(attrs, scope)) continue; const at = want.basis === "clearance" ? prtimeMs(r.creationTime) ?? prtimeMs(r.lastAccessed) : prtimeMs(r.lastAccessed); if (!best || (at ?? 0) > (best.at ?? 0)) best = { at, exp: secondsMs(r.expiry) }; } out[s] = { service: s, basis: want.basis, found: best !== null, at: best?.at ? new Date(best.at).toISOString() : null, ...(best?.exp && want.basis === "clearance" ? { expiresAt: new Date(best.exp).toISOString() } : {}), }; } return out; } finally { await rm(tmp, { recursive: true, force: true }); } } type Cache = { key: string; at: number; value: BrowserCookieAges }; const CACHE_KEY = Symbol.for("archilyzer.browserCookieAge.cache"); function cache(): Map { const g = globalThis as unknown as Record>; return (g[CACHE_KEY] ??= new Map()); } // The ages for one cookie spec (a channel's or settings' cookiesFromBrowser). export async function readBrowserCookieAges( spec: string | undefined, opts: { now?: number; fresh?: boolean; home?: string; tmpRoot?: string } = {}, ): Promise { const now = opts.now ?? Date.now(); const key = (spec ?? "").trim(); const readAt = new Date(now).toISOString(); const c = cache(); const hit = c.get(key); if (!opts.fresh && hit && now - hit.at < BROWSER_COOKIE_AGE_CACHE_MS) return hit.value; const done = (services: Record): BrowserCookieAges => { const value = { spec: key, readAt, services }; c.set(key, { key, at: now, value }); return value; }; if (!key) return done(allUnknown("No cookiesFromBrowser is set, so yt-dlp sends no browser cookies.")); const file = cookieFileOf(key); if (file) { try { const st = await stat(file); const at = new Date(st.mtimeMs).toISOString(); const out = {} as Record; for (const s of BROWSER_COOKIE_SERVICES) out[s] = { service: s, basis: "file", found: true, at }; return done(out); } catch { return done(allUnknown("The cookies file cookiesFromBrowser names could not be read.", "file")); } } const parsed = parseBrowserSpec(key); if (!parsed) return done(allUnknown("cookiesFromBrowser names no browser this screen can read.")); if (!SELF_READ_BROWSERS.includes(parsed.browser)) { return done(allUnknown(`${parsed.browser}'s cookie store is encrypted; only Firefox's can be read here.`)); } try { const found = await findFirefoxCookieDb(parsed, opts.home ?? os.homedir()); if (!found.file) return done(allUnknown("No Firefox cookie store found.")); return done( await readFirefoxServiceCookieTimes(found.file, { ...(parsed.container ? { container: parsed.container } : {}), ...(opts.tmpRoot ? { tmpRoot: opts.tmpRoot } : {}), }), ); } catch (err) { return done(allUnknown(`Could not read Firefox's cookie store: ${(err as Error).message.split("\n")[0]}`)); } } // Forget every cached read (tests). export function resetBrowserCookieAgeCache(): void { cache().clear(); }