// SAVE PAGE NOW (release 37 S5, `save-page-now`): "Ask the Wayback Machine to // capture this now" — for a live page likely to be taken down. One page per // job: archive.org's SPN2 API (lib/waybackPages/savePageNow.ts) with the // operator's S3 keys, the capture waited for, then (when a Wayback pages // channel is named) an `import-page` job of the new capture into it // (controller/importPage.ts startImportPageJob), queued behind this one. // // {url, slug?} slug: the Wayback pages channel the capture is imported // into (absent: the capture is made and named, not // imported) // // WITHOUT KEYS (lane spn-batch, 5 Nov) the capture is asked ANONYMOUSLY, at // archive.org's public endpoint (lib/waybackPages/savePageNow.ts // parseSpnAnonymous), under its stricter limits: every result and log names // its `mode` ("anonymous" | "keys"). A key FILE that is there but unsafe // (others can read it, no key lines) is still refused: the operator meant keys. // // ONE SAVE AT A TIME, process-wide (SpnPacer below): a single job and a batch // (controller/savePageNowBatch.ts) take turns through the same pacer — at // least SPN_ANON_GAP_MS (60 s) between anonymous saves, SPN_KEYS_GAP_MS (10 s) // with keys, both stretched by pacing.jitter; a 429/503 or SPN's own "slow // down" codes rest it (Retry-After when sent, else 2 min doubling to 1 h). // // Refused before any request, with the sentence a caller shows: a URL that is not http(s), a page on the // Wayback Machine itself, a channel that is not a Wayback pages channel, a // video ("use import-video"), an X page outside an X-scoped channel while X // posts are private (importPage's own rule). // // POLITE: every request goes through the process's Wayback client (one // stream, the 2 s gap, 429/503 waited out, then stopped), on the // `platform:archive.org` queue — one capture asked at a time; the status is // polled every SPN_POLL_MS, at most SPN_MAX_POLLS times. The keys are sent in // the Authorization header only, and never logged. import { getPaths, type Paths } from "../lib/paths"; import { getSettings } from "../lib/settings"; import { readChannelConfig } from "./channels"; import { isWaybackPagesChannel } from "../lib/waybackPages/config"; import { isWaybackHost, waybackPageUrl } from "../lib/wayback"; import { videoPageOf } from "../lib/waybackPages/urls"; import { ArchiveOrgRequestError } from "../lib/archiveOrgClient"; import { waybackClient as defaultWaybackClient, type WaybackClient } from "../lib/waybackClient"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { parseSpnStatus, parseSpnSubmit, SPN_SAVE_URL, spnAuthorization, spnSaveBody, spnStatusUrl, type SpnKeys, } from "../lib/waybackPages/savePageNow"; import { readSpnKeys, redactSpnKeys } from "../lib/waybackPages/savePageNow-server"; import { startImportPageJob, WAYBACK_PAGES_QUEUE, xCaptureRefusal } from "./importPage"; import { jitterMs } from "../lib/jitter"; import { parseSpnAnonymous, spnAnonymousSaveUrl, spnStatusRests, spnUserAgent, type SpnMode, } from "../lib/waybackPages/savePageNow"; import { parseRetryAfterMs } from "../lib/archiveOrgClient"; import { PROJECT_NAME, PROJECT_URL } from "../lib/project"; import { existsSync } from "node:fs"; import os from "node:os"; import { DEFAULT_ARCHIVE_ORG_S3_KEY_FILE } from "../lib/archiveOrgTorrent"; export type { SpnMode }; export const SPN_USER_AGENT = spnUserAgent(PROJECT_NAME, PROJECT_URL); // The gap between two saves, from this process (a floor; jitter only adds). export const SPN_ANON_GAP_MS = 60_000; export const SPN_KEYS_GAP_MS = 10_000; // The rest after a 429/503/"slow down": Retry-After when longer, else this, // doubling per rest in a row, at most SPN_MAX_REST_MS. export const SPN_BASE_REST_MS = 2 * 60_000; export const SPN_MAX_REST_MS = 60 * 60_000; // How long one anonymous capture GET may take (SPN's own cap is 2 minutes). export const SPN_ANON_TIMEOUT_MS = 150_000; type PacerDeps = { now: () => number; sleep: (ms: number, signal?: AbortSignal) => Promise }; // THE PACER: one save at a time, the gap between saves, and the rest after a // refusal — shared by every Save Page Now in the process. export class SpnPacer { private chain: Promise = Promise.resolve(); private lastSaveAt = -Infinity; private restUntil = 0; private restsInARow = 0; constructor( private readonly deps: PacerDeps, private readonly gaps: { anonymous: number; keys: number } = { anonymous: SPN_ANON_GAP_MS, keys: SPN_KEYS_GAP_MS }, ) {} gapMs(mode: SpnMode): number { return this.gaps[mode]; } // When the next save may start (epoch ms). nextAt(mode: SpnMode): number { return Math.max(this.lastSaveAt + this.gaps[mode], this.restUntil); } resting(): { until: number; inARow: number } | null { return this.restUntil > this.deps.now() ? { until: this.restUntil, inARow: this.restsInARow } : null; } // Run one save: after every earlier one, its gap and any rest. turn(mode: SpnMode, fn: () => Promise, o: { signal?: AbortSignal; onWait?: (ms: number, why: string) => void } = {}): Promise { const run = this.chain.then(async () => { const resting = this.restUntil > this.deps.now(); const wait = Math.max(this.lastSaveAt + jitterMs(this.gaps[mode]), this.restUntil) - this.deps.now(); if (wait > 0) { o.onWait?.(wait, resting ? "resting after archive.org asked us to slow down" : "the gap between saves"); await this.deps.sleep(wait, o.signal); } try { return await fn(); } finally { this.lastSaveAt = this.deps.now(); } }); this.chain = run.catch(() => {}); return run; } // archive.org asked us to slow down: rest (and say how long). rest(retryAfterMs?: number | null): number { this.restsInARow++; const doubling = Math.min(SPN_MAX_REST_MS, SPN_BASE_REST_MS * 2 ** (this.restsInARow - 1)); const ms = Math.max(doubling, Math.min(retryAfterMs ?? 0, 24 * 60 * 60_000)); this.restUntil = Math.max(this.restUntil, this.deps.now() + ms); return ms; } // A save went through: the rests in a row start over. saved(): void { this.restsInARow = 0; } } export const spnPacer = new SpnPacer({ now: () => Date.now(), sleep: (ms, signal) => defaultSleep(ms, signal) }); const expandHome = (p: string) => (p === "~" || p.startsWith("~/") ? os.homedir() + p.slice(1) : p); // The keys, or anonymous when NONE are configured (no env pair, no key file); // a key file that exists but cannot be used is refused with its sentence. export function spnKeysOrAnonymous(o: { keyFile?: string; env?: Readonly> }): | { ok: true; mode: "keys"; keys: SpnKeys } | { ok: true; mode: "anonymous" } | { ok: false; reason: string } { const read = readSpnKeys({ ...(o.keyFile ? { keyFile: o.keyFile } : {}), ...(o.env ? { env: o.env } : {}) }); if (read.ok) return { ok: true, mode: "keys", keys: read.keys }; const file = expandHome(o.keyFile?.trim() || DEFAULT_ARCHIVE_ORG_S3_KEY_FILE); if (existsSync(file)) return { ok: false, reason: read.reason }; return { ok: true, mode: "anonymous" }; } export const SPN_ANONYMOUS_NOTE = "No archive.org S3 keys: Save Page Now asks anonymously (archive.org allows 3 captures a minute and 200 a day), one at a time, at least 60 s apart."; export const SAVE_PAGE_NOW_JOB_KIND = "save-page-now"; export const SAVE_PAGE_NOW_RESULT_MARKER = "@@save-page-now "; // SPN2 asks status pollers to wait a few seconds between polls; a capture // usually completes within a minute or two. export const SPN_POLL_MS = 10_000; export const SPN_MAX_POLLS = 30; type SpnSettings = { archiveOrg?: { s3KeyFile?: string }; social?: { x?: { visibility?: unknown } } }; export type SavePageNowAvailability = { on: true; mode: "keys" } | { on: true; mode: "anonymous"; note: string } | { on: false; reason: string }; // Whether the button is on, and why not: the keys' presence (never their // value). export function savePageNowAvailability(o: { settings?: SpnSettings; env?: Readonly> } = {}): SavePageNowAvailability { const settings = o.settings ?? (getSettings() as SpnSettings); const read = spnKeysOrAnonymous({ keyFile: settings.archiveOrg?.s3KeyFile, ...(o.env ? { env: o.env } : {}) }); if (!read.ok) return { on: false, reason: read.reason }; return read.mode === "keys" ? { on: true, mode: "keys" } : { on: true, mode: "anonymous", note: SPN_ANONYMOUS_NOTE }; } export type SavePageNowPlan = { url: string; slug?: string; mode: SpnMode; keys?: SpnKeys }; // Everything checked before a request: the plan, or the refusal. export async function planSavePageNow( paths: Paths, opts: { url: string; slug?: string; settings?: SpnSettings; env?: Readonly> }, ): Promise<{ ok: true; plan: SavePageNowPlan } | { ok: false; error: string }> { const settings = opts.settings ?? (getSettings() as SpnSettings); const url = opts.url.trim(); let u: URL; try { u = new URL(url); } catch { return { ok: false, error: `"${url}" is not a URL` }; } if (u.protocol !== "http:" && u.protocol !== "https:") return { ok: false, error: `only http and https pages are captured (not ${u.protocol})` }; if (isWaybackHost(u.hostname)) return { ok: false, error: `${url} is on the Wayback Machine already: import it (import-page) instead` }; const slug = opts.slug?.trim() || undefined; if (slug) { const config = await readChannelConfig(paths, slug); if (!config) return { ok: false, error: `No such channel: ${slug}` }; if (!isWaybackPagesChannel(config)) { return { ok: false, error: `${slug} is not a Wayback pages channel; a capture is imported into a channel on platform "webpage"` }; } const video = videoPageOf(url); if (video) return { ok: false, error: `${url} is a video (${video}), not a page: use import-video for a video` }; const x = xCaptureRefusal(config, slug, url, settings); if (x) return { ok: false, error: x }; } const read = spnKeysOrAnonymous({ keyFile: settings.archiveOrg?.s3KeyFile, ...(opts.env ? { env: opts.env } : {}) }); if (!read.ok) return { ok: false, error: read.reason }; return { ok: true, plan: { url, ...(slug ? { slug } : {}), mode: read.mode, ...(read.mode === "keys" ? { keys: read.keys } : {}) } }; } export type SavePageNowResult = { ok: boolean; url: string; slug?: string; // "anonymous" (no keys: the public endpoint) or "keys" (SPN2 with S3 keys). mode?: SpnMode; // archive.org asked us to slow down (a 429/503, SPN's "too many"): the // capture was not made, the pacer rests `restMs`; `daily` when it was the // day's cap. rateLimited?: boolean; restMs?: number; daily?: boolean; dryRun?: boolean; // What a dry run would ask. wouldAsk?: string; // SPN's job id. spnJobId?: string; captureTs?: string; originalUrl?: string; waybackUrl?: string; // The import-page job of the capture. importJobId?: string; importError?: string; polls?: number; // SPN's status_ext for a refusal (error:blocked-url, …), when it named one. code?: string; error?: string; }; export type SavePageNowDeps = { client: Pick; pacer: SpnPacer; sleep: (ms: number, signal?: AbortSignal) => Promise; // The capture into the channel (default: an import-page job). importCapture: (slug: string, waybackUrl: string) => Promise<{ jobId: string }>; }; const defaultSleep = (ms: number, signal?: AbortSignal) => new Promise((resolve, reject) => { if (signal?.aborted) return reject(signal.reason ?? new Error("aborted")); const t = setTimeout(resolve, ms); signal?.addEventListener( "abort", () => { clearTimeout(t); reject(signal.reason ?? new Error("aborted")); }, { once: true }, ); }); // ONE CAPTURE ASKED, waited for, and (with a slug) imported. export async function savePageNow(opts: { paths: Paths; url: string; slug?: string; dryRun?: boolean; settings?: SpnSettings; env?: Readonly>; pollMs?: number; maxPolls?: number; deps?: Partial; onLog?: (line: string) => void; signal?: AbortSignal; }): Promise { const base: SavePageNowResult = { ok: false, url: opts.url.trim(), ...(opts.slug?.trim() ? { slug: opts.slug.trim() } : {}) }; const planned = await planSavePageNow(opts.paths, opts); if (!planned.ok) return { ...base, error: planned.error }; const { plan } = planned; base.mode = plan.mode; if (opts.dryRun) { return { ...base, ok: true, dryRun: true, wouldAsk: plan.mode === "keys" ? `POST ${SPN_SAVE_URL} (url=${plan.url}, capture_outlinks=0), then poll its status${plan.slug ? `, then import the capture into ${plan.slug}` : ""}` : `GET ${spnAnonymousSaveUrl(plan.url)} (anonymous: no keys), then poll its status if it names a job${plan.slug ? `, then import the capture into ${plan.slug}` : ""}`, }; } const deps: SavePageNowDeps = { // A caller that brings its own sleep (a test) gets its own pacer on it. pacer: opts.deps?.pacer ?? (opts.deps?.sleep ? new SpnPacer({ now: () => Date.now(), sleep: opts.deps.sleep }) : spnPacer), client: opts.deps?.client ?? defaultWaybackClient, sleep: opts.deps?.sleep ?? defaultSleep, importCapture: opts.deps?.importCapture ?? ((slug, waybackUrl) => startImportPageJob({ slug, url: waybackUrl, requestedBy: "save-page-now", paths: opts.paths })), }; const log = (line: string) => opts.onLog?.(redactSpnKeys(line, plan.keys)); const pollMs = opts.pollMs ?? SPN_POLL_MS; const maxPolls = opts.maxPolls ?? SPN_MAX_POLLS; const fmtWait = (ms: number) => (ms >= 120_000 ? `${Math.round(ms / 60_000)} min` : `${Math.round(ms / 1000)} s`); return deps.pacer.turn( plan.mode, () => (plan.mode === "keys" ? keyedCapture() : anonymousCapture()), { ...(opts.signal ? { signal: opts.signal } : {}), onWait: (ms, why) => log(`Waiting ${fmtWait(ms)} (${why}).`) }, ).catch((e: unknown) => { if (opts.signal?.aborted) return { ...base, error: "cancelled" }; throw e; }); // The capture made: imported when a channel was named. async function captured(spnJobId: string | undefined, polls: number, timestamp: string, originalUrl: string): Promise { deps.pacer.saved(); const waybackUrl = waybackPageUrl({ captureTs: timestamp, originalUrl }); log(`Captured: ${waybackUrl}`); const out: SavePageNowResult = { ...base, ok: true, ...(spnJobId ? { spnJobId } : {}), polls, captureTs: timestamp, originalUrl, waybackUrl, }; if (plan.slug) { try { const imp = await deps.importCapture(plan.slug, waybackUrl); out.importJobId = imp.jobId; log(`Import into ${plan.slug}: job ${imp.jobId}.`); } catch (e) { out.importError = (e as Error).message; log(`The import into ${plan.slug} was refused: ${out.importError}`); } } return out; } function rested(error: string, retryAfterMs?: number | null, daily?: boolean, spnJobId?: string): SavePageNowResult { const restMs = deps.pacer.rest(daily ? Math.max(retryAfterMs ?? 0, 6 * 60 * 60_000) : retryAfterMs); log(`${error}; Save Page Now rests ${fmtWait(restMs)}.`); return { ...base, ...(spnJobId ? { spnJobId } : {}), rateLimited: true, restMs, ...(daily ? { daily: true } : {}), error: `${error}; resting ${fmtWait(restMs)}` }; } // Poll an SPN job's status until it is made (both modes). async function poll(jobId: string, headers: Record): Promise { let polls = 0; for (;;) { if (polls >= maxPolls) { return { ...base, spnJobId: jobId, polls, error: `the capture was still pending after ${polls} status checks; archive.org may finish it later (look the page up with archive-lookup, then import-page it)`, }; } await deps.sleep(jitterMs(pollMs), opts.signal); polls++; const st = await deps.client.send(spnStatusUrl(jobId), { method: "GET", headers, ...(opts.signal ? { signal: opts.signal } : {}) }); const status = parseSpnStatus(st.status, st.text); if (status.state === "pending") continue; if (status.state === "error") { const rest = spnStatusRests(status); if (rest) return rested(redactSpnKeys(status.error, plan.keys), null, rest.daily, jobId); return { ...base, spnJobId: jobId, polls, ...(status.code ? { code: status.code } : {}), error: redactSpnKeys(status.error, plan.keys) }; } return captured(jobId, polls, status.timestamp, status.originalUrl); } } async function anonymousCapture(): Promise { try { log(`Asking the Wayback Machine to capture ${plan.url} now (Save Page Now, anonymous: no keys).`); const headers = { "user-agent": SPN_USER_AGENT }; const sent = await deps.client.send(spnAnonymousSaveUrl(plan.url), { method: "GET", accept: "text/html,application/xhtml+xml;q=0.9,application/json;q=0.8,*/*;q=0.5", headers, noRetry: true, timeoutMs: SPN_ANON_TIMEOUT_MS, ...(opts.signal ? { signal: opts.signal } : {}), }); const h = sent.headers ?? new Headers(); const answer = parseSpnAnonymous({ status: sent.status, header: (n) => h.get(n), finalUrl: sent.url, text: sent.text, retryAfterMs: parseRetryAfterMs(h.get("retry-after"), Date.now()), }); if (answer.state === "success") return captured(undefined, 0, answer.timestamp, answer.originalUrl); if (answer.state === "rate-limited") return rested(answer.error, answer.retryAfterMs, answer.daily); if (answer.state === "unavailable") return rested(answer.error, null); if (answer.state === "error") return { ...base, ...(answer.code ? { code: answer.code } : {}), error: answer.error }; log(`Save Page Now job ${answer.jobId}: waiting for the capture.`); return await poll(answer.jobId, headers); } catch (e) { if (opts.signal?.aborted) return { ...base, error: "cancelled" }; if (e instanceof ArchiveOrgRequestError) { if (e.rateLimited) return rested(e.message, null); return { ...base, error: e.message }; } throw e; } } async function keyedCapture(): Promise { const headers = { authorization: spnAuthorization(plan.keys!) }; try { log(`Asking the Wayback Machine to capture ${plan.url} now (Save Page Now).`); const sent = await deps.client.send(SPN_SAVE_URL, { method: "POST", headers: { ...headers, "content-type": "application/x-www-form-urlencoded" }, body: spnSaveBody(plan.url), ...(opts.signal ? { signal: opts.signal } : {}), }); const submit = parseSpnSubmit(sent.status, sent.text); if (!submit.ok) { if (submit.code && spnStatusRests({ state: "error", code: submit.code, error: submit.error })) { const rest = spnStatusRests({ state: "error", code: submit.code, error: submit.error })!; return rested(redactSpnKeys(submit.error, plan.keys), null, rest.daily); } return { ...base, ...(submit.code ? { code: submit.code } : {}), error: redactSpnKeys(submit.error, plan.keys) }; } log(`Save Page Now job ${submit.jobId}: waiting for the capture.`); return await poll(submit.jobId, headers); } catch (e) { if (opts.signal?.aborted) return { ...base, error: "cancelled" }; if (e instanceof ArchiveOrgRequestError) { if (e.rateLimited) return rested(redactSpnKeys(e.message, plan.keys), null); return { ...base, error: redactSpnKeys(e.message, plan.keys) }; } throw e; } } } // THE JOB: a `save-page-now` job on the archive.org queue, refused (no job) // with the plan's sentence. The log ends with `@@save-page-now {…}`. export async function queueSavePageNow(opts: { paths: Paths; url: string; slug?: string; requestedBy?: string; settings?: SpnSettings; deps?: Partial; pollMs?: number; onDone?: (result: SavePageNowResult) => void; }): Promise { const planned = await planSavePageNow(opts.paths, opts); if (!planned.ok) return { ok: false, error: planned.error }; const slug = planned.plan.slug; return runManagedFunction({ kind: SAVE_PAGE_NOW_JOB_KIND, queueKey: WAYBACK_PAGES_QUEUE, paths: opts.paths, ...(slug ? { channelSlug: slug } : {}), fn: async (onLog, signal) => { onLog( `Save Page Now (${planned.plan.mode === "keys" ? "with archive.org keys" : "anonymous: no keys"}): ${planned.plan.url}${slug ? ` into ${slug}` : ""}${opts.requestedBy ? ` for ${opts.requestedBy}` : ""}`, ); const result = await savePageNow({ paths: opts.paths, url: planned.plan.url, ...(slug ? { slug } : {}), ...(opts.settings ? { settings: opts.settings } : {}), ...(opts.deps ? { deps: opts.deps } : {}), ...(opts.pollMs !== undefined ? { pollMs: opts.pollMs } : {}), onLog, signal, }); onLog(`${SAVE_PAGE_NOW_RESULT_MARKER}${JSON.stringify(result)}`); opts.onDone?.(result); if (!result.ok) throw new Error(result.error ?? "Save Page Now failed"); }, }); } export class SavePageNowRefusal extends Error { constructor(message: string) { super(message); this.name = "SavePageNowRefusal"; } } // LANE B's DOOR (the Captures tab's targets): one `save-page-now` job for one // URL, its capture imported into `slug`. Throws SavePageNowRefusal with the // sentence when it is refused (no keys among them). export async function startSavePageNowJob(opts: { url: string; slug?: string; requestedBy?: string; paths?: Paths; }): Promise<{ jobId: string }> { const res = await queueSavePageNow({ ...opts, paths: opts.paths ?? getPaths() }); if (!res.ok) throw new SavePageNowRefusal(res.error); void res.stream.cancel(); return { jobId: res.jobId }; }