// THE ARCHIVE SESSION (release 37 lane F): one persistent Chromium profile for // archive.today, opened HEADLESS by the client when archive.today answers a // plain request with a check, and HEADED by Connect archive session. // // The forum browser's model (social/forumSession.ts), for one service: a check // a person passes once in a real window sets a clearance cookie the profile // keeps, so later reads through the headless profile go through. A window // opens only on the operator's explicit action (the channel page's Archived // pages panel, or Settings), never from a job; the headless read waits a check // out (its own script may clear it) and never clicks, types or solves // anything. A check that still stands is refused with a sentence. // // Layout: transcripts/.archive-session/archive.today/profile/ (the profile), // transcripts/.archive-session/archive.today/session.json (the last Connect). import path from "node:path"; import { stat } from "node:fs/promises"; import type { Paths } from "../paths"; import { readJsonFile, writeJsonAtomic } from "../jsonFile-server"; import { importPlaywright, type BrowserContextLike, type ChromiumLike, type PageLike } from "../../social/playwrightRuntime"; import { openForumProfile } from "../../social/forumSession"; import { describeXBrowser, findXBrowser, writeXBrowserRecord } from "../../social/xBrowser"; import { launchHeadedContext, type HeadedDisplayLaunchDeps } from "../../social/headedDisplay"; import { isArchiveTodayChallenge } from "./archiveToday"; import type { ArchiveTodayBrowser, ArchiveTodayBrowserLoad } from "./archiveTodayClient"; export const ARCHIVE_SESSION_SERVICE = "archive.today"; export function archiveSessionDir(paths: Pick): string { return path.join(paths.transcriptsDir, ".archive-session", ARCHIVE_SESSION_SERVICE); } export function archiveProfileDir(paths: Pick): string { return path.join(archiveSessionDir(paths), "profile"); } export type ArchiveSessionRecord = { service: string; host: string; connectedAt: string; // The window's last look before it closed: was a page showing that is not a // check, and how many cookies archive.today had set. cleared: boolean; cookies: number; browser?: string; // The display the window opened on and where it was found // (social/headedDisplay.ts): "DISPLAY=:0 (from the user session)". display?: string; }; export type ArchiveSessionStatus = { service: string; hasProfile: boolean; lastConnect?: ArchiveSessionRecord; }; export async function readArchiveSessionStatus(paths: Pick): Promise { const dir = archiveSessionDir(paths); const hasProfile = await stat(path.join(dir, "profile")).then(() => true, () => false); const read = await readJsonFile(path.join(dir, "session.json")); const rec = read.ok ? (read.value as ArchiveSessionRecord | null) : null; return { service: ARCHIVE_SESSION_SERVICE, hasProfile, ...(rec && typeof rec.connectedAt === "string" ? { lastConnect: rec } : {}), }; } const firstLine = (err: unknown) => ((err as Error)?.message ?? String(err)).split("\n")[0]; const OUTER_HTML = "document.documentElement ? document.documentElement.outerHTML : ''"; const INNER_TEXT = "document.body ? document.body.innerText : ''"; export const ARCHIVE_CHALLENGE_WAIT_MS = 45_000; // Go to `url` and read what the page shows, waiting a check out (up to // `timeoutMs`; its own script may clear it and reload). Nothing is clicked. export async function loadArchivePage( page: PageLike, url: string, o: { signal?: AbortSignal; timeoutMs?: number; pollMs?: number; now?: () => number; onLog?: (l: string) => void } = {}, ): Promise { const now = o.now ?? Date.now; let status: number | undefined; try { const res = (await page.goto(url, { waitUntil: "domcontentloaded", timeout: 60_000 })) as { status?: () => number } | null; status = typeof res?.status === "function" ? res.status() : undefined; } catch (err) { if (!/interrupted|ERR_ABORTED|frame was detached/i.test(firstLine(err))) throw new Error(`Could not load ${url}: ${firstLine(err)}`); } const read = async () => { try { return { html: String(await page.evaluate(OUTER_HTML)), text: String(await page.evaluate(INNER_TEXT)) }; } catch { return null; } }; let got = (await read()) ?? { html: "", text: "" }; if (isArchiveTodayChallenge(got.html)) { o.onLog?.(`archive.today showed a check in the headless browser; waiting up to ${Math.round((o.timeoutMs ?? ARCHIVE_CHALLENGE_WAIT_MS) / 1000)} s for it to clear by itself.`); const started = now(); while (now() - started < (o.timeoutMs ?? ARCHIVE_CHALLENGE_WAIT_MS)) { if (o.signal?.aborted) break; await page.waitForTimeout(o.pollMs ?? 2_000); const next = await read(); if (!next) continue; got = next; if (!isArchiveTodayChallenge(got.html)) break; } } let href = url; try { const h = String(await page.evaluate("location.href")); if (h && h !== "about:blank") href = h; } catch { // keep the asked URL } return { ...got, url: href, ...(status !== undefined ? { status } : {}) }; } // The client's `openBrowser`: the archive profile, headless, one page; closed // by the client after the one read. export function archiveSessionBrowser( paths: Pick, o: { onLog?: (l: string) => void; chromium?: ChromiumLike; timeoutMs?: number } = {}, ): () => Promise { return async () => { const context: BrowserContextLike = await openForumProfile(archiveProfileDir(paths), { onLog: o.onLog, chromium: o.chromium }); const page = context.pages()[0] ?? (await context.newPage()); return { load: (url, signal) => loadArchivePage(page, url, { signal, onLog: o.onLog, timeoutMs: o.timeoutMs }), close: () => context.close(), }; }; } // CONNECT: a HEADED window on the archive profile at `url` (archive.today's // front page by default), on the display of the machine running the editor, // for the operator to pass the check once and close it. Resolves when the // window closes, with its last look. export async function connectArchiveSession( paths: Pick, url: string, o: { onLog?: (l: string) => void; timeoutMs?: number; env?: Record; // Injectable for tests: a stand-in browser, and the display search's // runner and file system (social/headedDisplay.ts). chromium?: ChromiumLike; display?: HeadedDisplayLaunchDeps; } = {}, ): Promise { const log = o.onLog ?? (() => {}); const host = new URL(url).hostname.toLowerCase(); const profileDir = archiveProfileDir(paths); // The profile directory is made by launchHeadedContext, once a display is found. const browser = findXBrowser({ env: o.env }); const label = describeXBrowser(browser); const chromium = o.chromium ?? (await importPlaywright()).chromium; log(`Opening ${label} at ${host}. Pass the check if one shows, wait for the page, then close the window.`); // On the desktop's display, found at this press (social/headedDisplay.ts): // refused with a sentence when there is none. const { context, display } = await launchHeadedContext({ chromium, profileDir, browser, onLog: log, env: o.env, display: o.display, }); await writeXBrowserRecord(profileDir, browser).catch(() => {}); let cleared = false; let cookies = 0; const look = async () => { try { const page = context.pages()[0]; if (page) cleared = !isArchiveTodayChallenge(String(await page.evaluate(OUTER_HTML))); cookies = ((await context.cookies()) as { domain?: string }[]).filter((c) => /archive\.(?:ph|today|is|li|vn|fo|md)$/i.test((c.domain ?? "").replace(/^\./, "")), ).length; } catch { // closing, or mid-navigation } }; try { const page = context.pages()[0] ?? (await context.newPage()); await page.goto(url, { waitUntil: "domcontentloaded", timeout: 60_000 }).catch((err: unknown) => { log(`The first load did not finish (${firstLine(err)}); the window stays open.`); }); await new Promise((resolve) => { let settled = false; const timer = setInterval(() => void look(), 2_000); const finish = () => { if (settled) return; settled = true; clearInterval(timer); resolve(); }; context.on("close", finish); if (o.timeoutMs) setTimeout(finish, o.timeoutMs); }); } finally { await context.close().catch(() => {}); } const record: ArchiveSessionRecord = { service: ARCHIVE_SESSION_SERVICE, host, connectedAt: new Date().toISOString(), cleared, cookies, browser: label, display, }; await writeJsonAtomic(path.join(archiveSessionDir(paths), "session.json"), record, { mkdir: true }); log( cleared ? `A page that is not a check showed before the window closed; ${cookies} cookie(s) for archive.today kept in the profile.` : `The window closed with a check still showing; ${cookies} cookie(s) for archive.today in the profile.`, ); return record; }