// THE WAYBACK MACHINE'S CDX API (release 29 E2): which captures web.archive.org // holds of a URL — the deleted-video fallback asks it for a gone recording's // watch page (publish/findCopy.ts, `pnpm ops wayback-lookup`). // // web.archive.org is archive.org's, and is asked with archive.org's manners: // the same polite client (lib/archiveOrgClient.ts) — one request at a time, a // 2 s gap, the project's User-Agent, 429/503 waited out (Retry-After, else 5 s, // 10 s, … capped) a few times and then stopped — as its own instance, so a // Wayback lookup and an archive.org import each keep their own gap. // // A capture's replay URL is `https://web.archive.org/web//`: // the page as captured, which is also what yt-dlp's Wayback extractor reads // a YouTube watch page's video from. import { createHash } from "node:crypto"; import { readFileSync } from "node:fs"; import { ArchiveOrgClient, ArchiveOrgRequestError, type ArchiveOrgClientDeps, type ArchiveOrgClientOpts, } from "./archiveOrgClient"; import { isWaybackHost, parseWaybackUrl, waybackRawUrl } from "./wayback"; import { bareMimetype, isPageMimetype, PAGE_MIMETYPES } from "./waybackPages/urls"; export const WAYBACK_ORIGIN = "https://web.archive.org"; export type WaybackCapture = { // YYYYMMDDhhmmss timestamp: string; // The URL as captured. original: string; // The HTTP status the capture recorded ("200", "302", "-" for a revisit). status: string; mimetype?: string; // The capture's page on web.archive.org. replayUrl: string; }; export function waybackReplayUrl(timestamp: string, original: string): string { return `${WAYBACK_ORIGIN}/web/${timestamp}/${original}`; } export function waybackCdxUrl( url: string, o: { limit?: number; okOnly?: boolean; closest?: string; from?: string; to?: string } = {}, ): string { const q = new URLSearchParams(); q.set("url", url); q.set("output", "json"); if (o.okOnly) q.set("filter", "statuscode:200"); if (o.limit) q.set("limit", String(o.limit)); // Release 37 lane F: capture-time bounds (timestamp prefixes, inclusive). if (o.from) q.set("from", o.from); if (o.to) q.set("to", o.to); // Release 37: the captures nearest a time first (the page import's // `{url, at}` form). if (o.closest) { q.set("closest", o.closest); q.set("sort", "closest"); } return `${WAYBACK_ORIGIN}/cdx/search/cdx?${q.toString()}`; } // The CDX API's JSON answer: a header row naming the columns, then one row per // capture. `[]`, an empty body or a header alone: no captures. Anything else // that is not that shape is an error (the API changed, or answered a page). export function parseCdxJson(body: string): WaybackCapture[] { const text = body.trim(); if (!text) return []; let raw: unknown; try { raw = JSON.parse(text); } catch { throw new Error(`the CDX API did not answer JSON (${text.slice(0, 80)})`); } if (!Array.isArray(raw)) throw new Error("the CDX API's answer is not a list"); if (raw.length === 0) return []; const [header, ...rows] = raw as unknown[][]; if (!Array.isArray(header)) throw new Error("the CDX API's answer has no header row"); const col = (name: string) => header.indexOf(name); const ts = col("timestamp"); const orig = col("original"); const st = col("statuscode"); const mt = col("mimetype"); if (ts < 0 || orig < 0) throw new Error("the CDX API's header names no timestamp or original"); const out: WaybackCapture[] = []; for (const row of rows) { if (!Array.isArray(row)) continue; const timestamp = String(row[ts] ?? ""); const original = String(row[orig] ?? ""); if (!/^\d{14}$/.test(timestamp) || !original) continue; const mimetype = mt >= 0 && typeof row[mt] === "string" ? (row[mt] as string) : undefined; out.push({ timestamp, original, status: st >= 0 ? String(row[st] ?? "") : "", ...(mimetype ? { mimetype } : {}), replayUrl: waybackReplayUrl(timestamp, original), }); } return out; } // What yt-dlp's YoutubeWebArchive extractor asks before it fetches anything // (yt_dlp/extractor/archiveorg.py, `_real_extract`): the Wayback Machine's // own index of the YouTube VIDEOS it holds. No formats there: "The requested // video is not archived or indexed" — whatever captures of the watch page exist // (YouTube serves "Video unavailable" with a 200, and most page captures hold // no video). export function waybackVideoInfoUrl(youtubeId: string): string { return `${WAYBACK_ORIGIN}/__wb/videoinfo?${new URLSearchParams({ vtype: "youtube", vid: youtubeId }).toString()}`; } // The replay URL yt-dlp's extractor takes for a YouTube video (its _VALID_URL: // web.archive.org/web//https://www.youtube.com/watch?v=). export function waybackYoutubeUrl(youtubeId: string, timestamp?: string): string { return `${WAYBACK_ORIGIN}/web/${timestamp ?? ""}${timestamp ? "/" : ""}https://www.youtube.com/watch?v=${youtubeId}`; } // THE STREAM of an archived YouTube format, as yt-dlp's extractor fetches it // (archiveorg.py `_parse_fmt`): `https://web.archive.org/web/2id_/` // — the raw bytes Wayback holds for that googlevideo URL, if any. export function waybackStreamUrl(formatUrl: string): string { return `${WAYBACK_ORIGIN}/web/2id_/${formatUrl}`; } // The format URLs of the video index's answer, audio first (fetch-copies asks // yt-dlp for `ba/b`): a dmux answer's `formats.audio` then `formats.video`, // else `formats` in its order. Repeats once; anything not an http(s) URL is // skipped. export function videoInfoFormatUrls(raw: unknown): string[] { const formats = (raw as { formats?: unknown } | null)?.formats; const urlsOf = (list: unknown): string[] => Array.isArray(list) ? list.map((f) => (f as { url?: unknown } | null)?.url).filter((u): u is string => typeof u === "string" && /^https?:\/\//.test(u)) : []; const all = Array.isArray(formats) ? urlsOf(formats) : formats && typeof formats === "object" ? [...urlsOf((formats as Record).audio), ...urlsOf((formats as Record).video), ...Object.entries(formats as Record).filter(([k]) => k !== "audio" && k !== "video").flatMap(([, v]) => urlsOf(v))] : []; return [...new Set(all)]; } // At most this many of a video's formats are probed for a stream (one ranged // request each, paced): a video whose first three formats all 404 is taken as // its page alone. export const WAYBACK_STREAM_PROBES_MAX = 3; // What the "found" check saw (release 32 R8): the formats the video index // lists, the stream that answered (null: none did — the page was captured, // the video was not), and each probe's status. export type WaybackVideoStream = { formats: number; stream: string | null; probes: { url: string; status: number }[]; }; // A page capture's raw body is read up to this (release 37): a page larger // than this is a dump, not a page, and is refused unread past the cap. export const WAYBACK_PAGE_MAX_BYTES = 2 * 1024 * 1024; // How many redirects inside the archive a capture fetch follows. export const WAYBACK_MAX_REDIRECTS = 5; // The cap on one archived file a page record's capture downloads (release 37 S4). export const WAYBACK_FILE_MAX_BYTES = 10 * 1024 * 1024; const PAGE_ACCEPT = "text/html,application/xhtml+xml;q=0.9,text/plain;q=0.8,application/json;q=0.8,*/*;q=0.1"; // One capture's bytes (getCapture). export type WaybackRawCapture = { body: Buffer; // The bare mimetype ("text/html"), and the Content-Type as served (its // charset, when it names one). mimetype: string; contentType: string; // The capture the redirects (if any) ended at. finalTs: string; originalUrl: string; bytes: number; sha256: string; }; export type WaybackCaptureRefusalCode = | "mimetype" | "too-large" | "offsite-redirect" | "redirect-loop" | "not-archived" // Release 37 lane F: the archive answered 403 for the capture (see // WaybackExcludedError). | "excluded"; // A capture getCapture will not hand back, with the sentence a caller shows. export class WaybackCaptureRefusal extends Error { readonly code: WaybackCaptureRefusalCode; readonly mimetype?: string; constructor(code: WaybackCaptureRefusalCode, message: string, mimetype?: string) { super(message); this.name = "WaybackCaptureRefusal"; this.code = code; if (mimetype) this.mimetype = mimetype; } } // AN EXCLUDED URL (release 37 lane F): the Wayback Machine answers HTTP 403 — // at its CDX API, or for a capture — for a URL it will not show anyone (a site // owner's request, a legal one, a policy: it does not say which), while it // answers every other URL as usual. That is a fact about the URL, not an // outage, and every surface says it in these words. The error stays an // ArchiveOrgRequestError (status 403), so every catch written before it reads // it as it always did. export const WAYBACK_EXCLUDED_PHRASE = "excluded from the Wayback Machine (cause unknown)"; export class WaybackExcludedError extends ArchiveOrgRequestError { readonly excluded = true as const; readonly url: string; constructor(url: string) { super(`${url} is ${WAYBACK_EXCLUDED_PHRASE}: the Wayback Machine answered HTTP 403 for it`, 403, false); this.name = "WaybackExcludedError"; this.url = url; } } // Whether `e` is the Wayback Machine refusing a URL as excluded (a CDX 403, or // getCapture's "excluded"). export function isWaybackExcluded(e: unknown): boolean { return e instanceof WaybackExcludedError || (e instanceof WaybackCaptureRefusal && e.code === "excluded"); } // A CDX request's error as the exclusion it is (a 403), else as it was: what a // caller that builds its own CDX request (lane B's scan pages) wraps its // request in. export function waybackExcludedOf(e: unknown, url: string): unknown { return e instanceof ArchiveOrgRequestError && !(e instanceof WaybackExcludedError) && e.status === 403 ? new WaybackExcludedError(url) : e; } export class WaybackClient { private readonly http: ArchiveOrgClient; constructor(deps: ArchiveOrgClientDeps = {}, opts: ArchiveOrgClientOpts = {}) { this.http = new ArchiveOrgClient(deps, opts); } // Requests sent (each attempt), for tests and logs. get requests(): number { return this.http.requests; } // One request of any method to web.archive.org through this client's chain // and gap (release 37 S5: Save Page Now's POST and status polls, // lib/waybackPages/savePageNow.ts). ArchiveOrgClient.send's contract. send( url: string, init: Parameters[1], ): ReturnType { return this.http.send(url, init); } // Whether the Wayback Machine holds the YouTube VIDEO itself (formats in // its videoinfo index — what yt-dlp asks), not only captures of its page. async youtubeVideoArchived(youtubeId: string, o: { signal?: AbortSignal } = {}): Promise { return (await this.youtubeVideoFormats(youtubeId, o)).length > 0; } // The video index's format URLs for a YouTube id (videoInfoFormatUrls). async youtubeVideoFormats(youtubeId: string, o: { signal?: AbortSignal } = {}): Promise { const body = await this.http.getText(waybackVideoInfoUrl(youtubeId), "application/json", o.signal); let raw: unknown; try { raw = body.trim() ? JSON.parse(body) : {}; } catch { throw new ArchiveOrgRequestError(`the Wayback video index did not answer JSON for ${youtubeId}`, null, false); } return videoInfoFormatUrls(raw); } // THE "FOUND" CHECK (release 32 R8): the video index lists formats AND one // of their streams answers. The index can list a video whose bytes Wayback // does not hold (the live case: formats listed, 404 at the format URL), so // each of the first WAYBACK_STREAM_PROBES_MAX formats is probed with one // ranged GET through the paced client; the first that serves (200/206, not // an HTML page) is the stream. Throws ArchiveOrgRequestError when the index // or a probe kept refusing. async youtubeVideoStream(youtubeId: string, o: { signal?: AbortSignal } = {}): Promise { const formats = await this.youtubeVideoFormats(youtubeId, o); const out: WaybackVideoStream = { formats: formats.length, stream: null, probes: [] }; for (const f of formats.slice(0, WAYBACK_STREAM_PROBES_MAX)) { const url = waybackStreamUrl(f); const p = await this.http.probe(url, o.signal); out.probes.push({ url, status: p.status }); if (p.ok && !/^text\/html\b/i.test(p.contentType ?? "")) { out.stream = url; break; } } return out; } // THE CAPTURE NEAREST `at` (release 37: the page import's `{url, at}`): // one CDX request, `closest` + `sort=closest`, a few rows, the 200s only. // Null when the Wayback Machine holds no capture of `url` that recorded a // 200. async closestCapture(url: string, at: string, o: { signal?: AbortSignal } = {}): Promise { let body: string; try { body = await this.http.getText(waybackCdxUrl(url, { okOnly: true, limit: 5, closest: at }), "application/json", o.signal); } catch (e) { throw waybackExcludedOf(e, url); } let rows: WaybackCapture[]; try { rows = parseCdxJson(body); } catch (e) { throw new ArchiveOrgRequestError(`${(e as Error).message} for ${url}`, null, false); } if (rows.length === 0) return null; // `sort=closest` is the server's; ordering by distance here keeps the // answer right when a server (or a fake) ignores it. const want = Number(at.padEnd(14, "0")); return rows .map((r) => ({ r, d: Math.abs(Number(r.timestamp) - want) })) .sort((a, b) => a.d - b.d || a.r.timestamp.localeCompare(b.r.timestamp))[0].r; } // ONE CAPTURE'S RAW BODY (release 37, the page import): the `id_` form, // `/web/id_/` — the bytes as captured, no toolbar, no rewritten // links — through the client's own chain and gap. // - At most `maxBytes` (default WAYBACK_PAGE_MAX_BYTES, 2 MB); a longer // body is refused unread past the cap ("too-large"). // - text/html, text/plain or application/json only; anything else is // refused by its mimetype ("mimetype"). // - Redirects are followed by hand, inside the Wayback Machine only and at // most WAYBACK_MAX_REDIRECTS times: the archive answers a timestamp it // holds no capture at with the NEAREST capture's URL, and a capture that // recorded a redirect with the capture of its target. The answer is the // FINAL capture (`finalTs`, `originalUrl`). A redirect off the archive // is refused ("offsite-redirect"). // - A capture the archive does not hold is refused ("not-archived"). // Throws WaybackCaptureRefusal for those, ArchiveOrgRequestError when the // archive kept refusing (`rateLimited`) or answered another error. async getCapture( ts: string, url: string, o: { raw?: true; maxBytes?: number; signal?: AbortSignal } = {}, ): Promise { const maxBytes = o.maxBytes ?? WAYBACK_PAGE_MAX_BYTES; let at = waybackRawUrl({ captureTs: ts, originalUrl: url }); const seen = new Set(); for (let hop = 0; hop <= WAYBACK_MAX_REDIRECTS; hop++) { seen.add(at); let res; try { res = await this.http.getBounded(at, PAGE_ACCEPT, { maxBytes, signal: o.signal, manualRedirect: true }); } catch (e) { if (e instanceof ArchiveOrgRequestError && (e.status === 404 || e.status === 410)) { throw new WaybackCaptureRefusal("not-archived", `the Wayback Machine holds no capture of ${url} at ${ts}`); } if (e instanceof ArchiveOrgRequestError && e.status === 403) { throw new WaybackCaptureRefusal("excluded", `${url} is ${WAYBACK_EXCLUDED_PHRASE}: it answered HTTP 403 for the capture at ${ts}`); } throw e; } if (res.location !== null || (res.status >= 300 && res.status < 400)) { const next = res.location; if (!next) throw new WaybackCaptureRefusal("offsite-redirect", `the Wayback Machine answered ${at} with a redirect that names no URL`); let host = ""; try { host = new URL(next).hostname; } catch { host = ""; } const ref = isWaybackHost(host) ? parseWaybackUrl(next) : null; if (!ref) { throw new WaybackCaptureRefusal( "offsite-redirect", `the capture of ${url} redirects off the Wayback Machine (${next}); only redirects inside the archive are followed`, ); } // Stay on the raw form whatever modifier the redirect named. at = waybackRawUrl(ref); if (seen.has(at)) throw new WaybackCaptureRefusal("redirect-loop", `the capture of ${url} redirects in a loop (${at})`); continue; } const contentType = res.headers.get("content-type"); const mimetype = bareMimetype(contentType); if (!isPageMimetype(contentType)) { throw new WaybackCaptureRefusal( "mimetype", `the capture of ${url} is ${mimetype || "of no stated type"}, not a page (${PAGE_MIMETYPES.join(", ")})`, mimetype || undefined, ); } if (res.tooLarge || !res.body) { throw new WaybackCaptureRefusal( "too-large", `the capture of ${url} is over ${Math.round(maxBytes / 1024)} KB (${res.bytes} bytes and counting); not fetched`, ); } const final = parseWaybackUrl(at)!; return { body: res.body, mimetype, contentType: contentType ?? mimetype, finalTs: final.captureTs, originalUrl: final.originalUrl, bytes: res.body.byteLength, sha256: createHash("sha256").update(res.body).digest("hex"), }; } throw new WaybackCaptureRefusal("redirect-loop", `the capture of ${url} redirected more than ${WAYBACK_MAX_REDIRECTS} times`); } // Run a request something else makes (a headless browser's load of a // replay page, release 37 S4) in this client's chain and gap. paced(fn: () => Promise, o: { signal?: AbortSignal } = {}): Promise { return this.http.paced(fn, o.signal); } // A FILE a capture names (release 37 S4: a page record's image), by its own // Wayback URL (`im_`, lib/wayback.ts waybackFileUrl), through the same chain, // gap and back-off: its body read up to `maxBytes` (default 10 MB), redirects // followed by hand inside web.archive.org only (≤ WAYBACK_MAX_REDIRECTS, the // modifier kept). Answers null for a file the archive does not hold (404/410) // or one over the cap; throws WaybackCaptureRefusal for a redirect off the // archive or a loop, ArchiveOrgRequestError as getCapture does. async getArchivedFile( url: string, o: { maxBytes?: number; accept?: string; signal?: AbortSignal } = {}, ): Promise<{ body: Buffer; contentType: string | null; url: string } | null> { const maxBytes = o.maxBytes ?? WAYBACK_FILE_MAX_BYTES; let at = url; const seen = new Set(); for (let hop = 0; hop <= WAYBACK_MAX_REDIRECTS; hop++) { seen.add(at); let res; try { res = await this.http.getBounded(at, o.accept ?? "image/*,*/*;q=0.5", { maxBytes, signal: o.signal, manualRedirect: true }); } catch (e) { if (e instanceof ArchiveOrgRequestError && (e.status === 404 || e.status === 410)) return null; throw e; } if (res.location !== null || (res.status >= 300 && res.status < 400)) { const next = res.location; let host = ""; try { host = next ? new URL(next).hostname : ""; } catch { host = ""; } if (!next || !isWaybackHost(host)) { throw new WaybackCaptureRefusal("offsite-redirect", `the archived file ${url} redirects off the Wayback Machine (${next ?? "no URL"})`); } if (seen.has(next)) throw new WaybackCaptureRefusal("redirect-loop", `the archived file ${url} redirects in a loop (${next})`); at = next; continue; } if (res.tooLarge || !res.body) return null; return { body: res.body, contentType: res.headers.get("content-type"), url: at }; } throw new WaybackCaptureRefusal("redirect-loop", `the archived file ${url} redirected more than ${WAYBACK_MAX_REDIRECTS} times`); } // The captures of `url`, oldest first: every capture, or (`okOnly`) only the // ones that recorded a 200. Throws ArchiveOrgRequestError when the API kept // refusing (`rateLimited`) or answered an error. async captures( url: string, o: { limit?: number; okOnly?: boolean; from?: string; to?: string; signal?: AbortSignal } = {}, ): Promise { let body: string; try { body = await this.http.getText(waybackCdxUrl(url, o), "application/json", o.signal); } catch (e) { throw waybackExcludedOf(e, url); } try { return parseCdxJson(body); } catch (e) { throw new ArchiveOrgRequestError(`${(e as Error).message} for ${url}`, null, false); } } // ONE PAGE OF A CDX LISTING the caller built (release 37 S2, the Wayback // pages scan — lib/waybackPages/scanCdx.ts builds the URL and parses the // answer): the body as text, through the same chain, gap and back-off. // Throws ArchiveOrgRequestError when the API kept refusing or answered an // error. async cdxPage(cdxUrl: string, o: { signal?: AbortSignal } = {}): Promise { try { return await this.http.getText(cdxUrl, "application/json", o.signal); } catch (e) { // Release 37 lane F: a 403 for the scanned URL is its exclusion. let url = cdxUrl; try { url = new URL(cdxUrl).searchParams.get("url") ?? cdxUrl; } catch { // keep the request URL } throw waybackExcludedOf(e, url); } } } // TEST-ONLY: E2E_WAYBACK_ORIGIN_FILE names a file holding ONE loopback origin // (`http://127.0.0.1:`). While that file exists, the process's Wayback // client sends every https://web.archive.org request there — the editor e2e // suite's fake Wayback (common/testing/web/fakeWayback.mjs), which a spec // starts and names in the file (read per request, so a spec can start its fake // after the server booted). Anything but a loopback origin is ignored. Unset // everywhere but the editor's e2e server; unit tests pass `fetch` directly. const LOOPBACK_ORIGIN = /^http:\/\/(?:127\.0\.0\.1|localhost)(?::\d{1,5})?$/; export function waybackTestOrigin(env: Readonly> = process.env): string | null { const file = env.E2E_WAYBACK_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; } function processWaybackFetch(url: string, init: RequestInit): Promise { const origin = waybackTestOrigin(); return fetch(origin ? url.replace(/^https?:\/\/(?:web|wayback)\.archive\.org/, origin) : url, init); } // THE process's Wayback client: one chain, one gap. export const waybackClient = new WaybackClient({ fetch: processWaybackFetch });