// SAVE PAGE NOW (release 37 S5) — asking the Wayback Machine to capture a // live page now, through its SPN2 API (archive.org's documented // "Save Page Now 2 Public API"): // // POST https://web.archive.org/save // Authorization: LOW : (archive.org's S3 keys) // Accept: application/json // url=&capture_outlinks=0 (the page alone) // → {url, job_id} or {status: "error", status_ext, message} // GET https://web.archive.org/save/status/ // → {status: "pending"} ask again later // → {status: "success", timestamp, original_url} // → {status: "error", status_ext, message} // // Pure: what the answers mean. The keys, the requests and the job are // ./savePageNow-server.ts and controller/savePageNow.ts. // The archive's origin, spelled here (lib/waybackClient.ts's WAYBACK_ORIGIN // carries node:fs with it); the process client sends it to a test's fake. const ORIGIN = "https://web.archive.org"; export const SPN_SAVE_URL = `${ORIGIN}/save`; export function spnStatusUrl(jobId: string): string { return `${ORIGIN}/save/status/${encodeURIComponent(jobId)}`; } // The form a capture request sends: the page alone, no outlinks. export function spnSaveBody(url: string): string { return new URLSearchParams({ url, capture_outlinks: "0" }).toString(); } export type SpnKeys = { access: string; secret: string }; // The Authorization header's value. Never logged. export function spnAuthorization(keys: SpnKeys): string { return `LOW ${keys.access}:${keys.secret}`; } export type SpnSubmit = { ok: true; jobId: string } | { ok: false; error: string; code?: string }; const json = (text: string): Record | null => { try { const v = JSON.parse(text) as unknown; return v && typeof v === "object" && !Array.isArray(v) ? (v as Record) : null; } catch { return null; } }; const str = (v: unknown): string => (typeof v === "string" ? v.trim() : ""); // What archive.org answered a capture request. A 401/403 is the keys; an // error body names its `status_ext` (error:too-many-daily-captures, …). export function parseSpnSubmit(status: number, text: string): SpnSubmit { const body = json(text); if (status === 401 || status === 403) { return { ok: false, code: "auth", error: `archive.org refused the S3 keys (HTTP ${status}); check them at archive.org/account/s3.php` }; } const jobId = str(body?.job_id); if (status >= 200 && status < 300 && jobId) return { ok: true, jobId }; const ext = str(body?.status_ext); const message = str(body?.message); return { ok: false, ...(ext ? { code: ext } : {}), error: `Save Page Now refused the capture (HTTP ${status}${ext ? `, ${ext}` : ""})${message ? `: ${message}` : ""}`, }; } export type SpnStatus = | { state: "pending" } | { state: "success"; timestamp: string; originalUrl: string } | { state: "error"; error: string; code?: string }; // What a status poll answered. export function parseSpnStatus(status: number, text: string): SpnStatus { const body = json(text); if (status === 401 || status === 403) { return { state: "error", code: "auth", error: `archive.org refused the S3 keys (HTTP ${status})` }; } const state = str(body?.status); if (status >= 200 && status < 300 && state === "pending") return { state: "pending" }; if (status >= 200 && status < 300 && state === "success") { const timestamp = str(body?.timestamp); const originalUrl = str(body?.original_url); if (/^\d{14}$/.test(timestamp) && /^https?:\/\//i.test(originalUrl)) return { state: "success", timestamp, originalUrl }; return { state: "error", error: "Save Page Now said success but named no capture (timestamp, original_url)" }; } const ext = str(body?.status_ext); const message = str(body?.message); return { state: "error", ...(ext ? { code: ext } : {}), error: `the capture failed (HTTP ${status}${ext ? `, ${ext}` : ""})${message ? `: ${message}` : ""}`, }; } // Why Save Page Now is off, in the sentence the button shows, when no keys // are configured. export function spnOffSentence(keyFile: string): string { return ( `Save Page Now needs archive.org S3 keys: ARCHIVE_ORG_S3_ACCESS and ARCHIVE_ORG_S3_SECRET in the editor's ` + `environment, or in ${keyFile} (mode 600; settings archiveOrg.s3KeyFile).` ); } // ─── ANONYMOUS SAVE PAGE NOW (lane spn-batch, 5 Nov) ──────────────────────── // // With no S3 keys the public endpoint is used, the way archive.org's own // "Save Page Now" form and the `savepagenow` library use it: ONE GET of // // GET https://web.archive.org/save/ (no Authorization) // → the capture named by Content-Location (/web//), a Link // rel="memento", or the URL the redirects ended at; or a page that // watches an SPN job (spn.watchJob("spn2-…")) whose status is then // polled at /save/status/; X-Archive-Wayback-Runtime-Error // names a refusal (Blocked By Robots, …). // // archive.org's limits for anonymous captures (the SPN2 doc's Limitations): // at most 3 captures a minute and 200 a day (authenticated: 7 and 30k), 5 of // one URL a day. The pacing that keeps well inside them is // controller/savePageNow.ts's (SpnPacer). export type SpnMode = "anonymous" | "keys"; // The sentence an SPN HTML page says (its error), scripts and styles left out. export function spnPageMessage(html: string): string { const text = html .replace(//gi, " ") .replace(//gi, " ") .replace(/<[^>]*>/g, " ") .replace(/ /g, " ") .replace(/&/g, "&") .replace(/'|'/g, "'") .replace(/"/g, '"') .replace(/\s+/g, " ") .trim(); // The page's chrome first (the title, "Save Page Now", menus): the message is // the first sentence that reads like one about the capture. const m = /((?:Sorry|Job failed|This (?:URL|host|page)|The (?:server|page|capture|URL)|Cannot|Can't|We couldn't|Live page|Error)[^.!?]{0,200}[.!?]?)/i.exec(text); return (m?.[1] ?? text.slice(0, 160)).trim().slice(0, 240); } // Browser-shaped (archive.org's SPN serves its capture flow to browsers) but // honest: it names the project and where it lives, and claims no browser. export function spnUserAgent(projectName: string, projectUrl: string): string { return `Mozilla/5.0 (compatible; ${projectName} Save Page Now; +${projectUrl})`; } export function spnAnonymousSaveUrl(url: string): string { return `${ORIGIN}/save/${url}`; } export type SpnAnonymousAnswer = | { state: "success"; timestamp: string; originalUrl: string } | { state: "pending"; jobId: string } // 429, or SPN's own "too many" refusals: the caller rests. | { state: "rate-limited"; error: string; code?: string; retryAfterMs?: number; daily?: boolean } // 502/503/504/520/523: archive.org is struggling; the caller rests. | { state: "unavailable"; error: string } | { state: "error"; error: string; code?: string }; const CAPTURE_PATH = /\/web\/(\d{14})[a-z_]*\/(https?:\/\/.+)$/i; // A capture named by a URL or path (`/web//`, absolute or not). export function spnCaptureOf(ref: string | null | undefined): { timestamp: string; originalUrl: string } | null { if (!ref) return null; let p = ref.trim(); try { if (/^https?:\/\//i.test(p)) { const u = new URL(p); if (!/(^|\.)archive\.org$/i.test(u.hostname)) return null; p = u.pathname + u.search; } } catch { return null; } const m = CAPTURE_PATH.exec(p); return m ? { timestamp: m[1], originalUrl: m[2] } : null; } // The memento a Link header names (rel="memento", else rel="last memento"). export function spnLinkMemento(link: string | null | undefined): string | null { if (!link) return null; let best: string | null = null; for (const part of link.split(/,(?=\s*<)/)) { const m = /<([^>]+)>\s*;(.*)$/.exec(part.trim()); if (!m) continue; const rel = /rel="?([^";]+)"?/i.exec(m[2])?.[1]?.toLowerCase() ?? ""; if (rel === "memento") return m[1]; if (rel.includes("memento") && !best) best = m[1]; } return best; } const DAILY = /daily|per day|today/i; // A status_ext that means "rest", not "this URL failed". function restingCode(code: string, message: string): { daily: boolean } | null { if (code === "error:too-many-daily-captures") return null; // this URL, 5-10 a day: the URL's own failure if (code === "error:user-session-limit" || code === "error:too-many-requests") return { daily: false }; if (/^error:(max-daily-bandwidth|max-daily-bandwidth-from-ip|daily-limit|user-daily-limit)/.test(code)) return { daily: true }; if (code.startsWith("error:") && /limit|too many/i.test(code + " " + message)) return { daily: DAILY.test(code + " " + message) }; return null; } // What the anonymous endpoint answered. `get(name)` reads a response header. export function parseSpnAnonymous(a: { status: number; header: (name: string) => string | null; finalUrl?: string; text: string; retryAfterMs?: number | null; }): SpnAnonymousAnswer { const runtime = a.header("x-archive-wayback-runtime-error"); if (runtime) { const robots = /robots/i.test(runtime); return { state: "error", code: robots ? "blocked-by-robots" : "runtime-error", error: `Save Page Now refused the capture: ${runtime.trim()}` }; } if (a.status === 429) { return { state: "rate-limited", error: "archive.org answered HTTP 429 (too many captures)", ...(a.retryAfterMs != null ? { retryAfterMs: a.retryAfterMs } : {}), }; } if ([502, 503, 504].includes(a.status)) return { state: "unavailable", error: `archive.org answered HTTP ${a.status}` }; // 520/523 from the save itself (x-location: save-sync): SPN tried THIS URL // and could not capture it — the page says why. A failure of the URL, not a // reason to rest (the live answer for an X post, 5 Nov: 523 in ~2 s, x-rl 0). if (a.status === 520 || a.status === 523) { const said = spnPageMessage(a.text); // "We're currently facing some limitations when it comes to archiving this // site": the SITE is refused (x.com, 5 Nov), not this page — the caller // stops asking for that host. const host = /archiving this site|this site|this host|this domain/i.test(said) ? "host-limited" : `http-${a.status}`; return { state: "error", code: host, error: `Save Page Now could not capture the page (HTTP ${a.status})${said ? `: ${said}` : ""}` }; } const body = json(a.text); const ext = str(body?.status_ext); const message = str(body?.message); if (ext) { const rest = restingCode(ext, message); if (rest) return { state: "rate-limited", code: ext, daily: rest.daily, error: `Save Page Now asked us to slow down (${ext})${message ? `: ${message}` : ""}` }; } if (a.status === 401 || a.status === 403) { return { state: "error", code: "refused", error: `archive.org refused an anonymous capture (HTTP ${a.status})${message ? `: ${message}` : ""}` }; } const cap = spnCaptureOf(a.header("content-location")) ?? spnCaptureOf(spnLinkMemento(a.header("link"))) ?? spnCaptureOf(a.finalUrl); if (a.status >= 200 && a.status < 400 && cap) return { state: "success", ...cap }; const jobId = str(body?.job_id) || (/watchJob\(\s*["']([^"']+)["']/.exec(a.text)?.[1] ?? ""); if (a.status >= 200 && a.status < 300 && jobId) return { state: "pending", jobId }; if (body && str(body.status) === "error") { return { state: "error", ...(ext ? { code: ext } : {}), error: `Save Page Now refused the capture (HTTP ${a.status}${ext ? `, ${ext}` : ""})${message ? `: ${message}` : ""}` }; } // The HTML page's own error sentence, when it has one. const said = /]*>([^<]{3,200})<\/h2>/i.exec(a.text)?.[1]?.trim(); return { state: "error", error: `Save Page Now named no capture (HTTP ${a.status})${said ? `: ${said}` : ""}`, }; } // A status poll's answer read for resting too: SPN's "slow down" codes are // not this URL's failure. export function spnStatusRests(s: SpnStatus): { daily: boolean } | null { return s.state === "error" && s.code ? restingCode(s.code, s.error) : null; }