// THE POLITE archive.today CLIENT (release 37 lane F): every request this app // makes to archive.today — a page's timemap, one copy's bytes. archive.today is // one person's service and says so; the rules here are the operator's "polite // scraping", made mechanical: // // ONE AT A TIME requests are chained: a second caller waits for the first // to finish, and then for the gap. // A LONG GAP at least `minGapMs` (8 s; settings.archives) between the // end of one request and the start of the next, plus up to // a quarter more at random. // IDENTIFIED a User-Agent naming the project and its URL. // STOPS AT A 429 "too many requests" is not waited out and retried: the // run stops with a sentence (ArchiveRefusal // "rate-limited"), and the client sends NOTHING to // archive.today for `cooldownMs` (30 min) or the // Retry-After, whichever is longer. A 502/503/504 (or a // dropped connection) is retried after an exponential // wait, a few times. // NEVER SOLVES archive.today often answers a client that is not a // browser with a check (a CAPTCHA, a browser check). That // is told apart from a copy (lib/archives/archiveToday.ts // isArchiveTodayChallenge) and never parsed as one. With a // browser (`openBrowser`), the copy is read once more // through the headless browser on the archive session's // profile — a check the operator cleared in Connect // archive session stays cleared there — and a check that // still stands is refused ("challenge"). Nothing is ever // clicked or answered by code. // // Every URL is sent to ONE canonical host (settings.archives.archiveTodayHost, // default archive.ph), whichever of archive.today's names a copy's URL used. import { createHash } from "node:crypto"; import { readFileSync } from "node:fs"; import { PROJECT_NAME, PROJECT_URL } from "../project"; import { bareMimetype, isPageMimetype, PAGE_MIMETYPES } from "../waybackPages/urls"; import { archiveTodayHostOf, isArchiveTodayHost, parseArchiveTodayUrl, } from "./mementos"; import { challengeDetail, copyFactsFromHeaders, copyFactsFromHtml, isArchiveTodayChallenge, nearestCapture, parseArchiveTodayTimemap, unwrapArchiveTodayHtml, withinCaptureRange, } from "./archiveToday"; import { ArchiveRefusal, type ArchiveCaptureRow, type ArchiveMementoRef, type ArchiveRawCapture } from "./types"; export const ARCHIVE_TODAY_QUEUE = "platform:archive.today"; // Identifies the project ON PURPOSE (an archive asks bots to say who they are) — never the derived browser UA. export const ARCHIVE_TODAY_USER_AGENT = `${PROJECT_NAME} archive.today import (+${PROJECT_URL})`; export const ARCHIVE_TODAY_MAX_REDIRECTS = 5; // A copy's body is read up to this (the Wayback page cap's size). export const ARCHIVE_TODAY_PAGE_MAX_BYTES = 2 * 1024 * 1024; // A non-200 answer's body is read this far (enough to tell a check page). const ERROR_BODY_BYTES = 256 * 1024; const PAGE_ACCEPT = "text/html,application/xhtml+xml;q=0.9,*/*;q=0.1"; const RETRYABLE = new Set([502, 503, 504]); // The connect sentence every challenge refusal ends with. export const CONNECT_ARCHIVE_SESSION_HINT = "Connect archive session (the channel page's Archived pages panel, or Settings), pass the check once in the window, then try again"; export class ArchiveTodayRequestError extends Error { readonly status: number | null; constructor(message: string, status: number | null) { super(message); this.name = "ArchiveTodayRequestError"; this.status = status; } } // What the headless browser hands back for one URL. export type ArchiveTodayBrowserLoad = { html: string; text: string; url: string; status?: number }; export type ArchiveTodayBrowser = { load(url: string, signal?: AbortSignal): Promise; close(): Promise; }; export type ArchiveTodayClientDeps = { fetch?: (url: string, init: RequestInit) => Promise; now?: () => number; sleep?: (ms: number, signal?: AbortSignal) => Promise; random?: () => number; // The headless browser on the archive session's profile, opened only when a // check stands in the way; null/absent = refuse at the check. openBrowser?: (() => Promise) | null; // Read per check: false = refuse at the check (settings can change while // the editor runs). browserEnabled?: () => boolean; // The canonical host, read per request (settings can change while the // editor runs). host?: () => string; // Told of every check that stood and every answer that was not one — the // cookie refresh alert for archive.today (lib/serviceCookies-server.ts). // Its failure never fails the request. observe?: (o: ArchiveTodayObservation) => void | Promise; }; export type ArchiveTodayObservation = | { challenge: true; url: string; line: string } | { challenge: false; url: string }; export type ArchiveTodayClientOpts = { minGapMs?: number | (() => number); // Up to this fraction of the gap again, at random. jitter?: number; cooldownMs?: number | (() => number); maxAttempts?: number; baseBackoffMs?: number; maxBackoffMs?: number; timeoutMs?: number; }; type Answer = { status: number; headers: Headers; location: string | null; body: Buffer | null; bytes: number; tooLarge: boolean; url: string; }; function defaultSleep(ms: number, signal?: AbortSignal): Promise { return new Promise((resolve, reject) => { if (signal?.aborted) return reject(signal.reason ?? new Error("aborted")); const t = setTimeout(() => { signal?.removeEventListener("abort", onAbort); resolve(); }, ms); const onAbort = () => { clearTimeout(t); reject(signal?.reason ?? new Error("aborted")); }; signal?.addEventListener("abort", onAbort, { once: true }); }); } function retryAfterMs(value: string | null, nowMs: number): number | null { if (!value) return null; const v = value.trim(); if (/^\d+$/.test(v)) return Number(v) * 1000; const at = Date.parse(v); return Number.isFinite(at) ? Math.max(0, at - nowMs) : null; } const minutes = (ms: number) => Math.max(1, Math.round(ms / 60_000)); export class ArchiveTodayClient { private readonly deps: Required> & Pick; private readonly opts: Required> & { minGapMs: () => number; cooldownMs: () => number; }; private chain: Promise = Promise.resolve(); private lastDoneAt = -Infinity; private coolUntil = 0; // Requests actually sent (each attempt), and copies read through the // browser — for tests and logs. requests = 0; browserLoads = 0; constructor(deps: ArchiveTodayClientDeps = {}, opts: ArchiveTodayClientOpts = {}) { this.deps = { fetch: deps.fetch ?? ((url, init) => fetch(url, init)), now: deps.now ?? (() => Date.now()), sleep: deps.sleep ?? defaultSleep, random: deps.random ?? Math.random, ...(deps.openBrowser ? { openBrowser: deps.openBrowser } : {}), ...(deps.host ? { host: deps.host } : {}), ...(deps.browserEnabled ? { browserEnabled: deps.browserEnabled } : {}), ...(deps.observe ? { observe: deps.observe } : {}), }; const gap = opts.minGapMs ?? 8_000; const cool = opts.cooldownMs ?? 30 * 60_000; this.opts = { minGapMs: typeof gap === "function" ? gap : () => gap, cooldownMs: typeof cool === "function" ? cool : () => cool, jitter: opts.jitter ?? 0.25, maxAttempts: opts.maxAttempts ?? 3, baseBackoffMs: opts.baseBackoffMs ?? 10_000, maxBackoffMs: opts.maxBackoffMs ?? 120_000, timeoutMs: opts.timeoutMs ?? 60_000, }; } get host(): string { return archiveTodayHostOf(this.deps.host?.() ?? undefined); } // When the client will next send a request after a 429 (epoch ms), or 0. get cooldownUntil(): number { return this.coolUntil > this.deps.now() ? this.coolUntil : 0; } // Any archive.today URL on the canonical host. canonical(url: string): string { const u = new URL(url); if (isArchiveTodayHost(u.hostname)) { u.hostname = this.host; u.protocol = "https:"; u.port = ""; } return u.toString(); } private serial(fn: () => Promise): Promise { const run = this.chain.then(fn, fn); this.chain = run.catch(() => {}); return run; } private assertNotCooling(url: string): void { const now = this.deps.now(); if (this.coolUntil > now) { throw new ArchiveRefusal( "archive.today", "rate-limited", `archive.today answered "too many requests" earlier; nothing is sent to it before ${new Date(this.coolUntil).toISOString()} ` + `(${minutes(this.coolUntil - now)} min) — ${url} was not asked`, { retryAt: this.coolUntil }, ); } } private async waitGap(signal?: AbortSignal): Promise { const gap = this.opts.minGapMs() * (1 + this.deps.random() * this.opts.jitter); const wait = this.lastDoneAt + gap - this.deps.now(); if (wait > 0) await this.deps.sleep(Math.round(wait), signal); } // ONE GET (no redirect followed), the gap before it, its body read up to // `maxBytes` (an error answer's to 256 KB). 502/503/504 and a dropped // connection are retried; a 429 that is not a check page starts the // cool-down and throws. Every other status is answered for the caller. private async send(url: string, o: { accept: string; maxBytes: number; signal?: AbortSignal }): Promise { let lastError = ""; for (let attempt = 1; attempt <= this.opts.maxAttempts; attempt++) { this.assertNotCooling(url); await this.waitGap(o.signal); this.requests++; let res: Response | null = null; let answer: Answer | null = null; try { const timeout = AbortSignal.timeout(this.opts.timeoutMs); res = await this.deps.fetch(url, { signal: o.signal ? AbortSignal.any([o.signal, timeout]) : timeout, redirect: "manual", headers: { accept: o.accept, "user-agent": ARCHIVE_TODAY_USER_AGENT }, }); answer = await readAnswer(res, url, res.status >= 200 && res.status < 300 ? o.maxBytes : ERROR_BODY_BYTES); } catch (err) { if (o.signal?.aborted) throw err; lastError = (err as Error).message; } finally { this.lastDoneAt = this.deps.now(); } if (answer) { if (answer.status === 429 && !(answer.body && isArchiveTodayChallenge(answer.body.toString("utf8")))) { const wait = Math.max(this.opts.cooldownMs(), retryAfterMs(answer.headers.get("retry-after"), this.deps.now()) ?? 0); this.coolUntil = this.deps.now() + wait; throw new ArchiveRefusal( "archive.today", "rate-limited", `archive.today answered HTTP 429 (too many requests) for ${url}; stopped, and nothing is sent to it for ` + `${minutes(wait)} min (until ${new Date(this.coolUntil).toISOString()})`, { retryAt: this.coolUntil }, ); } if (!RETRYABLE.has(answer.status) || (answer.body && isArchiveTodayChallenge(answer.body.toString("utf8")))) return answer; lastError = `HTTP ${answer.status}`; } if (attempt === this.opts.maxAttempts) break; const exp = Math.min(this.opts.maxBackoffMs, this.opts.baseBackoffMs * 2 ** (attempt - 1)); await this.deps.sleep(Math.round(exp * (1 + (this.deps.random() * 0.4 - 0.2))), o.signal); } throw new ArchiveTodayRequestError( `archive.today did not answer ${url} after ${this.opts.maxAttempts} attempts (${lastError}); stopping`, null, ); } // The same URL through the headless browser, in the chain and after the // gap. Null when no browser is offered. private async viaBrowser(url: string, signal?: AbortSignal): Promise { if (!this.deps.openBrowser || this.deps.browserEnabled?.() === false) return null; this.assertNotCooling(url); await this.waitGap(signal); this.browserLoads++; let browser: ArchiveTodayBrowser | null = null; try { browser = await this.deps.openBrowser(); return await browser.load(url, signal); } finally { await browser?.close().catch(() => {}); this.lastDoneAt = this.deps.now(); } } private challengeRefusal(url: string, html: string, triedBrowser: boolean): ArchiveRefusal { return new ArchiveRefusal( "archive.today", "challenge", `archive.today answered ${url} with ${challengeDetail(html)} instead of the copy` + (triedBrowser ? ", in the headless browser too" : "") + `; nothing was read. ${CONNECT_ARCHIVE_SESSION_HINT}`, ); } // The refusal at a check that stood, told to `observe` first (the cookie // refresh alert for archive.today). private async challenged(url: string, html: string, triedBrowser: boolean): Promise { const refusal = this.challengeRefusal(url, html, triedBrowser); await this.note({ challenge: true, url, line: refusal.message }); return refusal; } // An answer that was not a check (a copy, a timemap, a 404): told to // `observe`, which clears a cookie refresh alert. private async answered(url: string, out: T): Promise { await this.note({ challenge: false, url }); return out; } private async note(o: ArchiveTodayObservation): Promise { try { await this.deps.observe?.(o); } catch { // bookkeeping only } } // THE COPIES OF A PAGE, oldest first: its timemap // (`/timemap/`, one request). A 404 is "none". Within // `from`/`to` (capture-time prefixes), at most `limit`. listCaptures( originalUrl: string, o: { from?: string; to?: string; limit?: number; signal?: AbortSignal } = {}, ): Promise { return this.serial(async () => { const url = `https://${this.host}/timemap/${originalUrl}`; const res = await this.send(url, { accept: "application/link-format,text/plain;q=0.9,*/*;q=0.1", maxBytes: 8 * 1024 * 1024, signal: o.signal }); let text: string; if (res.status === 404 || res.status === 410) return this.answered(url, []); const body = res.body?.toString("utf8") ?? ""; if (isArchiveTodayChallenge(body)) { const b = await this.viaBrowser(url, o.signal); if (!b || isArchiveTodayChallenge(b.html)) throw await this.challenged(url, b?.html ?? body, !!b); text = b.text; } else if (res.status >= 200 && res.status < 300) { if (res.tooLarge) throw new ArchiveTodayRequestError(`archive.today's timemap of ${originalUrl} is over 8 MB; not read`, res.status); text = body; } else { throw new ArchiveTodayRequestError(`archive.today answered HTTP ${res.status} for ${url}`, res.status); } const rows = parseArchiveTodayTimemap(text, originalUrl) .map((r) => ({ ...r, mementoUrl: this.canonical(r.mementoUrl) })) .filter((r) => withinCaptureRange(r.captureTs, o.from, o.to)); return this.answered(url, o.limit ? rows.slice(0, o.limit) : rows); }); } // The copy nearest `at` (4–14 digits) — one timemap request — or null. async closestCapture(url: string, at: string, o: { signal?: AbortSignal } = {}): Promise { return nearestCapture(await this.listCaptures(url, { signal: o.signal }), at); } // ONE COPY: its bytes as served (what a page import stores), and the copy // unwrapped as a page (`page`, what the extractors read). A memento URL in // any of its forms; redirects followed inside archive.today only (a // `//`, `/newest/` or `/oldest/` answer is a redirect to the copy), // at most ARCHIVE_TODAY_MAX_REDIRECTS. The copy's time and page come from // the answer's Memento headers, else its header bar, else the URL. // Refused (ArchiveRefusal): no such copy ("not-archived"); a check that // stands ("challenge"); not HTML ("mimetype"); over `maxBytes` // ("too-large"); off archive.today or round in circles; no time or page // to name it by ("unreadable"); a 429 ("rate-limited"). getCapture( memento: string | ArchiveMementoRef, o: { maxBytes?: number; signal?: AbortSignal } = {}, ): Promise { return this.serial(async () => { const maxBytes = o.maxBytes ?? ARCHIVE_TODAY_PAGE_MAX_BYTES; const ref = typeof memento === "string" ? parseArchiveTodayUrl(memento, this.host) : memento; if (!ref) { throw new ArchiveRefusal("archive.today", "not-archived", `${String(memento)} is not an archive.today copy's URL`); } let at = this.canonical(ref.mementoUrl); const seen = new Set(); for (let hop = 0; hop <= ARCHIVE_TODAY_MAX_REDIRECTS; hop++) { seen.add(at); const res = await this.send(at, { accept: PAGE_ACCEPT, maxBytes, signal: o.signal }); if (res.status >= 300 && res.status < 400) { const next = res.location; let host = ""; try { host = next ? new URL(next).hostname : ""; } catch { host = ""; } if (!next || !isArchiveTodayHost(host)) { throw new ArchiveRefusal( "archive.today", "offsite-redirect", `archive.today answered ${at} with a redirect off archive.today (${next ?? "no URL"}); only its own are followed`, ); } at = this.canonical(next); if (seen.has(at)) throw new ArchiveRefusal("archive.today", "redirect-loop", `archive.today redirects ${ref.mementoUrl} in a loop (${at})`); continue; } const text = res.body?.toString("utf8") ?? ""; if (res.body && isArchiveTodayChallenge(text)) { const b = await this.viaBrowser(at, o.signal); if (!b || isArchiveTodayChallenge(b.html)) throw await this.challenged(at, b?.html ?? text, !!b); return this.answered(at, this.copyOf(Buffer.from(b.html, "utf8"), "text/html; charset=utf-8", b.url && isArchiveTodayHost(safeHost(b.url)) ? this.canonical(b.url) : at, null, ref, true)); } if (res.status === 404 || res.status === 410) { throw new ArchiveRefusal("archive.today", "not-archived", `archive.today holds no copy at ${at}`); } if (res.status < 200 || res.status >= 300) { throw new ArchiveTodayRequestError(`archive.today answered HTTP ${res.status} for ${at}`, res.status); } const contentType = res.headers.get("content-type") ?? "text/html"; if (!isPageMimetype(contentType) || bareMimetype(contentType) !== "text/html") { throw new ArchiveRefusal( "archive.today", "mimetype", `archive.today's answer for ${at} is ${bareMimetype(contentType) || "of no stated type"}, not a copied page (${PAGE_MIMETYPES[0]})`, ); } if (res.tooLarge || !res.body) { throw new ArchiveRefusal("archive.today", "too-large", `archive.today's copy at ${at} is over ${Math.round(maxBytes / 1024)} KB; not read`); } return this.answered(at, this.copyOf(res.body, contentType, at, res.headers, ref, false)); } throw new ArchiveRefusal("archive.today", "redirect-loop", `archive.today redirected ${ref.mementoUrl} more than ${ARCHIVE_TODAY_MAX_REDIRECTS} times`); }); } private copyOf( body: Buffer, contentType: string, finalUrl: string, headers: Headers | null, ref: ArchiveMementoRef, viaBrowser: boolean, ): ArchiveRawCapture { const html = body.toString("utf8"); const fromHeaders = headers ? copyFactsFromHeaders(headers) : {}; const fromHtml = copyFactsFromHtml(html); const finalRef = parseArchiveTodayUrl(finalUrl, this.host); const captureTs = fromHeaders.captureTs ?? fromHtml.captureTs ?? (finalRef?.captureTs?.length === 14 ? finalRef.captureTs : undefined) ?? (ref.captureTs?.length === 14 ? ref.captureTs : undefined); const originalUrl = fromHeaders.originalUrl ?? fromHtml.originalUrl ?? finalRef?.originalUrl ?? ref.originalUrl; if (!captureTs || !originalUrl) { throw new ArchiveRefusal( "archive.today", "unreadable", `archive.today's answer for ${finalUrl} names no ${!captureTs ? "capture time" : "page"} (no Memento headers, no header bar)`, ); } // A copy is named by its short id when the answer gives one. const mementoUrl = finalRef?.id ? finalRef.mementoUrl : (headers ? mementoOfLink(headers, this) : null) ?? finalUrl; const page = unwrapArchiveTodayHtml(html, mementoUrl).html; return { source: "archive.today", body, mimetype: bareMimetype(contentType) || "text/html", contentType, finalTs: captureTs, originalUrl, mementoUrl, bytes: body.byteLength, sha256: createHash("sha256").update(body).digest("hex"), unwrapped: true, page, ...(viaBrowser ? { viaBrowser: true } : {}), }; } } function safeHost(url: string): string { try { return new URL(url).hostname; } catch { return ""; } } // The Link header's rel="memento" self link (a copy answered at its timestamp // URL names its short-id URL there), on the canonical host. function mementoOfLink(headers: Headers, client: ArchiveTodayClient): string | null { const link = headers.get("link"); if (!link) return null; const m = /<([^>]+)>\s*;[^,]*\brel\s*=\s*"?[^",]*\bmemento\b/i.exec(link); if (!m) return null; const ref = parseArchiveTodayUrl(m[1], client.host); return ref?.id ? ref.mementoUrl : null; } async function readAnswer(res: Response, url: string, maxBytes: number): Promise { const base = { status: res.status, headers: res.headers, url }; if (res.status >= 300 && res.status < 400) { await res.body?.cancel().catch(() => {}); const loc = res.headers.get("location"); let location: string | null = null; if (loc) { try { location = new URL(loc, url).toString(); } catch { location = null; } } return { ...base, location, body: null, bytes: 0, tooLarge: false }; } const declared = Number(res.headers.get("content-length")); if (Number.isFinite(declared) && declared > maxBytes && res.status >= 200 && res.status < 300) { await res.body?.cancel().catch(() => {}); return { ...base, location: null, body: null, bytes: declared, tooLarge: true }; } const reader = res.body?.getReader(); const chunks: Buffer[] = []; let bytes = 0; if (reader) { for (;;) { const { done, value } = await reader.read(); if (done) break; bytes += value.byteLength; if (bytes > maxBytes) { await reader.cancel().catch(() => {}); if (res.status >= 200 && res.status < 300) return { ...base, location: null, body: null, bytes, tooLarge: true }; break; } chunks.push(Buffer.from(value)); } } return { ...base, location: null, body: Buffer.concat(chunks), bytes, tooLarge: false }; } // TEST-ONLY: E2E_ARCHIVE_TODAY_ORIGIN_FILE names a file holding ONE loopback // origin; while it exists, the process's archive.today client sends every // request for any archive.today host there — the fake archive.today a spec // starts (common/testing/web/fakeArchiveToday.mjs) — and opens no browser. // Anything but a loopback origin is ignored. const LOOPBACK_ORIGIN = /^http:\/\/(?:127\.0\.0\.1|localhost)(?::\d{1,5})?$/; export function archiveTodayTestOrigin(env: Readonly> = process.env): string | null { const file = env.E2E_ARCHIVE_TODAY_ORIGIN_FILE; if (!file) return null; let origin = ""; try { origin = readFileSync(file, "utf8").trim().replace(/\/$/, ""); } catch { return null; } return LOOPBACK_ORIGIN.test(origin) ? origin : null; } export function processArchiveTodayFetch(url: string, init: RequestInit): Promise { const origin = archiveTodayTestOrigin(); return fetch(origin ? url.replace(/^https?:\/\/(?:www\.)?archive\.(?:ph|today|is|li|vn|fo|md)/, origin) : url, init); }