// Release 37 S5: Save Page Now on the fake Wayback — the keys read (env, a // mode-600 file, refused when others can read it, never a setting), the // refusals before any request, the capture asked → pending → success → the // capture imported into the channel, and the error paths: no keys, wrong keys, // a 429 that does not clear, a refused URL, a failed capture, a capture still // pending. The keys never appear in a log line or a result. No network. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/savePageNow.test.ts import test, { after } from "node:test"; import assert from "node:assert/strict"; import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { mkdir, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { FAKE_SPN_ACCESS, FAKE_SPN_SECRET, SPN_CAPTURE_TS, startFakeWayback } from "../testing/web/fakeWayback.mjs"; import type { Paths } from "../lib/paths"; import { WaybackClient } from "../lib/waybackClient"; import { readAllPosts } from "../lib/posts-server"; import { pageRecordId } from "../lib/waybackPages/types"; import { parseSpnStatus, parseSpnSubmit, spnSaveBody } from "../lib/waybackPages/savePageNow"; import { readSpnKeys } from "../lib/waybackPages/savePageNow-server"; import { looksLikeS3Key } from "../lib/archiveOrgTorrent"; import { sanitizeArchiveOrg } from "../lib/settingsSchema"; import { importPage } from "./importPage"; import { planSavePageNow, queueSavePageNow, savePageNow, savePageNowAvailability } from "./savePageNow"; const ROOT = mkdtempSync(path.join(tmpdir(), "save-page-now-")); after(() => rmSync(ROOT, { recursive: true, force: true })); const paths = { channelsDir: path.join(ROOT, "channels"), transcriptsDir: ROOT, jobsDir: path.join(ROOT, "jobs") } as unknown as Paths; const ENV = { ARCHIVE_ORG_S3_ACCESS: FAKE_SPN_ACCESS, ARCHIVE_ORG_S3_SECRET: FAKE_SPN_SECRET }; const NO_KEYS = path.join(ROOT, "no-such-keys.env"); const SETTINGS = { archiveOrg: { s3KeyFile: NO_KEYS }, social: { x: { visibility: "private" } } }; const LIVE = "https://live.example/notes/today.html"; async function channel(slug: string, config: Record) { const dir = path.join(paths.channelsDir, slug); await mkdir(dir, { recursive: true }); await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", name: slug, ...config })); return dir; } const pagesChannel = (slug: string, target: string) => channel(slug, { sourceKind: "social", platform: "webpage", socialHandle: "live.example", url: `https://web.archive.org/web/*/${target}*`, wayback: { targets: [{ url: target, match: "prefix" }] }, }); const noSleep = async () => {}; test("the keys: the environment first, else a mode-600 file; a file others can read is refused; never a setting", () => { assert.deepEqual(readSpnKeys({ keyFile: NO_KEYS, env: ENV }), { ok: true, keys: { access: FAKE_SPN_ACCESS, secret: FAKE_SPN_SECRET }, from: "env" }); const none = readSpnKeys({ keyFile: NO_KEYS, env: {} }); assert.equal(none.ok, false); assert.match(none.ok ? "" : none.reason, /Save Page Now needs archive\.org S3 keys/); const file = path.join(ROOT, "keys.env"); writeFileSync(file, `# archive.org\nARCHIVE_ORG_S3_ACCESS="${FAKE_SPN_ACCESS}"\nexport ARCHIVE_ORG_S3_SECRET=${FAKE_SPN_SECRET}\n`); chmodSync(file, 0o644); const open = readSpnKeys({ keyFile: file, env: {} }); assert.match(open.ok ? "" : open.reason, /readable by others — chmod 600/); chmodSync(file, 0o600); assert.deepEqual(readSpnKeys({ keyFile: file, env: {} }), { ok: true, keys: { access: FAKE_SPN_ACCESS, secret: FAKE_SPN_SECRET }, from: "file" }); const half = path.join(ROOT, "half.env"); writeFileSync(half, `ARCHIVE_ORG_S3_ACCESS=${FAKE_SPN_ACCESS}\n`, { mode: 0o600 }); assert.match((r => (r.ok ? "" : r.reason))(readSpnKeys({ keyFile: half, env: {} })), /no ARCHIVE_ORG_S3_ACCESS= and ARCHIVE_ORG_S3_SECRET= lines/); // The setting is a path; a key pasted there is refused, never stored. assert.equal(looksLikeS3Key(FAKE_SPN_ACCESS), true); assert.equal(looksLikeS3Key("~/.config/archilyzer/archive-org.env"), false); assert.equal(sanitizeArchiveOrg({ s3KeyFile: FAKE_SPN_SECRET }).s3KeyFile, "~/.config/archilyzer/archive-org.env"); assert.equal(sanitizeArchiveOrg({ s3KeyFile: "/etc/keys/ia.env" }).s3KeyFile, "/etc/keys/ia.env"); assert.equal(sanitizeArchiveOrg({}).s3KeyFile, "~/.config/archilyzer/archive-org.env"); // The button: off, with the sentence; on with keys. assert.deepEqual(savePageNowAvailability({ settings: SETTINGS, env: ENV }), { on: true, mode: "keys" }); // Lane spn-batch: NO keys configured is anonymous, not off. const anon = savePageNowAvailability({ settings: SETTINGS, env: {} }); assert.equal(anon.on && anon.mode, "anonymous"); // A key file that is there but unsafe is still off: the operator meant keys. chmodSync(file, 0o644); const off = savePageNowAvailability({ settings: { archiveOrg: { s3KeyFile: file } }, env: {} }); assert.equal(off.on, false); assert.match(off.on ? "" : off.reason, /readable by others/); chmodSync(file, 0o600); }); test("SPN's answers read: a job id, a refusal by status_ext, the keys refused; pending, success, a failed capture", () => { assert.deepEqual(parseSpnSubmit(200, JSON.stringify({ url: LIVE, job_id: "spn2-1" })), { ok: true, jobId: "spn2-1" }); const blocked = parseSpnSubmit(200, JSON.stringify({ status: "error", status_ext: "error:blocked-url", message: "blocked" })); assert.deepEqual([blocked.ok, blocked.ok ? "" : blocked.code], [false, "error:blocked-url"]); assert.equal((parseSpnSubmit(401, "{}") as { code?: string }).code, "auth"); assert.deepEqual(parseSpnStatus(200, '{"status":"pending"}'), { state: "pending" }); assert.deepEqual(parseSpnStatus(200, JSON.stringify({ status: "success", timestamp: SPN_CAPTURE_TS, original_url: LIVE })), { state: "success", timestamp: SPN_CAPTURE_TS, originalUrl: LIVE, }); assert.equal(parseSpnStatus(200, '{"status":"success"}').state, "error"); assert.match((parseSpnStatus(200, '{"status":"error","status_ext":"error:not-found","message":"404"}') as { error: string }).error, /error:not-found/); assert.equal(spnSaveBody(LIVE), `url=${encodeURIComponent(LIVE)}&capture_outlinks=0`); }); test("refused before any request: no keys, not http(s), a Wayback URL, not a pages channel, a video, X while private", async () => { await pagesChannel("live-notes", "live.example/"); await channel("a-video-channel", { url: "https://www.youtube.com/@x/videos" }); const ask = async (url: string, slug?: string, env: Record = ENV) => { const r = await planSavePageNow(paths, { url, ...(slug ? { slug } : {}), settings: SETTINGS, env }); return r.ok ? "" : r.error; }; // Lane spn-batch: no keys is not a refusal — the capture is asked anonymously. assert.equal(await ask(LIVE, "live-notes", {}), ""); const anonPlan = await planSavePageNow(paths, { url: LIVE, settings: SETTINGS, env: {} }); assert.equal(anonPlan.ok && anonPlan.plan.mode, "anonymous"); assert.match(await ask("ftp://live.example/x"), /only http and https/); assert.match(await ask(`https://web.archive.org/web/2014/${LIVE}`), /on the Wayback Machine already/); assert.match(await ask(LIVE, "a-video-channel"), /not a Wayback pages channel/); assert.match(await ask(LIVE, "nope"), /No such channel: nope/); assert.match(await ask("https://www.youtube.com/watch?v=abcdefghijk", "live-notes"), /is a video/); assert.match(await ask("https://x.com/someone", "live-notes"), /on X, whose posts are private here/); assert.equal(await ask(LIVE, "live-notes"), ""); assert.equal(await ask(LIVE), "", "no channel: the capture alone"); // The job door refuses the same way and starts nothing. const q = await queueSavePageNow({ paths, url: "https://www.youtube.com/watch?v=abcdefghijk", slug: "live-notes", settings: SETTINGS }); assert.equal(q.ok, false); }); test("asked → pending → success → the capture imported into the channel; the keys in no log line or result", async () => { const wb = await startFakeWayback({ spn: { pendingPolls: 2 } }); try { const client = new WaybackClient({ fetch: wb.fetch, sleep: noSleep }, { minGapMs: 0 }); const dir = await pagesChannel("live-notes-2", "live.example/"); const lines: string[] = []; const dry = await savePageNow({ paths, url: LIVE, slug: "live-notes-2", dryRun: true, settings: SETTINGS, env: ENV, deps: { client, sleep: noSleep } }); assert.equal(dry.ok, true); assert.match(dry.wouldAsk ?? "", /POST https:\/\/web\.archive\.org\/save .*then import the capture into live-notes-2/); assert.equal(wb.requests.length, 0, "a dry run asks nothing"); const r = await savePageNow({ paths, url: LIVE, slug: "live-notes-2", settings: SETTINGS, env: ENV, pollMs: 0, deps: { client, sleep: noSleep, importCapture: async (slug, url) => { const imp = await importPage({ paths, slug, url, client, settings: SETTINGS }); assert.equal(imp.ok, true, imp.error); return { jobId: "import-1" }; }, }, onLog: (l) => lines.push(l), }); assert.equal(r.ok, true, r.error); assert.deepEqual([r.captureTs, r.originalUrl, r.polls, r.importJobId], [SPN_CAPTURE_TS, LIVE, 3, "import-1"]); assert.equal(r.waybackUrl, `https://web.archive.org/web/${SPN_CAPTURE_TS}/${LIVE}`); assert.deepEqual(wb.spnForms, [{ url: LIVE, capture_outlinks: "0" }]); assert.deepEqual( wb.requests.map((q) => `${q.method} ${q.path.replace(/\?.*$/, "")}`).slice(0, 4), ["POST /save", "GET /save/status/spn2-fake-1", "GET /save/status/spn2-fake-1", "GET /save/status/spn2-fake-1"], ); const posts = await readAllPosts(dir); assert.deepEqual(posts.map((p) => p.id), [pageRecordId(SPN_CAPTURE_TS, LIVE)]); assert.match(posts[0]!.text, /captured by the fake Save Page Now/); const all = JSON.stringify({ lines, r }); assert.ok(!all.includes(FAKE_SPN_SECRET) && !all.includes(FAKE_SPN_ACCESS), "the keys never leave"); } finally { await wb.close(); } }); test("error paths: wrong keys, a 429 that does not clear, a refused URL, a failed capture, still pending", async () => { const wb = await startFakeWayback({ spn: { busyTimes: 9, failUrls: ["https://live.example/gone"], refuseUrls: ["https://live.example/blocked"] } }); try { const client = new WaybackClient({ fetch: wb.fetch, sleep: noSleep }, { minGapMs: 0, maxAttempts: 3 }); const run = (url: string, env: Record = ENV, maxPolls?: number) => savePageNow({ paths, url, settings: SETTINGS, env, pollMs: 0, ...(maxPolls ? { maxPolls } : {}), deps: { client, sleep: noSleep } }); const wrong = await run(LIVE, { ARCHIVE_ORG_S3_ACCESS: "WRONGACCESS", ARCHIVE_ORG_S3_SECRET: "WRONGSECRET" }); assert.match(wrong.error ?? "", /refused the S3 keys \(HTTP 401\)/); assert.ok(!(wrong.error ?? "").includes("WRONGSECRET")); const busy = await run(LIVE); assert.equal(busy.ok, false); assert.match(busy.error ?? "", /did not answer .* after 3 attempts \(HTTP 429\); stopping/); } finally { await wb.close(); } const wb2 = await startFakeWayback({ spn: { failUrls: ["https://live.example/gone"], refuseUrls: ["https://live.example/blocked"], pendingPolls: 1 } }); try { const client = new WaybackClient({ fetch: wb2.fetch, sleep: noSleep }, { minGapMs: 0 }); const run = (url: string, maxPolls?: number) => savePageNow({ paths, url, settings: SETTINGS, env: ENV, pollMs: 0, ...(maxPolls ? { maxPolls } : {}), deps: { client, sleep: noSleep } }); const blocked = await run("https://live.example/blocked"); assert.match(blocked.error ?? "", /refused the capture \(HTTP 200, error:blocked-url\)/); const failed = await run("https://live.example/gone"); assert.match(failed.error ?? "", /the capture failed \(HTTP 200, error:not-found\)/); assert.ok(failed.spnJobId); const pending = await run("https://live.example/slow", 1); assert.match(pending.error ?? "", /still pending after 1 status checks/); // No slug: the capture is made, nothing imported. const alone = await run("https://live.example/alone"); assert.deepEqual([alone.ok, alone.importJobId], [true, undefined]); } finally { await wb2.close(); } });