Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit f13ad6e031760d804a80ae09704c7ad4e48b7d25
parent d0a5dbdaebde2f32a52e7a5ecab9225ee7846a2c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon, 16 Nov 2026 09:49:03 -0500

cookie screen: the readers -- browser-cookie ages, the rows, the last press, a gated fake browser

- common/lib/browserCookieAge.ts: Rumble's and Odysee's cf_clearance (issued,
  expiry) and YouTube's sign-in (last used) from the Firefox store yt-dlp
  reads, X's discipline: a private copy of the store and its WAL, a query of
  host/name/creationTime/lastAccessed/expiry only (a test fails if it ever
  selects the value), cached 5 min per spec, `fresh` re-reads; a file: spec
  is aged by its mtime; a read that fails is "unknown" with the reason.
- common/lib/cookieStatus.ts: the /cookies rows, pure -- source (through the
  privacy displayers), age, alert state stale/fine/unknown with the alert's
  sentence, the one button per service, "headed" for the Connects (a window
  on the editor's machine), the last press, what is running.
- serviceCookies: `actions`, the last press per service (coerce-tolerant,
  absent until one is recorded) and its writer noteServiceCookieAction.
- common/social/fakeXProfileBrowser.ts: Refresh cookies' fake browser for the
  e2e suite (E2E_FAKE_X_PROFILE_COOKIES_FILE) -- inert unless E2E_TEST_ROUTES=1,
  the file is inside the process's transcriptsDir and it exists.
- The alert sentences and job log lines say /cookies where they said
  /settings (X's Refresh cookies / Connect, archive.today's Connect).

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Mcommon/controller/recheckServiceCookies.test.ts | 2+-
Mcommon/controller/recheckServiceCookies.ts | 4++--
Mcommon/controller/serviceCookieTimer.test.ts | 2+-
Mcommon/controller/xRun.ts | 2+-
Mcommon/jobs/networkGuard.test.ts | 2+-
Mcommon/jobs/networkGuard.ts | 8++++----
Mcommon/jobs/pacingGuard.test.ts | 2+-
Acommon/lib/browserCookieAge.test.ts | 144+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/browserCookieAge.ts | 205+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/cookieStatus.test.ts | 178+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/cookieStatus.ts | 310+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/envVars.ts | 1+
Mcommon/lib/serviceCookies-server.test.ts | 29+++++++++++++++++++++++++++++
Mcommon/lib/serviceCookies-server.ts | 20++++++++++++++++++++
Mcommon/lib/serviceCookies.ts | 49+++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/lib/settingsSchema.ts | 2+-
Acommon/social/fakeXProfileBrowser.test.ts | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/social/fakeXProfileBrowser.ts | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xCookieSource.ts | 2+-
Mcommon/social/xGalleryDlFetcher.ts | 6+++---
Mcommon/social/xJarAge.ts | 6+++---
21 files changed, 1109 insertions(+), 23 deletions(-)

diff --git a/common/controller/recheckServiceCookies.test.ts b/common/controller/recheckServiceCookies.test.ts @@ -189,7 +189,7 @@ test("Recheck (X, jar-age): the jar's age on disk, no request — stale while ol 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.", + 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 /cookies.", }), }; const stale = await recheckServiceCookies({ paths, service: "x", deps }); diff --git a/common/controller/recheckServiceCookies.ts b/common/controller/recheckServiceCookies.ts @@ -19,7 +19,7 @@ // 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 /settings) with a login in it, or, with the +// 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 @@ -269,7 +269,7 @@ export async function recheckServiceCookies(opts: { "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 /settings), press Refresh cookies there, then Recheck. Recheck sends X no request." + "(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.`, ); diff --git a/common/controller/serviceCookieTimer.test.ts b/common/controller/serviceCookieTimer.test.ts @@ -38,7 +38,7 @@ function jar(fresh: boolean): XJarStatusView { loggedIn: true, fresh, readAt: new Date(NOW).toISOString(), - summary: fresh ? "The X cookie jar was written 5 min ago (limit 60 min)." : "The X cookie jar was written 5 h ago (limit 60 min): press Refresh cookies (or Connect X account) on /settings.", + summary: fresh ? "The X cookie jar was written 5 min ago (limit 60 min)." : "The X cookie jar was written 5 h ago (limit 60 min): press Refresh cookies (or Connect X account) on /cookies.", }; } diff --git a/common/controller/xRun.ts b/common/controller/xRun.ts @@ -16,7 +16,7 @@ // - BEFORE EACH CHANNEL the network guard is asked again (the fresh-jar rule // and the X alert, jobs/networkGuard.ts). When it refuses, the run STOPS // there and every channel not yet fetched is DEFERRED. Nothing here ever -// refreshes the jar: a refresh is the operator's click on /settings +// refreshes the jar: a refresh is the operator's click on /cookies // (refreshXCookies loads x.com/home — itself a request to X); // - a deferred run is resumed by its id (the console's Resume, `pnpm ops // x-run {"resume": id}`, a Retry of the job): it starts with the deferred diff --git a/common/jobs/networkGuard.test.ts b/common/jobs/networkGuard.test.ts @@ -30,7 +30,7 @@ test("the fresh-jar rule (profile source)", () => { assert.deepEqual(v(16 * 24 * 3600_000), { ok: false, message: - "X cookies were last refreshed 16 days ago (limit 60 min): press Refresh cookies (or Connect X account) on /settings, then fetch again.", + "X cookies were last refreshed 16 days ago (limit 60 min): press Refresh cookies (or Connect X account) on /cookies, then fetch again.", }); assert.match((v(61 * 60_000) as { message: string }).message, /61 min ago/); assert.match((v(60_000, false) as { message: string }).message, /holds no login/); diff --git a/common/jobs/networkGuard.ts b/common/jobs/networkGuard.ts @@ -10,7 +10,7 @@ // 3. X ONLY ON A FRESH JAR. With the "profile" login source, a job aimed at X // starts only when the exported cookie jar was written within // `social.x.maxCookieAgeMinutes` (default 60; 0 = off) and carries a login. -// A refresh is a human click on /settings — refreshXCookies loads +// A refresh is a human click on /cookies — refreshXCookies loads // x.com/home, itself a request to X — so nothing here refreshes it. With // the "browser" source the age cannot be read: the job logs that and // proceeds. @@ -120,14 +120,14 @@ export function xJarVerdict(input: { if (!status.hasCookies || !status.cookiesUpdatedAt) { return { ok: false, - message: "No X cookie jar has been exported: press Connect X account on /settings, then fetch again.", + message: "No X cookie jar has been exported: press Connect X account on /cookies, then fetch again.", }; } if (!status.looksAuthenticated) { return { ok: false, message: - "The X cookie jar holds no login (no auth_token): press Connect X account on /settings, then fetch again.", + "The X cookie jar holds no login (no auth_token): press Connect X account on /cookies, then fetch again.", }; } const age = input.now - Date.parse(status.cookiesUpdatedAt); @@ -136,7 +136,7 @@ export function xJarVerdict(input: { ok: false, message: `X cookies were last refreshed ${ageText(age)} ago (limit ${input.maxAgeMinutes} min): ` + - `press Refresh cookies (or Connect X account) on /settings, then fetch again.`, + `press Refresh cookies (or Connect X account) on /cookies, then fetch again.`, }; } return { ok: true }; diff --git a/common/jobs/pacingGuard.test.ts b/common/jobs/pacingGuard.test.ts @@ -283,7 +283,7 @@ test("the fresh-jar rule raises X's jar-age banner (the job refused at its start xJar: { source: "profile", ageMinutes: 120, maxAgeMinutes: 60 }, }); assert.equal(view.alerts[0]?.headline, "X cookies are 2 h old (limit 60 min)"); - assert.equal(view.alerts[0]?.fix, "Refresh cookies (or Connect X account) on /settings — then Recheck."); + assert.equal(view.alerts[0]?.fix, "Refresh cookies (or Connect X account) on /cookies — then Recheck."); assert.equal(view.alerts[0]?.detail, `Refused fetch-posts ${bDone.jobId} (${SLUGS[1]}).`); assert.equal(view.alerts[0]?.compact, true); const browserView = buildServiceCookieAlerts(st, { diff --git a/common/lib/browserCookieAge.test.ts b/common/lib/browserCookieAge.test.ts @@ -0,0 +1,144 @@ +// The yt-dlp services' browser-cookie ages (browserCookieAge.ts), read BY NAME +// from a Firefox cookies.sqlite. Every store is a fixture written through +// node:sqlite under a temp dir (social/__fixtures__/firefoxCookieStore.ts) — no +// test reads a real browser profile, and nothing asks any service. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/browserCookieAge.test.ts + +import { test, after, beforeEach } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync } from "node:fs"; +import { rm, utimes, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { + BROWSER_COOKIE_TIMES_SQL, + readBrowserCookieAges, + readFirefoxServiceCookieTimes, + resetBrowserCookieAgeCache, +} from "./browserCookieAge"; +import { writeFirefoxCookieStore } from "../social/__fixtures__/firefoxCookieStore"; + +const TMP = mkdtempSync(path.join(os.tmpdir(), "cookieage-")); +after(() => rm(TMP, { recursive: true, force: true })); +beforeEach(() => resetBrowserCookieAgeCache()); + +const us = (iso: string) => Date.parse(iso) * 1000; + +test("the query never selects a cookie's value", () => { + // The column list is everything between SELECT and FROM. + const cols = /^SELECT (.*) FROM /.exec(BROWSER_COOKIE_TIMES_SQL)?.[1] ?? ""; + assert.ok(cols.length > 0); + assert.doesNotMatch(cols, /\bvalue\b/i); + assert.doesNotMatch(cols, /\*/); + assert.deepEqual( + cols.split(",").map((c) => c.trim()), + ["host", "name", "creationTime", "lastAccessed", "expiry", "originAttributes"], + ); +}); + +test("rumble's clearance: issued and expiry; youtube's sign-in: last used; odysee with none", async () => { + const dir = path.join(TMP, "p1"); + await writeFirefoxCookieStore(dir, [ + { + host: ".rumble.com", + name: "cf_clearance", + value: "fixture-not-a-real-clearance", + creationTime: us("2026-11-16T09:00:00Z"), + lastAccessed: us("2026-11-16T09:10:00Z"), + expiry: Date.parse("2026-11-16T10:00:00Z") / 1000, + }, + // An older clearance on a subdomain: the newest wins. + { host: "a.rumble.com", name: "cf_clearance", value: "x", creationTime: us("2026-11-15T09:00:00Z") }, + // Not the site's (a lookalike host). + { host: ".notrumble.com", name: "cf_clearance", value: "x", creationTime: us("2026-11-16T09:30:00Z") }, + { host: ".youtube.com", name: "SID", value: "x", lastAccessed: us("2026-11-16T08:00:00Z"), creationTime: us("2026-01-01T00:00:00Z") }, + { host: ".youtube.com", name: "__Secure-3PSID", value: "x", lastAccessed: us("2026-11-16T08:30:00Z") }, + { host: ".youtube.com", name: "PREF", value: "x", lastAccessed: us("2026-11-16T09:59:00Z") }, + ]); + const out = await readFirefoxServiceCookieTimes(path.join(dir, "cookies.sqlite"), { tmpRoot: TMP }); + assert.deepEqual(out.rumble, { + service: "rumble", + basis: "clearance", + found: true, + at: "2026-11-16T09:00:00.000Z", + expiresAt: "2026-11-16T10:00:00.000Z", + }); + assert.equal(out.youtube.basis, "login-used"); + assert.equal(out.youtube.at, "2026-11-16T08:30:00.000Z"); + assert.equal(out.youtube.expiresAt, undefined); + assert.deepEqual(out.odysee, { service: "odysee", basis: "clearance", found: false, at: null }); + // Nothing returned carries a value. + assert.doesNotMatch(JSON.stringify(out), /fixture-not-a-real/); +}); + +test("a cookie only in the write-ahead log counts; a container the spec does not read does not", async () => { + const dir = path.join(TMP, "p2"); + const { db } = await writeFirefoxCookieStore( + dir, + [ + { host: ".rumble.com", name: "cf_clearance", value: "x", creationTime: us("2026-11-16T07:00:00Z") }, + { + host: ".rumble.com", + name: "cf_clearance", + value: "x", + creationTime: us("2026-11-16T09:45:00Z"), + originAttributes: "^userContextId=2", + }, + ], + { keepOpen: true }, + ); + try { + const out = await readFirefoxServiceCookieTimes(path.join(dir, "cookies.sqlite"), { tmpRoot: TMP }); + assert.equal(out.rumble.at, "2026-11-16T07:00:00.000Z"); + const all = await readFirefoxServiceCookieTimes(path.join(dir, "cookies.sqlite"), { tmpRoot: TMP, container: "all" }); + assert.equal(all.rumble.at, "2026-11-16T09:45:00.000Z"); + } finally { + db?.close(); + } +}); + +test("readBrowserCookieAges: a profile path spec, the cache, and fresh", async () => { + const dir = path.join(TMP, "p3"); + await writeFirefoxCookieStore(dir, [ + { host: ".rumble.com", name: "cf_clearance", value: "x", creationTime: us("2026-11-16T09:00:00Z") }, + ]); + const spec = `firefox:${dir}`; + const a = await readBrowserCookieAges(spec, { home: TMP, tmpRoot: TMP, now: 1000 }); + assert.equal(a.services.rumble.at, "2026-11-16T09:00:00.000Z"); + // A rewrite of the store is not seen inside the cache window... + await rm(path.join(dir, "cookies.sqlite")); + await writeFirefoxCookieStore(dir, [ + { host: ".rumble.com", name: "cf_clearance", value: "x", creationTime: us("2026-11-16T09:50:00Z") }, + ]); + const b = await readBrowserCookieAges(spec, { home: TMP, tmpRoot: TMP, now: 2000 }); + assert.equal(b.services.rumble.at, "2026-11-16T09:00:00.000Z"); + // ...and is with fresh. + const c = await readBrowserCookieAges(spec, { home: TMP, tmpRoot: TMP, now: 3000, fresh: true }); + assert.equal(c.services.rumble.at, "2026-11-16T09:50:00.000Z"); +}); + +test("unreadable sources are answers, never throws", async () => { + const none = await readBrowserCookieAges(undefined, { home: TMP }); + assert.equal(none.services.rumble.found, null); + assert.match(none.services.rumble.unknown ?? "", /No cookiesFromBrowser/); + const chrome = await readBrowserCookieAges("chrome", { home: TMP }); + assert.match(chrome.services.youtube.unknown ?? "", /encrypted/); + const missing = await readBrowserCookieAges(`firefox:${path.join(TMP, "no-such-profile")}`, { home: TMP }); + assert.equal(missing.services.odysee.at, null); + assert.ok(missing.services.odysee.unknown); + const corrupt = path.join(TMP, "p4"); + await writeFirefoxCookieStore(corrupt, []); + await writeFile(path.join(corrupt, "cookies.sqlite"), "not a database"); + const bad = await readBrowserCookieAges(`firefox:${corrupt}`, { home: TMP, tmpRoot: TMP }); + assert.match(bad.services.rumble.unknown ?? "", /Could not read Firefox's cookie store/); +}); + +test("a file: spec is aged by the file's mtime", async () => { + const file = path.join(TMP, "cookies.txt"); + await writeFile(file, "# Netscape HTTP Cookie File\n"); + const t = new Date("2026-11-16T06:00:00Z"); + await utimes(file, t, t); + const out = await readBrowserCookieAges(`file:${file}`); + assert.deepEqual(out.services.youtube, { service: "youtube", basis: "file", found: true, at: t.toISOString() }); +}); diff --git a/common/lib/browserCookieAge.ts b/common/lib/browserCookieAge.ts @@ -0,0 +1,205 @@ +// 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 <spec>`: 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, 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<BrowserCookieService, Want> = { + 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<BrowserCookieService, BrowserCookieAge>; +}; + +// 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<BrowserCookieService, BrowserCookieAge> { + const out = {} as Record<BrowserCookieService, BrowserCookieAge>; + 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; +} + +// 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<Record<BrowserCookieService, BrowserCookieAge>> { + 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 tmp = await mkdtemp(path.join(opts.tmpRoot ?? os.tmpdir(), "archilyzer-cookieage-")); + 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<Record<string, unknown>>; + try { + rows = db + .prepare(`${BROWSER_COOKIE_TIMES_SQL}${names.map(() => "?").join(", ")})`) + .all(...names) as Array<Record<string, unknown>>; + } finally { + db.close(); + } + const out = {} as Record<BrowserCookieService, BrowserCookieAge>; + 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<string, Cache> { + const g = globalThis as unknown as Record<symbol, Map<string, Cache>>; + 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<BrowserCookieAges> { + 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<BrowserCookieService, BrowserCookieAge>): 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<BrowserCookieService, BrowserCookieAge>; + 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(); +} diff --git a/common/lib/cookieStatus.test.ts b/common/lib/cookieStatus.test.ts @@ -0,0 +1,178 @@ +// The /cookies screen's rows (cookieStatus.ts): pure, from what the editor read. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/cookieStatus.test.ts + +import test from "node:test"; +import assert from "node:assert/strict"; +import { ageSentence, buildCookieStatus, durationText, forumThreadFor, HEADED_NOTE, type CookieStatusInput } from "./cookieStatus"; +import { emptyServiceCookieState, type ServiceCookieAlertView } from "./serviceCookies"; +import type { BrowserCookieAge } from "./browserCookieAge"; + +const NOW = Date.parse("2026-11-16T10:00:00Z"); +const age = (service: "rumble" | "youtube" | "odysee", over: Partial<BrowserCookieAge> = {}): BrowserCookieAge => ({ + service, + basis: service === "youtube" ? "login-used" : "clearance", + found: false, + at: null, + ...over, +}); + +// The privacy displayers, as settings.privacy would draw them. +const display = { + path: (p: string) => p.replace("/home/user", "/home/user"), + text: (s: string) => s.replace("/home/user", "/home/user"), +}; + +function input(over: Partial<CookieStatusInput> = {}): CookieStatusInput { + return { + now: NOW, + alerts: { alerts: [], pending: [] }, + state: emptyServiceCookieState(), + x: { source: "profile", profileDir: "/home/user/t/.x-session/profile", hasProfile: true }, + ytdlp: { + rumble: { spec: "firefox", specFrom: "settings", age: age("rumble") }, + youtube: { spec: "firefox", specFrom: "settings", age: age("youtube") }, + odysee: { spec: "firefox", specFrom: "settings", age: age("odysee") }, + }, + archive: { dir: "/home/user/t/.archive-session", hasProfile: false }, + forums: [], + running: {}, + display, + ...over, + }; +} + +const row = (p: ReturnType<typeof buildCookieStatus>, s: string) => { + const r = p.rows.find((x) => x.service === s); + assert.ok(r, `no row for ${s}`); + return r; +}; + +test("durations and age sentences", () => { + assert.equal(durationText(12), "12 min"); + assert.equal(durationText(180), "3 h"); + assert.equal(durationText(60 * 24 * 3), "3 days"); + assert.equal(ageSentence("jar written", "2026-11-16T09:48:00Z", NOW), "jar written 12 min ago"); + assert.equal(ageSentence("jar written", "2026-11-16T09:59:40Z", NOW), "jar written just now"); + assert.equal(ageSentence("jar written", null, NOW), null); +}); + +test("the fixed rows, in order, with paths drawn through the displayers", () => { + const p = buildCookieStatus(input()); + assert.deepEqual(p.rows.map((r) => r.service), ["x", "rumble", "youtube", "odysee", "archive.today"]); + assert.equal(row(p, "x").source, "Connected profile (/home/user/t/.x-session/profile)"); + assert.equal(row(p, "archive.today").source, "Archive profile (/home/user/t/.archive-session)"); + assert.doesNotMatch(JSON.stringify(p), /user/); +}); + +test("X with a connected profile: Refresh cookies, the jar's age and its limit", () => { + const p = buildCookieStatus( + input({ + x: { + source: "profile", + profileDir: "/p", + hasProfile: true, + jar: { source: "profile", at: "2026-11-16T09:48:00Z", ageMinutes: 12, maxAgeMinutes: 60, loggedIn: true, fresh: true, readAt: "", summary: "" }, + }, + }), + ); + const x = row(p, "x"); + assert.deepEqual(x.button, { action: "refresh", label: "Refresh cookies" }); + assert.equal(x.age, "jar written 12 min ago"); + assert.equal(x.ageNote, "limit 60 min"); + assert.equal(x.state, "fine"); + assert.equal(x.headed, undefined); +}); + +test("X with no profile: Connect, said to open on the editor's machine", () => { + const x = row(buildCookieStatus(input({ x: { source: "profile", profileDir: "/p", hasProfile: false } })), "x"); + assert.deepEqual(x.button, { action: "connect", label: "Connect X account" }); + assert.equal(x.headed, true); + assert.equal(x.todo, HEADED_NOTE); + assert.equal(x.state, "unknown"); + assert.equal(x.ageUnknown, "No X profile connected yet."); +}); + +test("X with the browser login: open x.com, then Check again", () => { + const x = row( + buildCookieStatus(input({ x: { source: "browser", browserSpec: "firefox:/home/user/ff", profileDir: "/p", hasProfile: false } })), + "x", + ); + assert.deepEqual(x.button, { action: "recheck", label: "Check again" }); + assert.equal(x.todo, "Open x.com in firefox, then Check again (no request is sent to X)."); + assert.equal(x.source, "Browser login (firefox:/home/user/ff)"); +}); + +test("Rumble: a stale alert's headline, the clearance's age and expiry, Check again", () => { + const state = emptyServiceCookieState(); + state.lastGood.rumble = { url: "https://rumble.com/v1", channel: "c", at: "2026-11-16T08:00:00Z" }; + state.actions = { rumble: { at: "2026-11-16T09:30:00Z", action: "recheck", ok: true, result: "stale", message: "still refused" } }; + const alert = { service: "rumble", state: "stale", headline: "Rumble needs fresh cookies: open rumble.com in firefox" } as ServiceCookieAlertView; + const p = buildCookieStatus( + input({ + state, + alerts: { alerts: [alert], pending: [] }, + ytdlp: { + ...input().ytdlp, + rumble: { + spec: "firefox", + specFrom: "channel", + channel: "c", + age: age("rumble", { found: true, at: "2026-11-16T09:20:00Z", expiresAt: "2026-11-16T10:30:00Z" }), + }, + }, + running: { rumble: { action: "recheck", since: "2026-11-16T09:59:00Z" } }, + }), + ); + const r = row(p, "rumble"); + assert.equal(r.state, "stale"); + assert.equal(r.alert, alert.headline); + assert.equal(r.age, "clearance issued 40 min ago"); + assert.equal(r.ageNote, "expires in 30 min"); + assert.equal(r.source, "firefox (channel c)"); + assert.equal(r.todo, "Open rumble.com in firefox, then Check again."); + assert.deepEqual(r.button, { action: "recheck", label: "Check again" }); + assert.equal(r.last?.result, "stale"); + assert.deepEqual(r.running, { action: "recheck", since: "2026-11-16T09:59:00Z" }); +}); + +test("a yt-dlp service with nothing recorded: unknown, and Check again says why it cannot ask", () => { + const p = buildCookieStatus(input()); + const o = row(p, "odysee"); + assert.equal(o.state, "unknown"); + assert.equal(o.ageUnknown, "No clearance cookie for odysee.com in firefox."); + assert.equal(o.button?.disabled, "No Odysee request is recorded yet to ask again."); + const y = row(p, "youtube"); + assert.equal(y.todo, "Open youtube.com in firefox signed in, then Check again."); +}); + +test("a pending first signal is said, not raised", () => { + const p = buildCookieStatus( + input({ alerts: { alerts: [], pending: [{ service: "rumble", label: "Rumble", kind: "embed-403", videos: ["a"], lastSeen: "2026-11-16T09:12:00Z" }] } }), + ); + assert.equal(row(p, "rumble").alert, "One embed 403 at 09:12 UTC; a second video raises the alert."); +}); + +test("forum hosts: from the profiles and from the state, sorted; Connect needs a thread", () => { + const state = emptyServiceCookieState(); + state.lastGood["kiwifarms.st"] = { url: "https://kiwifarms.st/threads/t.1/", at: "2026-11-16T08:00:00Z" }; + const p = buildCookieStatus( + input({ + state, + forums: [ + { host: "kiwifarms.st", dir: "/home/user/t/.forum-session/kiwifarms.st", hasProfile: true, connectedAt: "2026-11-15T10:00:00Z", cleared: true }, + { host: "forum.example.org", dir: "/d", hasProfile: true }, + ], + }), + ); + assert.deepEqual(p.rows.slice(5).map((r) => r.service), ["forum.example.org", "kiwifarms.st"]); + const kf = row(p, "kiwifarms.st"); + assert.equal(kf.label, "Kiwi Farms (kiwifarms.st)"); + assert.equal(kf.age, "connected 24 h ago"); + assert.equal(kf.ageNote, "check passed"); + assert.equal(kf.headed, true); + assert.equal(kf.button?.disabled, undefined); + assert.match(row(p, "forum.example.org").button?.disabled ?? "", /No thread on this forum/); + assert.deepEqual(forumThreadFor(state, "kiwifarms.st"), { url: "https://kiwifarms.st/threads/t.1/" }); + assert.equal(forumThreadFor(state, "forum.example.org"), null); +}); diff --git a/common/lib/cookieStatus.ts b/common/lib/cookieStatus.ts @@ -0,0 +1,310 @@ +// THE COOKIES SCREEN'S ROWS (editor /cookies, plans/cookie-screen.md): one row +// per service the editor reads cookies for — X, Rumble, YouTube, Odysee, +// archive.today and each forum host — saying where its cookies come from, how +// old they are, whether its cookie alert is up, how the last press ended, and +// the ONE thing to press. +// +// Client-safe and pure: the reads are editor/app/lib/cookieStatus.ts, which +// hands this builder what it read and the privacy displayers (every path and +// spec drawn goes through them — settings.privacy decides what a home path or +// a user name looks like). +// +// THE ONE BUTTON PER ROW, and what it runs (each the existing action): +// x, connected profile Refresh cookies refreshXCookies (headless; loads x.com/home) +// x, no profile yet Connect X account (a HEADED window on the editor's machine) +// x, browser login Check again recheck "x" — no request; the line says open x.com +// rumble / youtube / odysee Check again recheck — one request; the line says open the site +// archive.today Connect archive session (headed) +// a forum host Connect forum session (headed), at a thread the app has met + +import type { ServiceCookieAction, ServiceCookieAlertsPayload, ServiceCookieState, XJarStatusView } from "./serviceCookies"; +import { forumServiceKey, serviceFamily, serviceLabel, type ServiceFamily } from "./serviceCookies"; +import type { BrowserCookieAge } from "./browserCookieAge"; + +export type CookieRowState = "stale" | "fine" | "unknown"; + +export type CookieRowButton = { + action: "refresh" | "connect" | "recheck"; + label: string; + // Why it cannot be pressed, when it cannot. + disabled?: string; +}; + +export type CookieRow = { + service: string; + label: string; + family: ServiceFamily; + // Where the cookies come from, already through the privacy displayers. + source: string; + // How old they are: `ageAt` is the time, `ageVerb` what happened then + // ("jar written"); `age` the sentence at readAt ("jar written 12 min ago"). + ageVerb: string | null; + ageAt: string | null; + ageMinutes: number | null; + age: string | null; + // The age limit or expiry, as a clause ("limit 60 min", "expires 10:40 UTC"). + ageNote?: string; + // Why the age is not known, when it is not. + ageUnknown?: string; + state: CookieRowState; + // The alert's sentence (or the pending first signal's), when there is one. + alert?: string; + // What to do by hand, in one line, where no button does it. + todo?: string; + // The button opens a window on the machine running the editor. + headed?: boolean; + button: CookieRowButton | null; + last?: ServiceCookieAction; + running?: CookieRunning; +}; + +export type CookieRunning = { action: CookieRowButton["action"]; since: string; jobId?: string }; + +export type CookieStatusPayload = { readAt: string; rows: CookieRow[] }; + +export type Displayers = { path: (p: string) => string; text: (s: string) => string }; + +export type YtdlpCookieInput = { + // The cookiesFromBrowser yt-dlp uses for this service, and where it is set. + spec?: string; + specFrom: "channel" | "settings"; + channel?: string; + age: BrowserCookieAge; +}; + +export type CookieStatusInput = { + now: number; + alerts: ServiceCookieAlertsPayload; + state: ServiceCookieState; + x: { + source: "profile" | "browser"; + browserSpec?: string; + profileDir: string; + hasProfile: boolean; + jar?: XJarStatusView; + }; + ytdlp: Record<"rumble" | "youtube" | "odysee", YtdlpCookieInput>; + archive: { dir: string; hasProfile: boolean; connectedAt?: string; cleared?: boolean }; + forums: { host: string; dir: string; hasProfile: boolean; connectedAt?: string; cleared?: boolean }[]; + running: Record<string, CookieRunning>; + display: Displayers; +}; + +export const HEADED_NOTE = "Opens a browser window on the editor's machine, not on this device."; + +// "12 min", "3 h", "16 days". +export function durationText(min: number): string { + if (min < 1) return "less than a minute"; + if (min < 120) return `${min} min`; + const h = Math.floor(min / 60); + return h < 48 ? `${h} h` : `${Math.floor(h / 24)} days`; +} + +export function minutesSince(at: string | null | undefined, now: number): number | null { + if (!at) return null; + const t = Date.parse(at); + return Number.isFinite(t) ? Math.max(0, Math.floor((now - t) / 60_000)) : null; +} + +// "jar written 12 min ago" — the client re-derives it every tick. +export function ageSentence(verb: string | null, at: string | null, now: number): string | null { + const m = minutesSince(at, now); + if (!verb || m === null) return null; + return m < 1 ? `${verb} just now` : `${verb} ${durationText(m)} ago`; +} + +function hhmm(at: string): string { + return `${at.slice(11, 16)} UTC`; +} + +function browserWord(spec: string | undefined): string { + const s = spec?.trim() ?? ""; + if (!s) return "the browser"; + if (s.startsWith("file:")) return "a browser"; + return s.split(/[:+]/)[0] || s; +} + +const SITE: Record<"rumble" | "youtube" | "odysee", string> = { + rumble: "rumble.com", + youtube: "youtube.com", + odysee: "odysee.com", +}; + +function alertFields( + service: string, + input: CookieStatusInput, +): { state: CookieRowState | null; alert?: string } { + const a = input.alerts.alerts.find((x) => x.service === service); + // A fix sentence may name a cookies file: drawn through the displayers too. + if (a?.state === "stale") return { state: "stale", alert: input.display.text(a.headline) }; + if (a?.state === "ok-again") return { state: "fine", alert: input.display.text(a.headline) }; + const p = input.alerts.pending.find((x) => x.service === service); + if (p) { + return { + state: null, + alert: `One ${p.kind === "embed-403" ? "embed 403" : p.kind} at ${hhmm(p.lastSeen)}; a second video raises the alert.`, + }; + } + return { state: null }; +} + +export function buildCookieStatus(input: CookieStatusInput): CookieStatusPayload { + const { now, display } = input; + const rows: CookieRow[] = []; + const last = (service: string) => { + const a = input.state.actions?.[service]; + return a ? { last: { ...a, message: display.text(a.message) } } : {}; + }; + const common = (service: string) => ({ + service, + label: serviceLabel(service), + family: serviceFamily(service), + ...last(service), + ...(input.running[service] ? { running: input.running[service] } : {}), + }); + const aged = (verb: string | null, at: string | null) => ({ + ageVerb: at ? verb : null, + ageAt: at, + ageMinutes: minutesSince(at, now), + age: ageSentence(verb, at, now), + }); + const settle = (known: boolean, a: ReturnType<typeof alertFields>): CookieRowState => + a.state ?? (known ? "fine" : "unknown"); + + // ── X ── + { + const x = input.x; + const a = alertFields("x", input); + const jar = x.jar; + if (x.source === "profile") { + const at = jar?.at ?? null; + rows.push({ + ...common("x"), + source: `Connected profile (${display.path(x.profileDir)})`, + ...aged("jar written", at), + ...(jar ? { ageNote: jar.maxAgeMinutes > 0 ? `limit ${jar.maxAgeMinutes} min` : "no age limit" } : {}), + ...(!at ? { ageUnknown: x.hasProfile ? "No cookie jar exported yet." : "No X profile connected yet." } : {}), + state: settle(!!at, a), + ...(a.alert ? { alert: a.alert } : {}), + ...(x.hasProfile + ? { button: { action: "refresh", label: "Refresh cookies" } } + : { headed: true, todo: HEADED_NOTE, button: { action: "connect", label: "Connect X account" } }), + }); + } else { + const at = jar?.at ?? null; + const b = browserWord(x.browserSpec); + rows.push({ + ...common("x"), + source: `Browser login (${display.text(x.browserSpec ?? "no cookiesFromBrowser set")})`, + ...aged("login last used", at), + ...(jar && jar.maxAgeMinutes > 0 ? { ageNote: `limit ${jar.maxAgeMinutes} min` } : {}), + ...(!at ? { ageUnknown: jar?.summary ? display.text(jar.summary) : "Not read." } : {}), + state: settle(!!at, a), + ...(a.alert ? { alert: a.alert } : {}), + todo: `Open x.com in ${b}, then Check again (no request is sent to X).`, + button: { action: "recheck", label: "Check again" }, + }); + } + } + + // ── the yt-dlp services ── + for (const svc of ["rumble", "youtube", "odysee"] as const) { + const y = input.ytdlp[svc]; + const a = alertFields(svc, input); + const verb = + y.age.basis === "file" ? "cookies file written" : y.age.basis === "clearance" ? "clearance issued" : "sign-in last used"; + const at = y.age.at; + const exp = y.age.expiresAt; + const expMin = exp ? Math.floor((Date.parse(exp) - now) / 60_000) : null; + const entry = input.state.services[svc]; + const canAsk = !!input.state.lastGood[svc] || !!entry?.evidence.url; + const lastGood = input.state.lastGood[svc]; + const ageUnknown = + y.age.unknown + ? display.text(y.age.unknown) + : y.age.found === false + ? `No ${svc === "youtube" ? "sign-in" : "clearance"} cookie for ${SITE[svc]} in ${browserWord(y.spec)}.` + : undefined; + rows.push({ + ...common(svc), + source: y.spec + ? `${display.text(y.spec)} (${y.specFrom === "channel" && y.channel ? `channel ${y.channel}` : "cookiesFromBrowser"})` + : "No browser cookies (cookiesFromBrowser is not set)", + ...aged(verb, at), + ...(expMin !== null ? { ageNote: expMin > 0 ? `expires in ${durationText(expMin)}` : `expired ${durationText(-expMin)} ago` } : {}), + ...(ageUnknown && !at ? { ageUnknown } : {}), + state: settle(!!at || !!lastGood, a), + ...(a.alert + ? { alert: a.alert } + : lastGood + ? { alert: `Last clean request ${durationText(minutesSince(lastGood.at, now) ?? 0)} ago.` } + : {}), + todo: `Open ${SITE[svc]} in ${browserWord(y.spec)}${svc === "youtube" ? " signed in" : ""}, then Check again.`, + button: { + action: "recheck", + label: "Check again", + ...(canAsk ? {} : { disabled: `No ${serviceLabel(svc)} request is recorded yet to ask again.` }), + }, + }); + } + + // ── archive.today ── + { + const ar = input.archive; + const a = alertFields("archive.today", input); + const at = ar.connectedAt ?? null; + rows.push({ + ...common("archive.today"), + source: `Archive profile (${display.path(ar.dir)})`, + ...aged("connected", at), + ...(at ? { ageNote: ar.cleared ? "check passed" : "check not passed" } : {}), + ...(!at ? { ageUnknown: ar.hasProfile ? "Profile present, never connected here." : "Never connected." } : {}), + state: settle(!!at, a), + ...(a.alert ? { alert: a.alert } : {}), + headed: true, + todo: HEADED_NOTE, + button: { action: "connect", label: "Connect archive session" }, + }); + } + + // ── each forum host ── + const hosts = new Map<string, CookieStatusInput["forums"][number] | null>(); + for (const f of input.forums) hosts.set(forumServiceKey(f.host), f); + for (const key of [...Object.keys(input.state.services), ...Object.keys(input.state.lastGood)]) { + if (serviceFamily(key) === "forum" && !hosts.has(key)) hosts.set(key, null); + } + for (const [host, f] of [...hosts.entries()].sort(([a], [b]) => a.localeCompare(b))) { + const a = alertFields(host, input); + const at = f?.connectedAt ?? null; + const entry = input.state.services[host]; + const thread = input.state.lastGood[host]?.url ?? entry?.evidence.url; + rows.push({ + ...common(host), + source: f ? `Forum profile (${display.path(f.dir)})` : "No forum profile yet", + ...aged("connected", at), + ...(at ? { ageNote: f?.cleared ? "check passed" : "check not passed" } : {}), + ...(!at ? { ageUnknown: f?.hasProfile ? "Profile present, never connected here." : "Never connected." } : {}), + state: settle(!!at, a), + ...(a.alert ? { alert: a.alert } : {}), + headed: true, + todo: HEADED_NOTE, + button: { + action: "connect", + label: "Connect forum session", + ...(thread ? {} : { disabled: "No thread on this forum is recorded yet: connect from the thread's channel page." }), + }, + }); + } + + return { readAt: new Date(now).toISOString(), rows }; +} + +// The thread a forum host's Connect opens at: the last clean page, else the +// page that met the check. +export function forumThreadFor(state: ServiceCookieState, host: string): { url: string; channel?: string } | null { + const good = state.lastGood[host]; + if (good) return { url: good.url, ...(good.channel ? { channel: good.channel } : {}) }; + const e = state.services[host]; + if (e?.evidence.url) return { url: e.evidence.url, ...(e.evidence.channel ? { channel: e.evidence.channel } : {}) }; + return null; +} diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -261,6 +261,7 @@ const DECLARED: EnvVarDecl[] = [ { name: "E2E_UMTOOL_ORIGIN_FILE", audience: "test", default: "unset (UMTOOL_URL)", readBy: "common/lib/umtoolUrl.ts", doc: "A file holding one loopback origin; while it exists, umtool is that origin for the editor's Find clips — the stub umtool `find-clips.spec` starts. The editor's e2e server names a file in each slot's test data; anything but a loopback origin in it is ignored." }, { name: "E2E_WAYBACK_ORIGIN_FILE", audience: "test", default: "unset (the real Wayback Machine)", readBy: "common/lib/waybackClient.ts", doc: "A file holding one loopback origin; while it exists, the editor's Wayback client sends every web.archive.org request (CDX, captures, the video index, Save Page Now) there — the fake Wayback a spec starts (`common/testing/web/fakeWayback.mjs`). The editor's e2e server names a file in each slot's test data (`wayback-pages.spec`); anything but a loopback origin in it is ignored." }, { name: "E2E_ARCHIVE_TODAY_ORIGIN_FILE", audience: "test", default: "unset (the real archive.today)", readBy: "common/lib/archives/archiveTodayClient.ts, common/lib/archives/index.ts", doc: "A file holding one loopback origin; while it exists, the editor's archive.today client sends every request for any archive.today name (archive.ph, archive.today, archive.is, …) there — the fake archive.today a spec starts (`common/testing/web/fakeArchiveToday.mjs`) — and never opens the archive session's browser. The editor's e2e server names a file in each slot's test data (`archive-today-pages.spec`); anything but a loopback origin in it is ignored." }, + { name: "E2E_FAKE_X_PROFILE_COOKIES_FILE", audience: "test", default: "unset (Refresh cookies opens the X profile in a real headless browser)", readBy: "common/social/fakeXProfileBrowser.ts (editor/app/settings/xSessionActions.ts)", doc: "A JSON file of SYNTHETIC cookies (`{delayMs?, fail?, cookies}`); while it exists, Refresh cookies reads the X profile through a fake browser that hands them back and loads nothing — no browser starts, nothing is asked of X. Inert unless `E2E_TEST_ROUTES=1` and the file is inside the process's transcriptsDir. The editor's e2e server names a file in each slot's test data (`cookies-screen.spec`)." }, { name: "E2E_BLUESKY_ORIGIN_FILE", audience: "test", default: "unset (the real Bluesky)", readBy: "common/social/blueskyEndpoints.ts", doc: "A file holding one loopback origin; while it exists, the Bluesky AppView, bsky.app and its image CDN are that origin — the fake Bluesky a spec starts (`common/testing/social/fakeBluesky.mjs`). The editor's e2e server names a file in each slot's test data (`capture-posts.spec`); anything but a loopback origin in it is ignored." }, { name: "E2E_AUDIO_CHECK_DEBUG_PAUSE_MS", audience: "test", default: "off", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "A debugging pause inside the audio check." }, { name: "E2E_FAKE_YTDLP_AUDIO_CHECK_MODE", audience: "test", default: "—", readBy: "editor/e2e/fixtures/bin/fake-ytdlp.mjs", doc: "Fake yt-dlp: which audio-check scenario to act out." }, diff --git a/common/lib/serviceCookies-server.test.ts b/common/lib/serviceCookies-server.test.ts @@ -18,6 +18,7 @@ import { markServiceCookieRerun, noteArchiveTodayOutcome, noteForumServiceOutcome, + noteServiceCookieAction, noteServiceCookieClean, noteServiceCookieSignal, observeYtdlpServiceOutcome, @@ -227,3 +228,31 @@ test("a Rumble listing 403 on a channel with no cookie config names the missing await rm(paths.transcriptsDir, { recursive: true, force: true }); } }); + +test("the last press per service is recorded, replaced by the next, and coerced back", async () => { + const paths = await tmpPaths(); + try { + await noteServiceCookieAction(paths, "x", { action: "refresh", ok: true, message: "Cookies refreshed." }, Date.parse("2026-11-16T09:00:00Z")); + await noteServiceCookieAction( + paths, + "rumble", + { action: "recheck", ok: false, result: "stale", message: "Rumble still refused.", jobId: "job-1" }, + Date.parse("2026-11-16T09:01:00Z"), + ); + await noteServiceCookieAction(paths, "x", { action: "refresh", ok: false, message: "No X session profile yet." }, Date.parse("2026-11-16T09:02:00Z")); + const state = await readServiceCookieState(paths); + assert.deepEqual(state.actions, { + x: { at: "2026-11-16T09:02:00.000Z", action: "refresh", ok: false, message: "No X session profile yet." }, + rumble: { at: "2026-11-16T09:01:00.000Z", action: "recheck", ok: false, result: "stale", message: "Rumble still refused.", jobId: "job-1" }, + }); + // A torn record is dropped, never thrown on. + const raw = JSON.parse(await readFile(serviceCookiesFile(paths), "utf8")); + raw.actions.youtube = { at: "not a time", action: "refresh" }; + raw.actions["not a service!"] = { at: "2026-11-16T09:00:00Z", action: "refresh" }; + raw.actions.odysee = { at: "2026-11-16T09:00:00Z", action: "explode" }; + await writeFile(serviceCookiesFile(paths), JSON.stringify(raw)); + assert.deepEqual(Object.keys((await readServiceCookieState(paths)).actions ?? {}).sort(), ["rumble", "x"]); + } finally { + await rm(paths.transcriptsDir, { recursive: true, force: true }); + } +}); diff --git a/common/lib/serviceCookies-server.ts b/common/lib/serviceCookies-server.ts @@ -33,6 +33,7 @@ import { serviceCookieSignalFromStderr, serviceLabel, serviceStoppedLine, + type ServiceCookieAction, type ServiceCookieEntry, type ServiceCookieSignal, type ServiceCookieState, @@ -331,6 +332,25 @@ export async function markServiceCookieRerun( ); } +// The last press on a service's own button and how it ended (the /cookies +// screen's "last result"). Never throws: a press is not failed by its +// bookkeeping. +export async function noteServiceCookieAction( + paths: Pick<Paths, "transcriptsDir">, + service: string, + action: Omit<ServiceCookieAction, "at">, + now: number = Date.now(), +): Promise<void> { + await mutate( + paths, + (state, at) => { + (state.actions ??= {})[service] = { at: new Date(at).toISOString(), ...action, message: action.message.slice(0, 600) }; + return { changed: true, out: undefined }; + }, + now, + ).catch(() => undefined); +} + // ── X (plans/pacing-guard.md) ───────────────────────────────────────────── // One gallery-dl run against X: a challenge or login-wall line raises the X diff --git a/common/lib/serviceCookies.ts b/common/lib/serviceCookies.ts @@ -105,7 +105,7 @@ export function serviceFixText(service: string, browser?: string, kind?: Service 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 " + + "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` ); } @@ -117,10 +117,10 @@ export function serviceFixText(service: string, browser?: string, kind?: Service case "odysee": return `open odysee.com in ${b} and let its check pass`; case ARCHIVE_TODAY_SERVICE: - return "Connect archive session (Settings → Archive sources) and pass the check once in the window"; + 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 /settings and clear it in the window (with the " + + "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" ); default: @@ -258,10 +258,29 @@ export type ServiceCookieLastGood = { 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<string, ServiceCookieEntry>; lastGood: Record<string, ServiceCookieLastGood>; + // Absent until a press is recorded (an older file has none). + actions?: Record<string, ServiceCookieAction>; }; export const PENDING_SIGNAL_TTL_MS = 60 * 60_000; @@ -364,6 +383,28 @@ export function coerceServiceCookieState(raw: unknown): ServiceCookieState { : {}), }; } + const actions = r.actions && typeof r.actions === "object" ? (r.actions as Record<string, unknown>) : null; + if (actions) { + for (const [key, v] of Object.entries(actions)) { + if (!isServiceKey(key) || !v || typeof v !== "object") continue; + const a = v as Record<string, unknown>; + 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; } @@ -665,7 +706,7 @@ export function buildServiceCookieAlerts( 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 /settings — 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})` : ""}.` diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -197,7 +197,7 @@ export const X_SOCIAL_SETTINGS_FIELD_DOCS: FieldDocs<XSocialSettings> = { "(Fetch posts, the older walk, an X search, Capture posts, Import one post, Check deleted " + "posts — and the scheduler's fetches) is refused when it STARTS unless the profile's exported " + "cookie jar was written within this many minutes and carries a login (an auth_token). The " + - "refusal says what to do: press Refresh cookies (or Connect X account) on /settings, then " + + "refusal says what to do: press Refresh cookies (or Connect X account) on /cookies, then " + "fetch again. A refresh is a human click — it loads x.com/home, itself a request to X — so " + "the editor never refreshes the jar to satisfy this. With the `\"browser\"` source the age " + "cannot be read: the job logs that and proceeds. ABSENT: 60. 0 turns the rule off; at most " + diff --git a/common/social/fakeXProfileBrowser.test.ts b/common/social/fakeXProfileBrowser.test.ts @@ -0,0 +1,64 @@ +// The e2e suite's fake "Refresh cookies" browser (fakeXProfileBrowser.ts) is +// inert unless the process is the test server AND the file is inside its +// transcriptsDir AND exists; when live, refreshXCookies runs on it end to end +// with no browser and no request. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/fakeXProfileBrowser.test.ts + +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { fakeXProfileChromium, fakeXProfileCookiesFile } from "./fakeXProfileBrowser"; +import { readXSessionStatus, refreshXCookies } from "./xSessionBroker"; + +test("the gate: test server, inside transcriptsDir, the file exists", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "fake-x-")); + try { + const t = path.join(root, "transcripts"); + await mkdir(t); + const inside = path.join(t, ".fake-x-profile-cookies.json"); + const outside = path.join(root, "elsewhere.json"); + await writeFile(outside, "{}"); + const env = { E2E_TEST_ROUTES: "1", E2E_FAKE_X_PROFILE_COOKIES_FILE: inside }; + // Not written yet. + assert.equal(fakeXProfileCookiesFile(t, env), null); + await writeFile(inside, "{}"); + assert.equal(fakeXProfileCookiesFile(t, env), inside); + // Not the test server: inert, even with the file there. + assert.equal(fakeXProfileCookiesFile(t, { E2E_FAKE_X_PROFILE_COOKIES_FILE: inside }), null); + assert.equal(fakeXProfileCookiesFile(t, { ...env, E2E_TEST_ROUTES: "0" }), null); + assert.equal(fakeXProfileChromium(t, { E2E_FAKE_X_PROFILE_COOKIES_FILE: inside }), null); + // A file outside the test data: inert. + assert.equal(fakeXProfileCookiesFile(t, { ...env, E2E_FAKE_X_PROFILE_COOKIES_FILE: outside }), null); + assert.equal(fakeXProfileCookiesFile(t, { ...env, E2E_FAKE_X_PROFILE_COOKIES_FILE: path.join(t, "..", "elsewhere.json") }), null); + assert.equal(fakeXProfileCookiesFile(t, { E2E_TEST_ROUTES: "1" }), null); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("refreshXCookies on the fake writes the jar from the fixture's cookies", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "fake-x-")); + try { + const paths = { transcriptsDir: root } as Parameters<typeof refreshXCookies>[0]; + await mkdir(path.join(root, ".x-session", "profile"), { recursive: true }); + const file = path.join(root, ".fake-x-profile-cookies.json"); + await writeFile( + file, + JSON.stringify({ cookies: [{ name: "auth_token", value: "fixture-not-a-token", domain: ".x.com" }] }), + ); + const chromium = fakeXProfileChromium(root, { E2E_TEST_ROUTES: "1", E2E_FAKE_X_PROFILE_COOKIES_FILE: file }); + assert.ok(chromium); + const status = await refreshXCookies(paths, { chromium }); + assert.equal(status.looksAuthenticated, true); + assert.equal((await readXSessionStatus(paths)).hasCookies, true); + assert.match(await readFile(path.join(root, ".x-session", "cookies.txt"), "utf8"), /\.x\.com\tTRUE\t\/\tTRUE\t0\tauth_token/); + // `fail` makes the launch throw, as a profile the browser cannot open. + await writeFile(file, JSON.stringify({ fail: "profile locked" })); + await assert.rejects(refreshXCookies(paths, { chromium }), /profile locked/); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/common/social/fakeXProfileBrowser.ts b/common/social/fakeXProfileBrowser.ts @@ -0,0 +1,94 @@ +// A FAKE BROWSER FOR "Refresh cookies", for the editor's e2e suite only +// (E2E_FAKE_X_PROFILE_COOKIES_FILE, set per slot by editor/e2e/servers.ts). +// refreshXCookies (xSessionBroker.ts) takes a `chromium`; under the test server +// it is handed this one, whose persistent context hands back the cookies a +// spec wrote into the file (after its `delayMs`, so a spec can watch the press +// run and be refused a second time) and whose page loads nothing — no browser +// starts and nothing is asked of X. Everything after the browser (the jar +// written, the login check, the status) is the real code. +// +// INERT ON A REAL EDITOR, three ways: it answers null unless the process is the +// e2e test server (E2E_TEST_ROUTES=1, which editor/playwright.config.ts sets on +// its server and nothing else does), unless the variable names a file INSIDE +// this process's transcriptsDir (a slot's test data), and unless that file +// exists (a spec writes it). The file holds SYNTHETIC cookies only: +// { "delayMs"?: number, "fail"?: string, "cookies": [{ name, value, domain, path?, expires? }] } + +import { readFileSync } from "node:fs"; +import path from "node:path"; +import type { BrowserContextLike, ChromiumLike, PageLike } from "./playwrightRuntime"; + +type FixtureFile = { + delayMs?: number; + fail?: string; + cookies?: Array<{ name: string; value: string; domain: string; path?: string; expires?: number }>; +}; + +export function fakeXProfileCookiesFile( + transcriptsDir: string, + env: Readonly<Record<string, string | undefined>> = process.env, +): string | null { + if (env.E2E_TEST_ROUTES !== "1") return null; + const file = env.E2E_FAKE_X_PROFILE_COOKIES_FILE?.trim(); + if (!file) return null; + const rel = path.relative(path.resolve(transcriptsDir), path.resolve(file)); + if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return null; + try { + readFileSync(file); + } catch { + return null; + } + return path.resolve(file); +} + +function readFixture(file: string): FixtureFile { + return JSON.parse(readFileSync(file, "utf8")) as FixtureFile; +} + +// The fake, or null when the gate above says no. +export function fakeXProfileChromium( + transcriptsDir: string, + env: Readonly<Record<string, string | undefined>> = process.env, +): ChromiumLike | null { + const file = fakeXProfileCookiesFile(transcriptsDir, env); + if (!file) return null; + const wait = (ms: number) => new Promise<void>((r) => setTimeout(r, ms)); + const page = { + goto: async () => { + const f = readFixture(file); + if (f.delayMs && f.delayMs > 0) await wait(Math.min(f.delayMs, 30_000)); + return null; + }, + waitForSelector: async () => null, + waitForTimeout: wait, + evaluate: async () => null, + on: () => {}, + } as unknown as PageLike; + const context: BrowserContextLike = { + newPage: async () => page, + pages: () => [page], + cookies: async () => + (readFixture(file).cookies ?? []).map((c) => ({ + name: c.name, + value: c.value, + domain: c.domain, + path: c.path ?? "/", + expires: c.expires ?? -1, + httpOnly: true, + secure: true, + })), + addCookies: async () => {}, + close: async () => {}, + on: () => {}, + }; + return { + launch: async () => { + throw new Error("the fake X profile browser launches no browser"); + }, + launchPersistentContext: async () => { + const f = readFixture(file); + if (f.fail) throw new Error(f.fail); + return context; + }, + }; +} diff --git a/common/social/xCookieSource.ts b/common/social/xCookieSource.ts @@ -59,7 +59,7 @@ export type XSocialSettings = { }; // Absent `social.x.maxCookieAgeMinutes`: an hour. A refresh is a human click -// on /settings (refreshXCookies loads x.com/home — itself a request to X), so +// on /cookies (refreshXCookies loads x.com/home — itself a request to X), so // the editor never refreshes the jar on its own to satisfy this. export const X_DEFAULT_MAX_COOKIE_AGE_MINUTES = 60; // A week: past that, "fresh" means nothing. diff --git a/common/social/xGalleryDlFetcher.ts b/common/social/xGalleryDlFetcher.ts @@ -93,7 +93,7 @@ export function xBlockedError(line: string): string { return ( `X answered with a challenge or a login wall (${line.trim().slice(0, 200)}): stopped here, posts read so far ` + "kept. The X cookie alert is up — no X job starts until it is cleared (pass X's check by hand, Refresh " + - "cookies on /settings, then Recheck on the dashboard)." + "cookies on /cookies, then Recheck on the dashboard)." ); } @@ -399,7 +399,7 @@ export async function captureXPostsByIds( const status = await readXSessionStatus(paths); if (!status.hasProfile) { const why = - "No X session profile to shoot posts or open articles with: connect an X account on /settings, then run it again."; + "No X session profile to shoot posts or open articles with: connect an X account on /cookies, then run it again."; input.onLog?.(`[auth] ${why}`); return { outcomes: [], needsCookies: true, stoppedEarly: why }; } @@ -928,7 +928,7 @@ function readLines( } const SEARCH_NEEDS_LOGIN = - "X search needs a logged-in session: connect an X account on /settings, or " + + "X search needs a logged-in session: connect an X account on /cookies, or " + "set cookiesFromBrowser for this channel (or globally), then run it again."; // The older-posts backfill: search windows walked backwards from `position` diff --git a/common/social/xJarAge.ts b/common/social/xJarAge.ts @@ -131,11 +131,11 @@ export function xJarStatusFrom(input: { 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." + ? "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 /settings." + ? "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 /settings."); + (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."