Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 5ca1161dd768df87dcf6d03bde55b1ec144076de
parent 22e2ca7180f2b936511c42adb202591a6bf76f8b
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 20 Oct 2026 14:18:19 -0400

wayback pages live (common): page records' availability by their original URL, Save Page Now, find-copy's page mode, the fake's SPN block, ops actions, generated docs

- check-post-availability on a Wayback pages channel asks each record's ORIGINAL URL at its own site (web pacer,
  fenced, HEAD then GET), one request per distinct URL; deleted / account_unavailable / available / error with the
  status and reason kept in posts-availability.json (two additive record fields)
- PAGE_GONE_MARKERS: X, Tumblr, Google Docs and YouTube "does not exist" pages, unit-tested
- save-page-now job (SPN2 through WaybackClient.send / ArchiveOrgClient.send, platform:archive.org), keys from the
  environment or the mode-600 file settings archiveOrg.s3KeyFile names, never logged; the capture imported with
  startImportPageJob; startSavePageNowJob for the Captures tab
- find-copy pages mode (publish/findCopyPages.ts): a gone cited page's nearest capture imported into the covering
  channel, pointTo/as answered, the report not rewritten; one nearest-capture function
- ops: check-post-availability, save-page-now, find-copy pages; COMMANDS/ENVIRONMENT/SETTINGS regenerated

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
MCOMMANDS.md | 6++++--
MENVIRONMENT.md | 4+++-
MSETTINGS.md | 4+++-
Mcommon/bin/archilyzer.ts | 2+-
Acommon/controller/checkPageAvailability.test.ts | 152+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/checkPageAvailability.ts | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/checkPostAvailability.ts | 19+++++++++++++++++++
Acommon/controller/savePageNow.test.ts | 197+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/savePageNow.ts | 297+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/jobKinds.ts | 13+++++++++++++
Mcommon/lib/archiveOrgClient.ts | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/archiveOrgTorrent.ts | 14++++++++++++++
Mcommon/lib/envVars.ts | 4+++-
Mcommon/lib/posts-server.ts | 10+++++++++-
Mcommon/lib/posts.ts | 4++++
Mcommon/lib/settingsSchema.ts | 11+++++++++++
Mcommon/lib/waybackClient.ts | 10++++++++++
Acommon/lib/waybackPages/liveness-server.ts | 106+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/liveness.test.ts | 173+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/liveness.ts | 227+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/savePageNow-server.ts | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/savePageNow.ts | 106+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/publish/findCopyPages.test.ts | 229+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/publish/findCopyPages.ts | 420+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/testing/README.md | 2+-
Mcommon/testing/web/fakeWayback.d.mts | 23++++++++++++++++++++++-
Mcommon/testing/web/fakeWayback.mjs | 106++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mscripts/archilyzer-ops.mjs | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.test.mjs | 18++++++++++++++++++
Msettings.json.example | 3++-
30 files changed, 2416 insertions(+), 11 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -67,7 +67,7 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `archilyzer duplicates` | `[--threshold N] [--all-durations] [--blocking title\|duration\|both] [--near F] [--tolerance N] …` | on-demand duplicate detection (after index + stats) *(passthrough)* | | `archilyzer posts fetch` | `--slug <channel> [--full \| --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N]` | fetch a social channel's posts into its posts corpus (--older: walk back below the oldest archived post; --pages: a forum thread's latest N pages) *(passthrough)* | | `archilyzer posts import-html` | `<slug> <file-or-dir>… [--dry-run]` | import forum thread pages saved from a browser ("Save page as", .html) into a forum-thread channel: new posts appended, edited ones updated, nothing fetched | -| `archilyzer posts check` | `--slug <channel> [--mode stale\|unchecked\|all] [--limit N]` | which archived posts were deleted at the source *(passthrough)* | +| `archilyzer posts check` | `--slug <channel> [--mode stale\|unchecked\|all] [--limit N]` | which archived posts were deleted at the source (a Wayback pages channel: each record's ORIGINAL URL, asked at its own site) *(passthrough)* | | `archilyzer diarize backfill` | `[--dry-run] [--scope transcribed\|channel:<slug>\|video:<slug>/<id>] [--limit N] [--force] …` | diarize videos whose audio is still on disk *(passthrough)* | | `archilyzer digest plan` | `[--lane local\|remote] [--channels a,b] [--top N] [--json] [--census] …` | price the digest backfill; writes nothing *(passthrough)* | | `archilyzer digest validate` | `<channel> [<channel> …]` | score digests already on disk *(passthrough)* | @@ -160,8 +160,10 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `import-post` | import-post imports ONE post by its URL into a posts channel of its platform: {"slug", "url"} — an X status (x.com/&lt;handle&gt;/status/&lt;id&gt;) or a Bluesky post (bsky.app/profile/&lt;handle&gt;/post/&lt;id&gt;, or its at:// URI). Read through the channel's own fetcher (gallery-dl for X, with the channel's login; the public AppView for Bluesky) as an import-post job on the platform's queue. Refused, before any job: a URL that is not a post, a channel that is not a posts channel of that platform or whose fetcher cannot read one post, a post the URL names as another account's, the platform held or cooling down. A post already archived is not read again; one the platform says is another account's is not written. The log ends with @@import-post {ok, slug, url, id, written, already?, post?, error?}. | `pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait` | | `import-page` | import-page imports ONE Wayback Machine capture of a page that is not a video into a Wayback pages channel (platform "webpage"): {"slug", "url"} — a capture's replay URL (web.archive.org/web/&lt;timestamp&gt;/&lt;page&gt;) — or {"slug", "url": &lt;the page&gt;, "at": "YYYYMMDD\[hhmmss\]"} for the capture nearest that date (one CDX lookup). An import-page job on the archive.org queue, at archive.org's pace: the raw (id\_) body, at most 2 MB, html, plain text or JSON only, redirects followed inside the archive only and the FINAL capture recorded; stored under the channel's pages/, read by the first site extractor that claims it (else the generic one), its page records written to the channel's posts. Refused, before any job: no such channel, not a Wayback pages channel, a URL that names no capture, a video (use import-video), an X capture outside an X channel while social.x.visibility is "private". A capture already stored is not fetched again. "dryRun" answers what it would fetch and starts nothing. The log ends with @@import-page {ok, slug, url, captureTs, originalUrl, records, written, updated, unchanged, extractor, already?, error?}. | `pnpm ops import-page --json '{"slug":"demo-pages","url":"https://web.archive.org/web/20140305120000/https://blog.example/a-post.html","dryRun":true}'`<br>`pnpm ops import-page --json '{"slug":"demo-pages","url":"https://blog.example/a-post.html","at":"20140301"}' --wait` | | `reextract-pages` | reextract-pages re-derives a Wayback pages channel's records from the raw captures it stores: {"slug", "dryRun"?}. No request. A reextract-pages job on the archive.org queue (never beside an import into the channel): every stored capture read again by the extractor it goes to now, the records replaced when anything differs. The log ends with @@reextract-pages {captures, stale, records: {added, changed, removed, unchanged, kept}, written}. | `pnpm ops reextract-pages --json '{"slug":"demo-pages","dryRun":true}' --wait` | +| `check-post-availability` | check-post-availability checks which of a posts channel's archived posts are gone at their source: {"slug", "mode"?: "stale" (default) \| "unchecked" \| "all", "limit"?: 200}, as a check-post-availability job. A Wayback pages channel's records are checked by their ORIGINAL URL at its own site (never the Wayback Machine), one request per distinct URL through the editor's web pacer (3 s apart): HEAD, then GET when the HEAD is refused or the platform has a "gone" page; available (2xx on the same site), deleted (404/410, or X's, Tumblr's, Google Docs' or YouTube's "does not exist" page), account\_unavailable (suspended, not shared), error otherwise — with the status. A deleted original means the Wayback copy is the only copy. Verdicts go to posts-availability.json. | `pnpm ops check-post-availability --json '{"slug":"demo-pages","mode":"unchecked"}' --wait` | +| `save-page-now` | save-page-now asks the Wayback Machine to capture a live page now (Save Page Now, with archive.org's S3 keys): {"url", "slug"?, "dryRun"?}. A save-page-now job on the archive.org queue: the capture asked (the page alone, no outlinks), its status polled until it is made, then — with slug, a Wayback pages channel — an import-page job of the new capture. Refused, before any job: no keys (ARCHIVE\_ORG\_S3\_ACCESS and ARCHIVE\_ORG\_S3\_SECRET in the editor's environment, or the mode-600 file settings archiveOrg.s3KeyFile names), a URL that is not http(s), a page on the Wayback Machine, not a Wayback pages channel, a video, an X page outside an X channel while X is private. The keys are never logged. "dryRun" answers what it would ask and starts nothing. The log ends with @@save-page-now {ok, url, slug?, spnJobId, captureTs, originalUrl, waybackUrl, importJobId?, importError?, polls, error?}. | `pnpm ops save-page-now --json '{"url":"https://blog.example/a-post.html","slug":"demo-pages","dryRun":true}'`<br>`pnpm ops save-page-now --json '{"url":"https://blog.example/a-post.html","slug":"demo-pages"}' --wait` | | `wayback-lookup` | wayback-lookup answers the Wayback Machine's captures of a page (its CDX API): {"url"} or a record's {"slug", "id"} (its metadata's page, else its availability check's, else the playlist's), "okOnly"?: only the captures that recorded a 200, "limit"?: 100 (at most 500) -&gt; {url, found, captures: \[{timestamp, status, mimetype?, replayUrl}\]}, oldest first. One request through the editor's Wayback client, with archive.org's manners (one at a time, 2 s apart, 429s waited out). Read only. | `pnpm ops wayback-lookup --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","okOnly":true}'` | -| `find-copy` | find-copy looks for a copy of every gone recording (deleted or private) a report cites, and fetches the cited windows from it, as a find-copy job: {"article"} \| {"articles": true} \| {"siteId"}, "dryRun"?, "retryFailed"? -&gt; {jobId}. Per YouTube recording, one at a time: the Wayback Machine when it holds the video (the check yt-dlp makes, not a capture of the page), then archive.org (a mirror of the upload: its identifier, a file name or its original URL names the id, and the file has the recording's length). A copy a fetch failed from at its source (404, 410, 403, unreachable; never our own format selector) is not picked again, unless "retryFailed": true. A copy's windows are cut with a lenient selector (a direct file of unknown height: then the best single file). Every copy's windows go to ONE fetch-windows job on the archive.org clip queue, the copy's URL as each window's page, so the clips land in the recording's own clips/ with the copy (wayback or archive.org, and its URL) in each window's provenance. A recording with no copy is left: its moments show their words only, marked "Source deleted". The log ends with @@find-copy {recordings: \[{slug, id, gone, watchUrl, youtubeId, windows, failedBefore, tried, copy?, outcome}\], items, stopped?, fetchJobId?, refused?}. dryRun looks and starts no fetch; a cancelled job starts none. The scope mode (release 31): {"slug"} \| {"siteId"}, "gone": "no-transcript" \| "all", "dryRun"?, "max"? (10, at most 200), "retryFailed"? -&gt; {jobId}. Every gone (deleted or private) video of the channel, or of the site's channels, that holds no audio or video ("no-transcript": and no transcript; "all": the transcribed ones too, after) is looked for the same way, at most max per run; a video whose last copy attempt found none or failed in the last 30 days is left out unless "retryFailed". Each copy's WHOLE audio is fetched into the video's own record (audio.&lt;fmt&gt;; its metadata stays the original's, the copy is in wayback.json or archiveorg.json and copy-attempts.json) by ONE fetch-copies job on archive.org's download queue, one at a time; the transcription lane then transcribes it like any downloaded audio. A video neither source holds is recorded none-found. dryRun asks the same (paced) questions and records and fetches nothing. The log ends with @@find-copy {scope, gone, dryRun, max, channels, eligible, skipped, looked: \[{slug, id, gone, noTranscript, watchUrl, youtubeId, tried, copy?, via?, outcome}\], left, items, stopped?, fetchJobId?, refused?}. | `pnpm ops find-copy --json '{"article":"demo-article","dryRun":true}'`<br>`pnpm ops find-copy --json '{"article":"demo-article"}' --wait`<br>`pnpm ops find-copy --json '{"article":"demo-article","retryFailed":true}' --wait`<br>`pnpm ops find-copy --json '{"siteId":"demo-site","gone":"no-transcript","dryRun":true}' --wait`<br>`pnpm ops find-copy --json '{"slug":"demo-channel","gone":"all","max":5}' --wait` | +| `find-copy` | find-copy looks for a copy of every gone recording (deleted or private) a report cites, and fetches the cited windows from it, as a find-copy job: {"article"} \| {"articles": true} \| {"siteId"}, "dryRun"?, "retryFailed"? -&gt; {jobId}. Per YouTube recording, one at a time: the Wayback Machine when it holds the video (the check yt-dlp makes, not a capture of the page), then archive.org (a mirror of the upload: its identifier, a file name or its original URL names the id, and the file has the recording's length). A copy a fetch failed from at its source (404, 410, 403, unreachable; never our own format selector) is not picked again, unless "retryFailed": true. A copy's windows are cut with a lenient selector (a direct file of unknown height: then the best single file). Every copy's windows go to ONE fetch-windows job on the archive.org clip queue, the copy's URL as each window's page, so the clips land in the recording's own clips/ with the copy (wayback or archive.org, and its URL) in each window's provenance. A recording with no copy is left: its moments show their words only, marked "Source deleted". The log ends with @@find-copy {recordings: \[{slug, id, gone, watchUrl, youtubeId, windows, failedBefore, tried, copy?, outcome}\], items, stopped?, fetchJobId?, refused?}. dryRun looks and starts no fetch; a cancelled job starts none. The scope mode (release 31): {"slug"} \| {"siteId"}, "gone": "no-transcript" \| "all", "dryRun"?, "max"? (10, at most 200), "retryFailed"? -&gt; {jobId}. Every gone (deleted or private) video of the channel, or of the site's channels, that holds no audio or video ("no-transcript": and no transcript; "all": the transcribed ones too, after) is looked for the same way, at most max per run; a video whose last copy attempt found none or failed in the last 30 days is left out unless "retryFailed". Each copy's WHOLE audio is fetched into the video's own record (audio.&lt;fmt&gt;; its metadata stays the original's, the copy is in wayback.json or archiveorg.json and copy-attempts.json) by ONE fetch-copies job on archive.org's download queue, one at a time; the transcription lane then transcribes it like any downloaded audio. A video neither source holds is recorded none-found. dryRun asks the same (paced) questions and records and fetches nothing. The log ends with @@find-copy {scope, gone, dryRun, max, channels, eligible, skipped, looked: \[{slug, id, gone, noTranscript, watchUrl, youtubeId, tried, copy?, via?, outcome}\], left, items, stopped?, fetchJobId?, refused?}. The page mode (release 37): {"article"} \| {"articles": true} \| {"siteId"}, "pages": true, "channel"?, "max"? (10, at most 100), "dryRun"? -&gt; {jobId}. Every page a report cites ("page" citations) whose original is gone at its own site gets the Wayback capture nearest the citation's date (one CDX lookup) imported into the Wayback pages channel named, else the one whose targets cover the page; a cited page record whose original is gone has its capture imported again when it is not stored. A live page is left (save-page-now it). The answer names the record each citation should cite (pointTo) and the citation as a post citation of it (as); the report is not rewritten. A find-copy job on the archive.org queue; dryRun asks the same paced questions and imports nothing. The log ends with @@find-copy {host, dryRun, max, pages, posts, items: \[{citedBy, url, original, channel?, capture?, outcome, detail, pointTo?, as?, records?}\], left, stopped?}. | `pnpm ops find-copy --json '{"article":"demo-article","dryRun":true}'`<br>`pnpm ops find-copy --json '{"article":"demo-article"}' --wait`<br>`pnpm ops find-copy --json '{"article":"demo-article","retryFailed":true}' --wait`<br>`pnpm ops find-copy --json '{"siteId":"demo-site","gone":"no-transcript","dryRun":true}' --wait`<br>`pnpm ops find-copy --json '{"slug":"demo-channel","gone":"all","max":5}' --wait`<br>`pnpm ops find-copy --json '{"article":"demo-article","pages":true,"dryRun":true}' --wait`<br>`pnpm ops find-copy --json '{"siteId":"demo-site","pages":true,"channel":"demo-pages"}' --wait` | | `wayback-scan` | wayback-scan lists the Wayback Machine's captures of a Wayback pages channel's targets (config wayback.targets) into its wayback-scan.json, as a wayback-scan job on archive.org's queue: {"slug", "dryRun"?, "maxRows"? (50000, at most 200000), "full"?} -&gt; {jobId}. The CDX API per target (its matchType exact \| prefix \| host \| domain, status 200, its mimes — text/html unless it names text/plain or application/json — collapse=digest, its from/to), in pages of 5,000 with a resume key; obvious assets (css, js, images, fonts) dropped unless the target's include names them. One row per distinct (URL, digest) with first/last seen. No bodies: import-page fetches a capture. A run cut short (the row cap, a refusal, a drain) keeps each target's resume key and the next continues; once every target is complete the next run is a new pass, from 30 days before the last began, and what it adds is marked new; "full" starts a new pass from each target's start. Paced as archive.org asks (one at a time, 2 s apart, 429/503 waited out; a refusal stops the job). dryRun asks nothing and writes nothing: it logs the next request per target. The log ends with @@wayback-scan {slug, dryRun, pass, newPass, targets: \[{url, match, requests, rows, added, complete, resumeKey?, next?}\], requests, rowsRead, added, totalRows, complete, stopped?, error?}. | `pnpm ops wayback-scan --json '{"slug":"demo-pages","dryRun":true}' --wait`<br>`pnpm ops wayback-scan --json '{"slug":"demo-pages"}' --wait` | | `wayback-import` | wayback-import imports chosen rows of a Wayback pages channel's scan, one import-page job per row (the capture the content was first listed at), queued on archive.org's queue: {"slug", "keys"?: \["&lt;digest&gt; &lt;url&gt;", ...\]} or a range — "year"? (first seen), "prefix"? ("host/path/"), "q"? (text in the URL), "show"? (all \| new \| not-imported \| imported) — and "dryRun"? -&gt; {ok, slug, dryRun, chosen, queued: \[{key, url, jobId?}\], skipped: \[{key, why}\], left}. Rows already imported are skipped; at most 500 are queued a call (left: how many remain). The Captures tab's Import selected and Import all in range. | `pnpm ops wayback-import --json '{"slug":"demo-pages","year":"2014","show":"not-imported","dryRun":true}'` | | `report-draft` | report-draft runs a generation over an article's iteration as a report-draft job: {"task": "sweep" \| "revise-report" \| "revise-video" \| "research" \| a media draft, "article", ...} -&gt; {jobId, iteration, warnings?}. A sweep takes "question" and "channels" (and "from"/"to"): a new iteration; a revision takes "iteration" (the one it revises) and "feedback": a new iteration. A media draft — "narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube" — takes "iteration" (a done one; "entries"? entry ids, "force"? re-drafts a field that is a draft already; narrate "cards"?) and is a step on it: it drafts fields of the iteration's video manifest, never one the operator wrote. "copyOf" N runs iteration N again on "model". "extractorModel" is an API sweep's extractor (a Claude model id; default settings.generation.models.extractor). "model" defaults to settings.generation's route for the task (one routed to code needs a model named). A Claude model runs on draft:api, capped at "maxUsd" (default by task, never above caps.max), and is refused when the day's API total has reached caps.daily; a local model runs on draft:local, through the GPU arbiter, and is unloaded when it ends. The corpus is "source" (a handle), "build" (a composed build), or the newest build holding the channels. `job cancel <id>` stops it. The log ends with @@report-draft {article, iteration, task, status, summary, usd, minutes}; --wait prints it. A research run takes "question" ("channels"? "from"/"to"?) and "autonomy" (propose \| limits \| auto; default settings.generation.research): it searches the corpus, the web and archive.org and proposes acquisitions (archive.org imports, videos, new channels — always on no site —, posts, transcription, persisting), each with its reason and evidence, enqueuing what its autonomy and the settings' caps allow through the editor's own actions; the rest waits in the iteration's proposals.json. A sweep with "iteration" N CONTINUES research run N: its question, over its channels and every channel a done acquisition wrote into, the sweep's parent N; refused while N still waits, unless "force" (what is done so far). "seed" (a new sweep's, on a Claude model) is cited markdown in the /sweep shape — umtool's research board: kept as the iteration's seed.md, the report starts from it, and the sweep verifies and extends it. "ids" (a sweep's) restricts it to those recordings: an enumeration reads only their pages and answers only their rows, a read of another is refused. A "refresh" re-fetches an iteration's scope and folds in what changed: "iteration" (default: the current report's) — its question, its recorded enumerations and every channel its citations touch. One job on draft:refresh: the editor's own sync / refresh-report / transcribe-bucket (what landed) per video channel and fetch-posts per posts channel (a platform held or cooling down is skipped; transcribe-bucket is skipped, and said, while transcription is paused or no worker is enabled), then a local build of the site holding them (never a deploy); the enumerations again (new and changed recordings) and every cited quote read again (changed words, en vs en-orig, a source gone); nothing changed ends no-change, $0 — or partial, naming what a capped search did not reach. Else, within the caps ("model", "maxUsd", "extractorModel"; past one it ends held-by-cap with the delta and the estimate), a sweep restricted to the new recordings and a revision of the report: a new refresh iteration, refresh.json beside it. "fetch": false skips the fetch and the build; "dryRun": true answers {plan} and writes nothing. Its log ends with @@report-draft {…, refresh: {status, newIds, changed, drifted, deleted, summary}}. "verdicts" proposes a verdict for each UNRULED claim of a fact-check ("article"; "claims"? only those; "model"?, "maxUsd"?): the verdict bench's prompt, one claim per call, on a model in settings.generation.verdicts.models only (refused otherwise; none named: the first of them on the verdicts route). No iteration (iteration 0): the proposals go to the article's verdicts.proposed.json, never report.json; a claim the operator ruled, or whose proposal was reviewed, is not asked. Its log ends with @@report-draft {…, verdicts: {proposed, failed, skipped, promptVersion}}. | `pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait`<br>`pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'`<br>`pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait`<br>`pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}'`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article"}' --wait`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article","dryRun":true}'`<br>`pnpm ops report-draft --json '{"task":"triage","article":"co-host-watch","question":"Who co-hosts?","channels":["demo-channel"],"terms":"co-host"}' --wait`<br>`pnpm ops report-draft --json '{"task":"verdicts","article":"demo-factcheck"}' --wait` | diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -59,6 +59,8 @@ Tokens, credentials and knobs a running process reads. Most configuration is not |---|---|---|---| | `WORKER_TOKEN` | unset (both surfaces off) | Bearer token for the remote-worker API and for `/api/ops/*` (`pnpm ops` and `archilyzer gen`; the MCP's `fetch_clip`, `enqueue`, `get_job`, `channel_coverage`, `generation_policy`, `generate` and `get_transcript`'s editor fallback), and for an agent's write to umtool's notes (the MCP's `notes` reply, stamped "agent"; umtool reads it from its environment, else the editor's `editor/.env`). Set the same value on every end. | common/lib/workerToken.ts, scripts/archilyzer-ops.mjs, common/bin/gen.ts, mcp/src/fetchClip.ts, mcp/src/editorOps.ts, mcp/src/archivalTools.ts, umtool/lib/annotations/agentAuth.mjs | | `ANTHROPIC_API_KEY` | unset (the API key file is read instead) | The Claude API key for report and video generation on the API (release 27): read first, before the mode-600 key file the generation settings name. Sent only to the Messages API in `x-api-key`; never logged, and never in an error, a job record or a transcript. | common/lib/llm/anthropic.ts | +| `ARCHIVE_ORG_S3_ACCESS` | unset (the S3 key file is read instead) | archive.org's S3 access key for Save Page Now (release 37): read first, with `ARCHIVE_ORG_S3_SECRET`, before the mode-600 file `settings.archiveOrg.s3KeyFile` names. Both or neither. Sent only to web.archive.org/save in the `Authorization: LOW <access>:<secret>` header; never logged, and never in an error, a job record or a result. Without keys Save Page Now is off and says why. | common/lib/waybackPages/savePageNow-server.ts | +| `ARCHIVE_ORG_S3_SECRET` | unset (the S3 key file is read instead) | archive.org's S3 secret key for Save Page Now, with `ARCHIVE_ORG_S3_ACCESS` (above). | common/lib/waybackPages/savePageNow-server.ts | | `SYNC_HEARTBEAT_SECONDS` | `settings.syncScheduler.heartbeatSeconds` | Overrides the editor's in-process sync heartbeat. `0` = no internal timer (tick from cron instead). | editor/app/scheduler/heartbeat.ts | | `SYNC_TICK_URL` | `http://127.0.0.1:3001/api/scheduler/tick` | Where `archilyzer sync tick` (cron's heartbeat) posts. | common/bin/sync-tick.ts | | `SYNC_TICK_TOKEN` | unset (no auth) | Bearer token for the tick endpoint; set on both the editor and the cron job. | common/bin/sync-tick.ts, editor/app/scheduler/auth.ts | @@ -234,7 +236,7 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one | `E2E_CLIP_WINDOW_GAP_MS` | the real gap (30–45 s, more for Rumble) | The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes. | common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts | | `E2E_ODYSEE_PAGE_FIXTURE` | unset (a headless browser) | A JSON file of recorded Odysee page reads keyed by page URL (`"*"` for any): while set, the browser lookup answers from it instead of opening a browser (with no gap between lookups), and the player-page opener opens nothing. The editor's e2e server names a file in each slot's test data (`browser-lookup.spec`). | common/ytdlp/odyseePageReader.ts, common/ytdlp/storedUrlPageOpen.ts, common/ytdlp/odyseeBrowserLookup.ts | | `E2E_UMTOOL_ORIGIN_FILE` | unset (UMTOOL_URL) | A file holding one loopback origin; while it exists, umtool is that origin for the editor's Find clips — the stub umtool `find-clips.spec` starts. The editor's e2e server names a file in each slot's test data; anything but a loopback origin in it is ignored. | common/lib/umtoolUrl.ts | -| `E2E_WAYBACK_ORIGIN_FILE` | unset (the real Wayback Machine) | A file holding one loopback origin; while it exists, the editor's Wayback client sends every web.archive.org request (CDX, captures, the video index) there — the fake Wayback a spec starts (`common/testing/web/fakeWayback.mjs`). The editor's e2e server names a file in each slot's test data (`wayback-pages.spec`); anything but a loopback origin in it is ignored. | common/lib/waybackClient.ts | +| `E2E_WAYBACK_ORIGIN_FILE` | unset (the real Wayback Machine) | A file holding one loopback origin; while it exists, the editor's Wayback client sends every web.archive.org request (CDX, captures, the video index, Save Page Now) there — the fake Wayback a spec starts (`common/testing/web/fakeWayback.mjs`). The editor's e2e server names a file in each slot's test data (`wayback-pages.spec`); anything but a loopback origin in it is ignored. | common/lib/waybackClient.ts | | `E2E_BLUESKY_ORIGIN_FILE` | unset (the real Bluesky) | A file holding one loopback origin; while it exists, the Bluesky AppView, bsky.app and its image CDN are that origin — the fake Bluesky a spec starts (`common/testing/social/fakeBluesky.mjs`). The editor's e2e server names a file in each slot's test data (`capture-posts.spec`); anything but a loopback origin in it is ignored. | common/social/blueskyEndpoints.ts | | `E2E_AUDIO_CHECK_DEBUG_PAUSE_MS` | off | A debugging pause inside the audio check. | common/ytdlp/audioCheckedDownload.ts | | `E2E_FAKE_YTDLP_AUDIO_CHECK_MODE` | — | Fake yt-dlp: which audio-check scenario to act out. | editor/e2e/fixtures/bin/fake-ytdlp.mjs | diff --git a/SETTINGS.md b/SETTINGS.md @@ -812,6 +812,7 @@ How archive.org files are fetched (controller/archiveOrgDownload.ts). Over BitTo | `maxPeers` | `30` | Most peers per torrent (aria2c --bt-max-peers). Clamped to [1, 500]; default 30. | | `maxDownloadKiBps` | `0` | Download rate cap for a torrent fetch, KiB/s (aria2c --max-overall-download-limit). 0 = unlimited. | | `maxUploadKiBps` | `0` | Upload rate cap while downloading and seeding, KiB/s (aria2c --max-overall-upload-limit). 0 = unlimited. | +| `s3KeyFile` | `"~/.config/archilyzer/archive-org.env"` | Release 37: the file holding archive.org's S3 keys for Save Page Now ("Ask the Wayback Machine to capture this now"): two lines, `ARCHIVE_ORG_S3_ACCESS=…` and `ARCHIVE_ORG_S3_SECRET=…` (from archive.org/account/s3.php), mode 600 — refused when the group or others can read it. `~` is the editor's home. The KEYS themselves are never a setting: a value that is not a path is refused, never stored. `ARCHIVE_ORG_S3_ACCESS` + `ARCHIVE_ORG_S3_SECRET` in the editor's environment win over the file. No keys: Save Page Now is off, and says why. | Default: @@ -823,7 +824,8 @@ Default: "stallMinutes": 5, "maxPeers": 30, "maxDownloadKiBps": 0, - "maxUploadKiBps": 0 + "maxUploadKiBps": 0, + "s3KeyFile": "~/.config/archilyzer/archive-org.env" } ``` diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -854,7 +854,7 @@ export const COMMANDS: Command[] = [ }, }, script(["posts", "check"], "check-post-availability.ts", - "--slug <channel> [--mode stale|unchecked|all] [--limit N] which archived posts were deleted at the source"), + "--slug <channel> [--mode stale|unchecked|all] [--limit N] which archived posts were deleted at the source (a Wayback pages channel: each record's ORIGINAL URL, asked at its own site)"), script(["diarize", "backfill"], "diarize-backfill.ts", "[--dry-run] [--scope transcribed|channel:<slug>|video:<slug>/<id>] [--limit N] [--force] … diarize videos whose audio is still on disk"), script(["digest", "plan"], "digest-plan.ts", diff --git a/common/controller/checkPageAvailability.test.ts b/common/controller/checkPageAvailability.test.ts @@ -0,0 +1,152 @@ +// Release 37 S5: check-post-availability on a Wayback pages channel — each +// record's ORIGINAL URL asked at its own site (a stub fetch behind a web +// pacer), ONE request per distinct URL however many records share it, the +// verdicts and their status/reason in posts-availability.json, history only +// on a change, modes and limits counted in URLs. No network. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/checkPageAvailability.test.ts + +import test, { after } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { mkdir, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import type { Post } from "../lib/posts"; +import { readPostAvailability, upsertPosts } from "../lib/posts-server"; +import { WebPacer } from "../lib/web/pacer"; +import { checkPostAvailability } from "./checkPostAvailability"; +import { selectUrlsToCheck } from "./checkPageAvailability"; + +const ROOT = mkdtempSync(path.join(tmpdir(), "check-pages-")); +after(() => rmSync(ROOT, { recursive: true, force: true })); +const paths = { channelsDir: path.join(ROOT, "channels"), transcriptsDir: ROOT } as unknown as Paths; + +function record(slug: string, id: string, originalUrl: string, captureTs: string): Post { + return { + id, + slug: `${slug}/${id}`, + channelSlug: slug, + author: "blog.example", + createdAt: "2014-03-05T12:00:00.000Z", + uploadDate: "20140305", + text: `the words of ${id}`, + url: originalUrl, + platform: "webpage", + isReply: false, + isRepost: false, + links: [], + page: { + originalUrl, + captureTs, + waybackUrl: `https://web.archive.org/web/${captureTs}/${originalUrl}`, + rawUrl: `https://web.archive.org/web/${captureTs}id_/${originalUrl}`, + kind: "generic", + extractor: "generic", + extractorVersion: 1, + }, + }; +} + +async function pagesChannel(slug: string, posts: Post[]) { + const dir = path.join(paths.channelsDir, slug); + await mkdir(dir, { recursive: true }); + await writeFile( + path.join(dir, "config.json"), + JSON.stringify({ + name: slug, + handling: "transcribe", + sourceKind: "social", + platform: "webpage", + socialHandle: "blog.example", + url: "https://web.archive.org/web/*/blog.example/*", + wayback: { targets: [{ url: "blog.example/", match: "prefix" }] }, + }), + ); + await upsertPosts(dir, posts); + return dir; +} + +function stub(statusOf: (url: string) => number) { + const sent: string[] = []; + const pacer = new WebPacer( + { + fetch: async (url, init) => { + sent.push(`${init.method} ${url}`); + return new Response(null, { status: statusOf(url) }); + }, + sleep: async () => {}, + }, + { minGapMs: 0, maxAttempts: 1 }, + ); + return { sent, pageCheck: { pacer, resolve: async () => ["93.184.216.34"] } }; +} + +const GONE = "https://blog.example/2014/gone.html"; +const LIVE = "https://blog.example/2014/live.html"; +const DOWN = "https://blog.example/2014/down.html"; + +test("one request per original URL; every record of it gets the verdict, with its status and reason", async () => { + const dir = await pagesChannel("old-blog", [ + record("old-blog", "20140305120000-aaaa", GONE, "20140305120000"), + record("old-blog", "20150611090000-aaaa", GONE, "20150611090000"), + record("old-blog", "20140101000000-bbbb", LIVE, "20140101000000"), + record("old-blog", "20140202000000-cccc", DOWN, "20140202000000"), + ]); + const s = stub((url) => (url === GONE ? 404 : url === DOWN ? 500 : 200)); + const lines: string[] = []; + const r = await checkPostAvailability({ paths, slug: "old-blog", pageCheck: s.pageCheck, onLog: (l) => lines.push(l) }); + assert.equal(r.ok, true); + assert.deepEqual(s.sent.sort(), [`HEAD ${DOWN}`, `HEAD ${GONE}`, `HEAD ${LIVE}`]); + assert.equal(r.checked, 4); + assert.deepEqual(r.newlyDeleted.sort(), ["20140305120000-aaaa", "20150611090000-aaaa"]); + const av = await readPostAvailability(dir); + assert.deepEqual( + [av["20140305120000-aaaa"]!.availability, av["20140305120000-aaaa"]!.status, av["20140305120000-aaaa"]!.reason], + ["deleted", 404, "HTTP 404"], + ); + assert.equal(av["20150611090000-aaaa"]!.availability, "deleted"); + assert.equal(av["20140101000000-bbbb"]!.availability, "available"); + // An error is an error, never a deletion. + assert.deepEqual([av["20140202000000-cccc"]!.availability, av["20140202000000-cccc"]!.status], ["error", 500]); + assert.ok(lines.some((l) => /3 of 3 original URL\(s\) \(4 page record\(s\)\)/.test(l))); + assert.ok(lines.some((l) => /newly GONE/.test(l))); + + // Again, the down page back up: history appended for the change only. + const s2 = stub((url) => (url === GONE ? 404 : 200)); + await checkPostAvailability({ paths, slug: "old-blog", mode: "all", pageCheck: s2.pageCheck }); + const av2 = await readPostAvailability(dir); + assert.equal(av2["20140202000000-cccc"]!.availability, "available"); + assert.deepEqual(av2["20140202000000-cccc"]!.history?.map((h) => h.availability), ["error"]); + assert.deepEqual(av2["20140305120000-aaaa"]!.history ?? [], []); + + // `unchecked`: nothing left to ask. + const s3 = stub(() => 200); + const r3 = await checkPostAvailability({ paths, slug: "old-blog", mode: "unchecked", pageCheck: s3.pageCheck }); + assert.equal(r3.checked, 0); + assert.equal(s3.sent.length, 0); +}); + +test("the limit counts URLs, least recently checked first", () => { + const groups = new Map([ + ["https://a.example/", ["a1", "a2"]], + ["https://b.example/", ["b1"]], + ["https://c.example/", ["c1"]], + ]); + const av = { + a1: { availability: "available" as const, checkedAt: "2026-10-01T00:00:00Z" }, + a2: { availability: "available" as const, checkedAt: "2026-10-02T00:00:00Z" }, + b1: { availability: "available" as const, checkedAt: "2026-09-01T00:00:00Z" }, + }; + assert.deepEqual(selectUrlsToCheck(groups, av, "stale", 2), ["https://c.example/", "https://b.example/"]); + assert.deepEqual(selectUrlsToCheck(groups, av, "unchecked", 5), ["https://c.example/"]); + assert.deepEqual(selectUrlsToCheck(groups, av, "all", 5).length, 3); +}); + +test("a channel with no page records checks nothing", async () => { + await pagesChannel("empty-pages", []); + const s = stub(() => 200); + const r = await checkPostAvailability({ paths, slug: "empty-pages", pageCheck: s.pageCheck }); + assert.deepEqual([r.ok, r.checked, s.sent.length], [true, 0, 0]); +}); diff --git a/common/controller/checkPageAvailability.ts b/common/controller/checkPageAvailability.ts @@ -0,0 +1,101 @@ +// IS EACH PAGE RECORD'S ORIGINAL STILL UP? (release 37 S5) — the Wayback +// pages channel's branch of check-post-availability +// (./checkPostAvailability.ts). A page record's availability is the state of +// the ORIGINAL URL it was captured from, never the Wayback Machine's: +// lib/waybackPages/liveness-server.ts checkOriginalUrl, through the process's +// web pacer (one request at a time, 3 s apart, 429/503 backed off). +// +// ONE REQUEST PER DISTINCT URL: a capture split into many records (an X +// profile's tweets, a Tumblr index's posts) and the versions of one page share +// an original URL, and each of them gets the URL's verdict. `limit` counts +// URLs. The verdicts land in the same sidecar every post channel uses +// (posts-availability.json, mergePostAvailability: history appended only when +// a verdict changes), with the answer's status and reason; the index merges +// them in, so a record whose original is gone is `isDeleted` — the Wayback +// copy is then the only copy. + +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { mergePostAvailability, readAllPosts, readPostAvailability, writePostAvailability } from "../lib/posts-server"; +import type { PostAvailability, PostAvailabilityMap } from "../lib/posts"; +import { groupByOriginalUrl, type OriginalCheck } from "../lib/waybackPages/liveness"; +import { checkOriginalUrl, type CheckOriginalOptions } from "../lib/waybackPages/liveness-server"; +import type { CheckPostAvailabilityMode, CheckPostAvailabilityResult } from "./checkPostAvailability"; + +// Which original URLs to ask this run: `stale` (the default) the +// never-checked first, then the least recently checked (by the oldest check +// among the URL's records); `unchecked` only URLs with a record never +// checked; `all` every URL. At most `limit`. +export function selectUrlsToCheck( + groups: ReadonlyMap<string, readonly string[]>, + availability: PostAvailabilityMap, + mode: CheckPostAvailabilityMode, + limit: number, +): string[] { + const oldest = (ids: readonly string[]) => + ids.reduce((min, id) => { + const at = availability[id]?.checkedAt ?? ""; + return at < min ? at : min; + }, "￿"); + let urls = [...groups.keys()]; + if (mode === "unchecked") urls = urls.filter((u) => groups.get(u)!.some((id) => !availability[id])); + if (mode === "stale") { + const at = new Map(urls.map((u) => [u, oldest(groups.get(u)!)])); + urls.sort((a, b) => at.get(a)!.localeCompare(at.get(b)!)); + } + return urls.slice(0, Math.max(0, limit)); +} + +export async function checkPageAvailability(opts: { + paths: Paths; + slug: string; + mode: CheckPostAvailabilityMode; + limit: number; + onLog?: (line: string) => void; + signal?: AbortSignal; + // Tests: the pacer, the fence's resolver, loopback allowed. + check?: CheckOriginalOptions; + now?: () => Date; +}): Promise<CheckPostAvailabilityResult & { urls?: OriginalCheck[] }> { + const log = (line: string) => opts.onLog?.(line); + const channelRoot = path.join(opts.paths.channelsDir, opts.slug); + const empty = { checked: 0, deleted: 0, newlyDeleted: [] as string[], changed: 0, remaining: 0 }; + const records = (await readAllPosts(channelRoot)).filter((p) => p.page); + if (records.length === 0) return { ok: true, ...empty }; + const availability = await readPostAvailability(channelRoot); + const groups = groupByOriginalUrl(records); + const batch = selectUrlsToCheck(groups, availability, opts.mode, opts.limit); + if (batch.length === 0) { + log(`Nothing to check for ${opts.slug} (mode: ${opts.mode}).`); + return { ok: true, ...empty }; + } + log( + `Checking ${batch.length} of ${groups.size} original URL(s) (${records.length} page record(s)) of ${opts.slug} ` + + `at their own sites, not the Wayback Machine (mode: ${opts.mode}).`, + ); + const observations = new Map<string, PostAvailability>(); + const details = new Map<string, { status: number | null; reason: string }>(); + const urls: OriginalCheck[] = []; + for (const url of batch) { + if (opts.signal?.aborted) break; + const verdict = await checkOriginalUrl(url, { ...opts.check, ...(opts.signal ? { signal: opts.signal } : {}) }); + urls.push(verdict); + const ids = groups.get(url)!; + for (const id of ids) { + observations.set(id, verdict.availability); + details.set(id, { status: verdict.status, reason: verdict.reason }); + } + log(` ${url}: ${verdict.availability} — ${verdict.reason}${ids.length > 1 ? ` (${ids.length} records)` : ""}`); + } + const checkedAt = (opts.now?.() ?? new Date()).toISOString(); + const { map, newlyDeleted, changed } = mergePostAvailability(availability, observations, checkedAt, details); + await writePostAvailability(channelRoot, map); + const deleted = Object.values(map).filter((r) => r.availability === "deleted").length; + const remaining = records.filter((r) => !map[r.id]).length; + if (newlyDeleted.length > 0) { + log(`${newlyDeleted.length} page record(s) whose original is newly GONE (the Wayback copy is the only copy): ${newlyDeleted.slice(0, 10).join(", ")}${newlyDeleted.length > 10 ? ` (+${newlyDeleted.length - 10} more)` : ""}`); + } + log(`Done: ${urls.length} URL(s) checked (${observations.size} record(s)), ${changed} changed, ${deleted} gone overall, ${remaining} never checked.`); + if (opts.signal?.aborted) log("Cancelled; the rest are left for a later run."); + return { ok: true, checked: observations.size, deleted, newlyDeleted, changed, remaining, urls }; +} diff --git a/common/controller/checkPostAvailability.ts b/common/controller/checkPostAvailability.ts @@ -37,6 +37,9 @@ import "../social/xenforoFetcher"; import "../social/xGalleryDlFetcher"; import "../social/xPlaywrightFetcher"; import "../social/xNitterFetcher"; +import { isWaybackPagesChannel } from "../lib/waybackPages/config"; +import type { CheckOriginalOptions } from "../lib/waybackPages/liveness-server"; +import { checkPageAvailability } from "./checkPageAvailability"; export type CheckPostAvailabilityMode = "stale" | "unchecked" | "all"; @@ -58,6 +61,9 @@ export type CheckPostAvailabilityOptions = { limit?: number; onLog?: (line: string) => void; signal?: AbortSignal; + // A Wayback pages channel's check (release 37 S5): tests pass the pacer, + // the fence's resolver and loopback. + pageCheck?: CheckOriginalOptions; }; export type CheckPostAvailabilityResult = { @@ -119,6 +125,19 @@ export async function checkPostAvailability( if (!isSocialChannel(config)) { return { ok: false, ...empty, error: `${slug} is not a social channel.` }; } + // A Wayback pages channel (release 37 S5): each record's ORIGINAL URL, + // asked at its own site — no fetcher, never the Wayback Machine. + if (isWaybackPagesChannel(config)) { + return checkPageAvailability({ + paths, + slug, + mode, + limit, + ...(onLog ? { onLog } : {}), + ...(signal ? { signal } : {}), + ...(opts.pageCheck ? { check: opts.pageCheck } : {}), + }); + } const fetcher = resolveSocialFetcher(config.postFetcher, config.url); if (!fetcher) { diff --git a/common/controller/savePageNow.test.ts b/common/controller/savePageNow.test.ts @@ -0,0 +1,197 @@ +// 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<string, unknown>) { + 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 }); + const off = savePageNowAvailability({ settings: SETTINGS, env: {} }); + assert.equal(off.on, false); +}); + +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<string, string> = ENV) => { + const r = await planSavePageNow(paths, { url, ...(slug ? { slug } : {}), settings: SETTINGS, env }); + return r.ok ? "" : r.error; + }; + assert.match(await ask(LIVE, "live-notes", {}), /Save Page Now needs archive\.org S3 keys/); + 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: LIVE, 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<string, string> = 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(); + } +}); diff --git a/common/controller/savePageNow.ts b/common/controller/savePageNow.ts @@ -0,0 +1,297 @@ +// 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) +// +// Refused before any request, with the sentence a caller shows: no keys (the +// button is off and says why), 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"; + +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 } | { 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<Record<string, string | undefined>> } = {}): SavePageNowAvailability { + const settings = o.settings ?? (getSettings() as SpnSettings); + const read = readSpnKeys({ keyFile: settings.archiveOrg?.s3KeyFile, ...(o.env ? { env: o.env } : {}) }); + return read.ok ? { on: true } : { on: false, reason: read.reason }; +} + +export type SavePageNowPlan = { url: string; slug?: string; 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<Record<string, string | undefined>> }, +): 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 = readSpnKeys({ 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 } : {}), keys: read.keys } }; +} + +export type SavePageNowResult = { + ok: boolean; + url: string; + slug?: string; + 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; + error?: string; +}; + +export type SavePageNowDeps = { + client: Pick<WaybackClient, "send">; + sleep: (ms: number, signal?: AbortSignal) => Promise<void>; + // 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<void>((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<Record<string, string | undefined>>; + pollMs?: number; + maxPolls?: number; + deps?: Partial<SavePageNowDeps>; + onLog?: (line: string) => void; + signal?: AbortSignal; +}): Promise<SavePageNowResult> { + 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; + if (opts.dryRun) { + return { + ...base, + ok: true, + dryRun: true, + wouldAsk: `POST ${SPN_SAVE_URL} (url=${plan.url}, capture_outlinks=0), then poll its status${plan.slug ? `, then import the capture into ${plan.slug}` : ""}`, + }; + } + const deps: SavePageNowDeps = { + 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 headers = { authorization: spnAuthorization(plan.keys) }; + const pollMs = opts.pollMs ?? SPN_POLL_MS; + const maxPolls = opts.maxPolls ?? SPN_MAX_POLLS; + 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) return { ...base, error: redactSpnKeys(submit.error, plan.keys) }; + log(`Save Page Now job ${submit.jobId}: waiting for the capture.`); + let polls = 0; + for (;;) { + if (polls >= maxPolls) { + return { + ...base, + spnJobId: submit.jobId, + polls, + error: `the capture was still pending after ${polls} status checks; archive.org may finish it later (look the page up with wayback-lookup, then import-page it)`, + }; + } + await deps.sleep(pollMs, opts.signal); + polls++; + const st = await deps.client.send(spnStatusUrl(submit.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") return { ...base, spnJobId: submit.jobId, polls, error: redactSpnKeys(status.error, plan.keys) }; + const waybackUrl = waybackPageUrl({ captureTs: status.timestamp, originalUrl: status.originalUrl }); + log(`Captured: ${waybackUrl}`); + const out: SavePageNowResult = { + ...base, + ok: true, + spnJobId: submit.jobId, + polls, + captureTs: status.timestamp, + originalUrl: status.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) { + // The capture exists either way; the import is a click away. + out.importError = (e as Error).message; + log(`The import into ${plan.slug} was refused: ${out.importError}`); + } + } + return out; + } + } catch (e) { + if (opts.signal?.aborted) return { ...base, error: "cancelled" }; + if (e instanceof ArchiveOrgRequestError) 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<SavePageNowDeps>; + pollMs?: number; + onDone?: (result: SavePageNowResult) => void; +}): Promise<StreamActionResult> { + 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.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 }; +} diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts @@ -618,6 +618,19 @@ const JOB_KINDS: Record<string, JobKindMeta> = { queueKeyStrategy: "platform", needsText: true, }, + // Save Page Now (release 37 S5, controller/savePageNow.ts): ask the Wayback + // Machine to capture a live page now (SPN2, archive.org's S3 keys), wait for + // the capture, then start an import-page of it into the channel named. On + // the archive.org queue, like the imports; it writes nothing itself (the + // import does). Not drainable (one capture); not replayable (each run asks + // archive.org for a new capture). + "save-page-now": { + kind: "save-page-now", + label: "Save Page Now", + drainable: false, + replayable: false, + queueKeyStrategy: "platform", + }, // A screenshot and the attached media of specific archived posts (and the X // Article a post links to), into the channel's `posts-media/` // (controller/capturePosts.ts). On the PLATFORM queue, like fetch-posts: diff --git a/common/lib/archiveOrgClient.ts b/common/lib/archiveOrgClient.ts @@ -304,6 +304,57 @@ export class ArchiveOrgClient { }); } + // ANY METHOD, ONE REQUEST (release 37 S5, Save Page Now: a form POST and its + // status polls carry an Authorization header) through the same chain and + // gap. A 429/503 (and 502/504, a dropped connection) is waited out and + // retried as getOnce does, then ArchiveOrgRequestError `rateLimited`; any + // other answer — a 4xx included — is handed back with its body as text, for + // the caller to read (SPN answers its refusals as JSON). The headers given + // are sent and never put in an error or a log line. + send( + url: string, + init: { method: "GET" | "POST"; headers?: Record<string, string>; body?: string; accept?: string; signal?: AbortSignal }, + ): Promise<{ status: number; text: string }> { + return this.serial(async () => { + let lastError = ""; + for (let attempt = 1; attempt <= this.opts.maxAttempts; attempt++) { + const wait = this.lastDoneAt + this.opts.minGapMs - this.deps.now(); + if (wait > 0) await this.deps.sleep(wait, init.signal); + this.requests++; + let res: Response | null = null; + let text = ""; + try { + const timeout = AbortSignal.timeout(this.opts.timeoutMs); + res = await this.deps.fetch(url, { + method: init.method, + signal: init.signal ? AbortSignal.any([init.signal, timeout]) : timeout, + redirect: "follow", + headers: { accept: init.accept ?? "application/json", "user-agent": ARCHIVE_ORG_USER_AGENT, ...init.headers }, + ...(init.body !== undefined ? { body: init.body } : {}), + }); + text = await res.text(); + } catch (err) { + if (init.signal?.aborted) throw err; + lastError = (err as Error).message; + res = null; + } finally { + this.lastDoneAt = this.deps.now(); + } + if (res && !RETRYABLE.has(res.status)) return { status: res.status, text }; + if (res) lastError = `HTTP ${res.status}`; + if (attempt === this.opts.maxAttempts) break; + const retryAfter = res ? parseRetryAfterMs(res.headers.get("retry-after"), this.deps.now()) : null; + const delay = Math.min(this.opts.maxBackoffMs, retryAfter ?? this.backoffMs(attempt)); + await this.deps.sleep(delay, init.signal); + } + throw new ArchiveOrgRequestError( + `archive.org did not answer ${url} after ${this.opts.maxAttempts} attempts (${lastError}); stopping`, + null, + true, + ); + }); + } + getJson(url: string, signal?: AbortSignal): Promise<unknown> { return this.serial(async () => { const res = await this.getOnce(url, "application/json", signal); diff --git a/common/lib/archiveOrgTorrent.ts b/common/lib/archiveOrgTorrent.ts @@ -150,8 +150,14 @@ export type ArchiveOrgFetchSettings = { // 0 = unlimited. maxDownloadKiBps: number; maxUploadKiBps: number; + // Release 37 S5: the PATH of the mode-600 file holding archive.org's S3 + // keys for Save Page Now (lib/waybackPages/savePageNow-server.ts). Never + // the keys themselves. + s3KeyFile: string; }; +export const DEFAULT_ARCHIVE_ORG_S3_KEY_FILE = "~/.config/archilyzer/archive-org.env"; + export const DEFAULT_ARCHIVE_ORG_FETCH_SETTINGS: ArchiveOrgFetchSettings = { torrent: true, seedMinutes: 10, @@ -160,8 +166,16 @@ export const DEFAULT_ARCHIVE_ORG_FETCH_SETTINGS: ArchiveOrgFetchSettings = { maxPeers: 30, maxDownloadKiBps: 0, maxUploadKiBps: 0, + s3KeyFile: DEFAULT_ARCHIVE_ORG_S3_KEY_FILE, }; +// A value for `s3KeyFile` that is not a path (no "/", no leading "~") is +// taken for a key pasted in the wrong place: refused, never stored. +export function looksLikeS3Key(v: string): boolean { + const s = v.trim(); + return !!s && !s.includes("/") && !s.startsWith("~"); +} + // ─── The aria2c command line ─── export type Aria2cSpec = { diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -95,6 +95,8 @@ const DECLARED: EnvVarDecl[] = [ // ── runtime ──────────────────────────────────────────────────────────── { name: "WORKER_TOKEN", audience: "runtime", default: "unset (both surfaces off)", readBy: "common/lib/workerToken.ts, scripts/archilyzer-ops.mjs, common/bin/gen.ts, mcp/src/fetchClip.ts, mcp/src/editorOps.ts, mcp/src/archivalTools.ts, umtool/lib/annotations/agentAuth.mjs", doc: "Bearer token for the remote-worker API and for `/api/ops/*` (`pnpm ops` and `archilyzer gen`; the MCP's `fetch_clip`, `enqueue`, `get_job`, `channel_coverage`, `generation_policy`, `generate` and `get_transcript`'s editor fallback), and for an agent's write to umtool's notes (the MCP's `notes` reply, stamped \"agent\"; umtool reads it from its environment, else the editor's `editor/.env`). Set the same value on every end." }, { name: "ANTHROPIC_API_KEY", audience: "runtime", default: "unset (the API key file is read instead)", readBy: "common/lib/llm/anthropic.ts", doc: "The Claude API key for report and video generation on the API (release 27): read first, before the mode-600 key file the generation settings name. Sent only to the Messages API in `x-api-key`; never logged, and never in an error, a job record or a transcript." }, + { name: "ARCHIVE_ORG_S3_ACCESS", audience: "runtime", default: "unset (the S3 key file is read instead)", readBy: "common/lib/waybackPages/savePageNow-server.ts", doc: "archive.org's S3 access key for Save Page Now (release 37): read first, with `ARCHIVE_ORG_S3_SECRET`, before the mode-600 file `settings.archiveOrg.s3KeyFile` names. Both or neither. Sent only to web.archive.org/save in the `Authorization: LOW <access>:<secret>` header; never logged, and never in an error, a job record or a result. Without keys Save Page Now is off and says why." }, + { name: "ARCHIVE_ORG_S3_SECRET", audience: "runtime", default: "unset (the S3 key file is read instead)", readBy: "common/lib/waybackPages/savePageNow-server.ts", doc: "archive.org's S3 secret key for Save Page Now, with `ARCHIVE_ORG_S3_ACCESS` (above)." }, { name: "SYNC_HEARTBEAT_SECONDS", audience: "runtime", default: "`settings.syncScheduler.heartbeatSeconds`", readBy: "editor/app/scheduler/heartbeat.ts", doc: "Overrides the editor's in-process sync heartbeat. `0` = no internal timer (tick from cron instead)." }, { name: "SYNC_TICK_URL", audience: "runtime", default: "`http://127.0.0.1:3001/api/scheduler/tick`", readBy: "common/bin/sync-tick.ts", doc: "Where `archilyzer sync tick` (cron's heartbeat) posts." }, { name: "SYNC_TICK_TOKEN", audience: "runtime", default: "unset (no auth)", readBy: "common/bin/sync-tick.ts, editor/app/scheduler/auth.ts", doc: "Bearer token for the tick endpoint; set on both the editor and the cron job." }, @@ -231,7 +233,7 @@ const DECLARED: EnvVarDecl[] = [ { name: "E2E_CLIP_WINDOW_GAP_MS", audience: "test", default: "the real gap (30–45 s, more for Rumble)", readBy: "common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts", doc: "The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes." }, { name: "E2E_ODYSEE_PAGE_FIXTURE", audience: "test", default: "unset (a headless browser)", readBy: "common/ytdlp/odyseePageReader.ts, common/ytdlp/storedUrlPageOpen.ts, common/ytdlp/odyseeBrowserLookup.ts", doc: "A JSON file of recorded Odysee page reads keyed by page URL (`\"*\"` for any): while set, the browser lookup answers from it instead of opening a browser (with no gap between lookups), and the player-page opener opens nothing. The editor's e2e server names a file in each slot's test data (`browser-lookup.spec`)." }, { name: "E2E_UMTOOL_ORIGIN_FILE", audience: "test", default: "unset (UMTOOL_URL)", readBy: "common/lib/umtoolUrl.ts", doc: "A file holding one loopback origin; while it exists, umtool is that origin for the editor's Find clips — the stub umtool `find-clips.spec` starts. The editor's e2e server names a file in each slot's test data; anything but a loopback origin in it is ignored." }, - { name: "E2E_WAYBACK_ORIGIN_FILE", audience: "test", default: "unset (the real Wayback Machine)", readBy: "common/lib/waybackClient.ts", doc: "A file holding one loopback origin; while it exists, the editor's Wayback client sends every web.archive.org request (CDX, captures, the video index) there — the fake Wayback a spec starts (`common/testing/web/fakeWayback.mjs`). The editor's e2e server names a file in each slot's test data (`wayback-pages.spec`); anything but a loopback origin in it is ignored." }, + { name: "E2E_WAYBACK_ORIGIN_FILE", audience: "test", default: "unset (the real Wayback Machine)", readBy: "common/lib/waybackClient.ts", doc: "A file holding one loopback origin; while it exists, the editor's Wayback client sends every web.archive.org request (CDX, captures, the video index, Save Page Now) there — the fake Wayback a spec starts (`common/testing/web/fakeWayback.mjs`). The editor's e2e server names a file in each slot's test data (`wayback-pages.spec`); anything but a loopback origin in it is ignored." }, { name: "E2E_BLUESKY_ORIGIN_FILE", audience: "test", default: "unset (the real Bluesky)", readBy: "common/social/blueskyEndpoints.ts", doc: "A file holding one loopback origin; while it exists, the Bluesky AppView, bsky.app and its image CDN are that origin — the fake Bluesky a spec starts (`common/testing/social/fakeBluesky.mjs`). The editor's e2e server names a file in each slot's test data (`capture-posts.spec`); anything but a loopback origin in it is ignored." }, { name: "E2E_AUDIO_CHECK_DEBUG_PAUSE_MS", audience: "test", default: "off", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "A debugging pause inside the audio check." }, { name: "E2E_FAKE_YTDLP_AUDIO_CHECK_MODE", audience: "test", default: "—", readBy: "editor/e2e/fixtures/bin/fake-ytdlp.mjs", doc: "Fake yt-dlp: which audio-check scenario to act out." }, diff --git a/common/lib/posts-server.ts b/common/lib/posts-server.ts @@ -416,6 +416,8 @@ export async function readPostAvailability( availability: r.availability, checkedAt: r.checkedAt, ...(Array.isArray(r.history) ? { history: r.history } : {}), + ...(typeof r.status === "number" || r.status === null ? { status: r.status } : {}), + ...(typeof r.reason === "string" ? { reason: r.reason } : {}), }; } return out; @@ -436,19 +438,24 @@ export async function writePostAvailability( // Fold new observations in, appending to history ONLY when the availability // actually changes. That keeps the file small and, more importantly, preserves // the moment a post was first seen deleted — which is the fact worth keeping. +// `details` (release 37 S5, a page record's original-URL check) carries the +// answer's status and reason, kept on the record (the latest only). export function mergePostAvailability( existing: PostAvailabilityMap, observations: ReadonlyMap<string, PostAvailability>, checkedAt: string, + details?: ReadonlyMap<string, { status: number | null; reason: string }>, ): { map: PostAvailabilityMap; newlyDeleted: string[]; changed: number } { const map: PostAvailabilityMap = { ...existing }; const newlyDeleted: string[] = []; let changed = 0; for (const [id, availability] of observations) { const prev = map[id]; + const detail = details?.get(id); + const facts = detail ? { status: detail.status, reason: detail.reason } : {}; if (prev?.availability === availability) { // Same verdict — just refresh when we last looked. - map[id] = { ...prev, checkedAt }; + map[id] = { ...prev, checkedAt, ...facts }; continue; } changed++; @@ -458,6 +465,7 @@ export function mergePostAvailability( map[id] = { availability, checkedAt, + ...facts, history: [ ...(prev?.history ?? []), ...(prev diff --git a/common/lib/posts.ts b/common/lib/posts.ts @@ -188,6 +188,10 @@ export type PostAvailabilityRecord = { // Appended only when the availability CHANGES, so the file stays small and // the first-seen-deleted moment is preserved. Mirrors the video record. history?: { availability: PostAvailability; at: string }[]; + // Release 37 S5 (a page record: its ORIGINAL URL's check): the last + // answer's HTTP status (null: none) and why, in a phrase. + status?: number | null; + reason?: string; }; // postId -> record, stored once per channel. Videos keep a file per video dir, diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -74,6 +74,7 @@ import { import { ATTRIBUTION_PROMPT_VERSION } from "./attribution"; import { DEFAULT_ARCHIVE_ORG_FETCH_SETTINGS, + looksLikeS3Key, type ArchiveOrgFetchSettings, } from "./archiveOrgTorrent"; import { sanitizeSeeder, type SeederSettings } from "./seederSettings"; @@ -539,6 +540,12 @@ export const ARCHIVE_ORG_SETTINGS_FIELD_DOCS: FieldDocs<ArchiveOrgFetchSettings> maxUploadKiBps: "Upload rate cap while downloading and seeding, KiB/s (aria2c " + "--max-overall-upload-limit). 0 = unlimited.", + s3KeyFile: + "Release 37: the file holding archive.org's S3 keys for Save Page Now (\"Ask the Wayback Machine to capture this now\"): " + + "two lines, `ARCHIVE_ORG_S3_ACCESS=…` and `ARCHIVE_ORG_S3_SECRET=…` (from archive.org/account/s3.php), mode 600 — " + + "refused when the group or others can read it. `~` is the editor's home. The KEYS themselves are never a setting: " + + "a value that is not a path is refused, never stored. `ARCHIVE_ORG_S3_ACCESS` + `ARCHIVE_ORG_S3_SECRET` in the " + + "editor's environment win over the file. No keys: Save Page Now is off, and says why.", }; function clampNumber(value: unknown, fallback: number, min: number, max: number): number { @@ -558,6 +565,10 @@ export function sanitizeArchiveOrg(value: unknown): ArchiveOrgFetchSettings { maxPeers: Math.floor(clampNumber(r.maxPeers, d.maxPeers, 1, 500)), maxDownloadKiBps: Math.floor(clampNumber(r.maxDownloadKiBps, d.maxDownloadKiBps, 0, 10_000_000)), maxUploadKiBps: Math.floor(clampNumber(r.maxUploadKiBps, d.maxUploadKiBps, 0, 10_000_000)), + s3KeyFile: + typeof r.s3KeyFile === "string" && r.s3KeyFile.trim() && !looksLikeS3Key(r.s3KeyFile) + ? r.s3KeyFile.trim() + : d.s3KeyFile, }; } diff --git a/common/lib/waybackClient.ts b/common/lib/waybackClient.ts @@ -203,6 +203,16 @@ export class WaybackClient { 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: { method: "GET" | "POST"; headers?: Record<string, string>; body?: string; accept?: string; signal?: AbortSignal }, + ): Promise<{ status: number; text: string }> { + 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<boolean> { diff --git a/common/lib/waybackPages/liveness-server.ts b/common/lib/waybackPages/liveness-server.ts @@ -0,0 +1,106 @@ +// ONE ORIGINAL URL'S STATE (release 37 S5): the request side of +// ./liveness.ts. Through the process's web pacer (lib/web/pacer.ts: one +// request at a time, 3 s apart, 429/503 backed off) — never the Wayback +// Machine, never a burst — and behind the web fetch's fence (http(s) only, +// no private or loopback host, every redirect hop checked the same way). +// +// HEAD, following redirects by hand (at most WEB_FETCH_MAX_REDIRECTS); +// a GET instead when the HEAD is refused (405, 403, 501) or when the page's +// platform has a "gone" page that answers 200 (its words decide), its body +// read up to LIVENESS_MAX_BODY_BYTES. +// +// Answers an OriginalCheck; never throws for what the site answered (a +// cancelled run's abort is rethrown). + +import { fetchRefusal, WEB_FETCH_MAX_REDIRECTS, type WebFetchOptions } from "../web/fetchPage"; +import { webPacer, WebRequestError, type WebPacer } from "../web/pacer"; +import { classifyOriginalAnswer, hasGoneMarkers, type OriginalCheck } from "./liveness"; + +// A "gone" page's words are near its top: the body is read no further. +export const LIVENESS_MAX_BODY_BYTES = 256 * 1024; + +// A HEAD these statuses refuse is asked again as a GET. +const HEAD_REFUSED = new Set([403, 405, 501]); + +export type CheckOriginalOptions = Pick<WebFetchOptions, "allowPrivate" | "resolve"> & { + pacer?: WebPacer; + signal?: AbortSignal; +}; + +async function readCapped(res: Response, maxBytes: number): Promise<string> { + if (!res.body) return ""; + const reader = res.body.getReader(); + const chunks: Uint8Array[] = []; + let n = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + chunks.push(value); + n += value.byteLength; + if (n >= maxBytes) { + await reader.cancel().catch(() => {}); + break; + } + } + return new TextDecoder("utf-8", { fatal: false }).decode(Buffer.concat(chunks).subarray(0, maxBytes)); +} + +type Hop = { redirect: string } | { status: number; body?: string }; + +// One method's walk: redirects followed by hand, each hop fenced. +async function walk( + url: string, + method: "HEAD" | "GET", + o: CheckOriginalOptions, +): Promise<{ finalUrl: string; status: number; body?: string } | { refusal: string; status: number | null; finalUrl: string }> { + const pacer = o.pacer ?? webPacer; + let at = url; + for (let hop = 0; hop <= WEB_FETCH_MAX_REDIRECTS; hop++) { + const refusal = await fetchRefusal(at, o); + if (refusal) return { refusal, status: null, finalUrl: at }; + const step: Hop = await pacer.request( + at, + { + method, + redirect: "manual", + headers: { accept: "text/html,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.5" }, + ...(o.signal ? { signal: o.signal } : {}), + }, + async (res): Promise<Hop> => { + const loc = res.headers.get("location"); + if (res.status >= 300 && res.status < 400 && loc) { + await res.body?.cancel().catch(() => {}); + return { redirect: new URL(loc, at).toString() }; + } + if (method === "HEAD") { + await res.body?.cancel().catch(() => {}); + return { status: res.status }; + } + return { status: res.status, body: await readCapped(res, LIVENESS_MAX_BODY_BYTES) }; + }, + ); + if ("redirect" in step) { + at = step.redirect; + continue; + } + return { finalUrl: at, status: step.status, ...(step.body !== undefined ? { body: step.body } : {}) }; + } + return { refusal: `more than ${WEB_FETCH_MAX_REDIRECTS} redirects`, status: null, finalUrl: at }; +} + +export async function checkOriginalUrl(url: string, o: CheckOriginalOptions = {}): Promise<OriginalCheck> { + try { + let answer = await walk(url, "HEAD", o); + const headRefused = !("refusal" in answer) && HEAD_REFUSED.has(answer.status); + const needsBody = !("refusal" in answer) && answer.status >= 200 && answer.status < 300 && hasGoneMarkers(answer.finalUrl); + if (headRefused || needsBody) answer = await walk(url, "GET", o); + if ("refusal" in answer) { + return { url, availability: "error", status: answer.status, ...(answer.finalUrl !== url ? { finalUrl: answer.finalUrl } : {}), reason: answer.refusal }; + } + return classifyOriginalAnswer({ url, finalUrl: answer.finalUrl, status: answer.status, ...(answer.body !== undefined ? { body: answer.body } : {}) }); + } catch (e) { + if (o.signal?.aborted) throw e; + const status = e instanceof WebRequestError ? e.status : null; + return { url, availability: "error", status, reason: (e as Error).message }; + } +} diff --git a/common/lib/waybackPages/liveness.test.ts b/common/lib/waybackPages/liveness.test.ts @@ -0,0 +1,173 @@ +// Release 37 S5: a page record's ORIGINAL — the marker table, the verdict on +// one answer, the same-site rule, grouping by original URL, and the request +// side (HEAD, then GET) through a web pacer over a stub fetch. No network. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/waybackPages/liveness.test.ts + +import test from "node:test"; +import assert from "node:assert/strict"; +import { + classifyOriginalAnswer, + foldPageText, + groupByOriginalUrl, + hasGoneMarkers, + PAGE_GONE_MARKERS, + pageGoneMarker, + sameSite, + siteOf, +} from "./liveness"; +import { checkOriginalUrl } from "./liveness-server"; +import { WebPacer } from "../web/pacer"; + +// Synthetic "gone" pages: each marker's words in the platform's own furniture. +const page = (words: string) => `<!doctype html><html><head><title>t</title><script>var x="${words.slice(0, 3)}";</script></head><body><div class="x"><h1>${words}</h1><p>Try something else.</p></div></body></html>`; + +const MARKER_CASES: { id: string; url: string; html: string }[] = [ + { id: "x-no-account", url: "https://x.com/someone", html: page("This account doesn&rsquo;t exist") }, + { id: "x-no-page", url: "https://twitter.com/someone/status/1", html: page("Hmm...this page doesn’t exist. Try searching for something else.") }, + { id: "x-suspended", url: "https://mobile.twitter.com/someone", html: page("Account suspended") }, + { id: "tumblr-nothing-here", url: "https://someone.tumblr.com/post/123", html: page("There's nothing here.") }, + { id: "tumblr-nothing-here", url: "https://www.tumblr.com/someone", html: page("Whatever you were looking for doesn&#39;t currently exist at this address. Unless you were looking for this error page, in which case: Congrats!") }, + { id: "gdocs-no-file", url: "https://docs.google.com/document/d/abc/edit", html: page("Sorry, the file you have requested does not exist.") }, + { id: "gdocs-permission", url: "https://drive.google.com/file/d/abc/view", html: page("You need access") }, + { id: "youtube-no-channel", url: "https://www.youtube.com/@someone/about", html: page("This channel does not exist.") }, + { id: "youtube-terminated", url: "https://m.youtube.com/channel/UCabc", html: page("This account has been terminated for a violation of YouTube's Terms of Service.") }, +]; + +test("the marker table: every platform's gone page is told by its words, on its own hosts only", () => { + for (const c of MARKER_CASES) { + assert.equal(pageGoneMarker(c.url, c.html)?.id, c.id, c.url); + } + // Every marker has a case. + assert.deepEqual(new Set(MARKER_CASES.map((c) => c.id)), new Set(PAGE_GONE_MARKERS.map((m) => m.id))); + // The same words elsewhere are not a gone page (a blog quoting X's message). + assert.equal(pageGoneMarker("https://blog.example/post", page("This account doesn't exist")), null); + assert.equal(pageGoneMarker("https://example.tumblr.net/", page("There's nothing here.")), null); + // A live page on the platform is not one either. + assert.equal(pageGoneMarker("https://someone.tumblr.com/post/1", page("A post about bread")), null); + // Words inside a script are not the page's. + assert.equal(pageGoneMarker("https://x.com/a", `<html><script>var m = "Account suspended";</script><p>hello</p></html>`), null); + assert.equal(hasGoneMarkers("https://www.youtube.com/@a/about"), true); + assert.equal(hasGoneMarkers("https://blog.example/"), false); + assert.equal(foldPageText("<p>Doesn&rsquo;t&nbsp; <b>EXIST</b></p>"), "doesn't exist"); +}); + +test("one answer's verdict: 404/410 deleted, 2xx available on the same site, a marker, anything else an error with its status", () => { + const v = (url: string, finalUrl: string, status: number, body?: string) => + classifyOriginalAnswer({ url, finalUrl, status, ...(body !== undefined ? { body } : {}) }); + assert.deepEqual( + [v("https://a.example/x", "https://a.example/x", 404).availability, v("https://a.example/x", "https://a.example/x", 410).availability], + ["deleted", "deleted"], + ); + const ok = v("http://a.example/x", "https://www.a.example/x/", 200); + assert.equal(ok.availability, "available"); + assert.equal(ok.finalUrl, "https://www.a.example/x/"); + const off = v("https://a.example/x", "https://parked.example/", 200); + assert.equal(off.availability, "error"); + assert.match(off.reason, /redirects to another site \(parked\.example\)/); + const gone = v("https://someone.tumblr.com/post/1", "https://www.tumblr.com/someone", 200, page("There's nothing here.")); + assert.deepEqual([gone.availability, gone.reason], ["deleted", "Tumblr says there's nothing here"]); + const walled = v("https://x.com/a", "https://x.com/a", 403); + assert.deepEqual([walled.availability, walled.status, walled.reason], ["error", 403, "HTTP 403"]); + assert.equal(v("https://a.example/", "https://a.example/", 500).availability, "error"); + // A gone page behind another status still says so. + assert.equal(v("https://docs.google.com/d/1", "https://docs.google.com/d/1", 401, page("You need permission")).availability, "account_unavailable"); +}); + +test("same site: www, http→https, a subdomain of the same domain, two-label suffixes, moved houses", () => { + assert.equal(sameSite("http://blog.example/", "https://www.blog.example/a"), true); + assert.equal(sameSite("https://someone.tumblr.com/", "https://www.tumblr.com/someone"), true); + assert.equal(sameSite("https://twitter.com/a", "https://x.com/a"), true); + assert.equal(sameSite("https://a.example.co.uk/", "https://b.example.co.uk/"), true); + assert.equal(sameSite("https://a.co.uk/", "https://b.co.uk/"), false); + assert.equal(sameSite("https://blog.example/", "https://other.example/"), false); + assert.equal(siteOf("www.news.bbc.co.uk"), "bbc.co.uk"); +}); + +test("records grouped by original URL: one request per URL, whatever a capture split into", () => { + const rec = (id: string, originalUrl?: string) => ({ id, ...(originalUrl ? { page: { originalUrl } } : {}) }); + const g = groupByOriginalUrl([rec("t1", "https://x.com/a"), rec("p1", "https://blog.example/"), rec("t2", "https://x.com/a"), rec("none")]); + assert.deepEqual([...g.entries()], [ + ["https://x.com/a", ["t1", "t2"]], + ["https://blog.example/", ["p1"]], + ]); +}); + +// ─── The request side, over a stub fetch ─── + +type Route = (method: string, url: string) => { status: number; headers?: Record<string, string>; body?: string }; + +function stubPacer(route: Route) { + const sent: string[] = []; + const pacer = new WebPacer( + { + fetch: async (url, init) => { + const method = (init.method ?? "GET").toUpperCase(); + sent.push(`${method} ${url}`); + const r = route(method, url); + return new Response(method === "HEAD" ? null : (r.body ?? ""), { status: r.status, headers: r.headers ?? {} }); + }, + sleep: async () => {}, + }, + { minGapMs: 0, maxAttempts: 2 }, + ); + // Every public name resolves to a public address; nothing is looked up. + return { pacer, sent, opts: { pacer, resolve: async () => ["93.184.216.34"] } }; +} + +test("checkOriginalUrl: a HEAD is enough for a plain page; a refused HEAD is asked again as a GET", async () => { + const live = stubPacer(() => ({ status: 200 })); + assert.equal((await checkOriginalUrl("https://blog.example/a", live.opts)).availability, "available"); + assert.deepEqual(live.sent, ["HEAD https://blog.example/a"]); + + const refused = stubPacer((m) => (m === "HEAD" ? { status: 405 } : { status: 200, body: "<p>hi</p>" })); + const r = await checkOriginalUrl("https://blog.example/a", refused.opts); + assert.equal(r.availability, "available"); + assert.deepEqual(refused.sent, ["HEAD https://blog.example/a", "GET https://blog.example/a"]); + + const gone = stubPacer(() => ({ status: 410 })); + assert.deepEqual( + [(await checkOriginalUrl("https://blog.example/a", gone.opts)).availability, gone.sent.length], + ["deleted", 1], + ); +}); + +test("checkOriginalUrl: redirects followed by hand; a platform with a gone page is read with a GET", async () => { + const s = stubPacer((m, url) => { + if (url === "https://someone.tumblr.com/post/1") return { status: 301, headers: { location: "https://www.tumblr.com/someone/1" } }; + return m === "HEAD" ? { status: 200 } : { status: 200, body: page("There’s nothing here.") }; + }); + const r = await checkOriginalUrl("https://someone.tumblr.com/post/1", s.opts); + assert.deepEqual([r.availability, r.finalUrl, r.reason], ["deleted", "https://www.tumblr.com/someone/1", "Tumblr says there's nothing here"]); + assert.deepEqual(s.sent, [ + "HEAD https://someone.tumblr.com/post/1", + "HEAD https://www.tumblr.com/someone/1", + "GET https://someone.tumblr.com/post/1", + "GET https://www.tumblr.com/someone/1", + ]); + const off = stubPacer((_m, url) => (url.includes("blog.example") ? { status: 302, headers: { location: "https://parked.example/" } } : { status: 200 })); + const o = await checkOriginalUrl("https://blog.example/", off.opts); + assert.equal(o.availability, "error"); + assert.match(o.reason, /another site/); +}); + +test("checkOriginalUrl: an error never reads as deleted — a 403 wall, a 503 that stays, a private address, no answer", async () => { + const wall = stubPacer(() => ({ status: 403 })); + const w = await checkOriginalUrl("https://blog.example/", wall.opts); + assert.deepEqual([w.availability, w.status], ["error", 403]); + assert.equal(wall.sent.length, 2, "HEAD, then GET"); + + const down = stubPacer(() => ({ status: 503 })); + const d = await checkOriginalUrl("https://blog.example/", down.opts); + assert.deepEqual([d.availability, d.status], ["error", 503]); + + const inside = stubPacer(() => ({ status: 200 })); + const p = await checkOriginalUrl("http://127.0.0.1:9/", inside.opts); + assert.equal(p.availability, "error"); + assert.match(p.reason, /private address/); + assert.equal(inside.sent.length, 0); + + const dead = new WebPacer({ fetch: async () => { throw new Error("getaddrinfo ENOTFOUND"); }, sleep: async () => {} }, { minGapMs: 0 }); + const n = await checkOriginalUrl("https://blog.example/", { pacer: dead, resolve: async () => ["93.184.216.34"] }); + assert.deepEqual([n.availability, n.status], ["error", null]); +}); diff --git a/common/lib/waybackPages/liveness.ts b/common/lib/waybackPages/liveness.ts @@ -0,0 +1,227 @@ +// IS THE ORIGINAL STILL UP? (release 37 S5, plans/release-37/wayback-pages.md +// "S5") — the pure half of a page record's availability: what one answer from +// the ORIGINAL URL (never the Wayback Machine) says about it. +// +// available a 2xx, after any redirects that stayed on the same +// site, whose body carries no platform's "gone" page +// deleted 404 or 410, or a platform's "this does not exist" +// page (PAGE_GONE_MARKERS) — the Wayback copy is then +// the only copy +// account_unavailable a platform's "this account is suspended / this +// document is not shared" page: the page is not served, +// and that may reverse +// error anything else (a 403, a 5xx, a redirect to another +// site, no answer), with the status — never a deletion +// reported from ignorance +// +// Pure and client-safe: the request side is ./liveness-server.ts. + +import type { PostAvailability } from "../posts"; + +// One platform's "gone" page: the hosts it applies to and the words it shows. +export type PageGoneMarker = { + // A short name for logs and tests. + id: string; + // The page's host (no "www."), tested against each pattern. + hosts: readonly RegExp[]; + // Matched against the page's text (tags dropped, entities and curly quotes + // folded, whitespace collapsed, lower case). + text: RegExp; + availability: Extract<PostAvailability, "deleted" | "account_unavailable">; + // What the log and the sidecar say. + reason: string; +}; + +const X_HOSTS = [/^(?:mobile\.)?(?:x|twitter)\.com$/]; +const TUMBLR_HOSTS = [/(?:^|\.)tumblr\.com$/]; +const GOOGLE_DOCS_HOSTS = [/^(?:docs|drive)\.google\.com$/]; +const YOUTUBE_HOSTS = [/^(?:m\.)?youtube\.com$/]; + +// THE TABLE (unit-tested in liveness.test.ts). A platform that serves its +// "nothing here" page with a 200 is only told apart by its words; one that +// answers 404 needs no entry (the status says it). +export const PAGE_GONE_MARKERS: readonly PageGoneMarker[] = [ + { + id: "x-no-account", + hosts: X_HOSTS, + text: /this account doesn't exist/, + availability: "deleted", + reason: "X says the account doesn't exist", + }, + { + id: "x-no-page", + hosts: X_HOSTS, + text: /(?:hmm\.\.\.\s*)?this page doesn't exist|sorry, that page doesn't exist/, + availability: "deleted", + reason: "X says the page doesn't exist", + }, + { + id: "x-suspended", + hosts: X_HOSTS, + text: /account suspended/, + availability: "account_unavailable", + reason: "X says the account is suspended", + }, + { + id: "tumblr-nothing-here", + hosts: TUMBLR_HOSTS, + text: /there's nothing here\.?|whatever you were looking for doesn't currently exist at this address/, + availability: "deleted", + reason: "Tumblr says there's nothing here", + }, + { + id: "gdocs-no-file", + hosts: GOOGLE_DOCS_HOSTS, + text: /sorry, the file you have requested does not exist/, + availability: "deleted", + reason: "Google Docs says the file does not exist", + }, + { + id: "gdocs-permission", + hosts: GOOGLE_DOCS_HOSTS, + text: /you need (?:access|permission)/, + availability: "account_unavailable", + reason: "Google Docs says the file is not shared", + }, + { + id: "youtube-no-channel", + hosts: YOUTUBE_HOSTS, + text: /this channel does not exist/, + availability: "deleted", + reason: "YouTube says the channel does not exist", + }, + { + id: "youtube-terminated", + hosts: YOUTUBE_HOSTS, + text: /this account has been terminated/, + availability: "account_unavailable", + reason: "YouTube says the account has been terminated", + }, +]; + +// The host without "www.", lower case; "" for no URL. +export function bareHost(url: string): string { + try { + return new URL(url).hostname.toLowerCase().replace(/^www\./, ""); + } catch { + return ""; + } +} + +// Whether a platform has a "gone" page worth reading the body for. +export function hasGoneMarkers(url: string): boolean { + const host = bareHost(url); + return !!host && PAGE_GONE_MARKERS.some((m) => m.hosts.some((h) => h.test(host))); +} + +// The page's words, folded for matching: tags and scripts dropped, a few +// entities and curly quotes folded, whitespace collapsed, lower case. +export function foldPageText(html: string): string { + return html + .replace(/<(script|style|noscript)\b[^>]*>[\s\S]*?<\/\1>/gi, " ") + .replace(/<[^>]+>/g, " ") + .replace(/&#0*39;|&#x0*27;|&apos;|&rsquo;|&lsquo;|&#8217;|&#x2019;/gi, "'") + .replace(/&nbsp;|&#160;/gi, " ") + .replace(/&amp;/gi, "&") + .replace(/[‘’ʼ]/g, "'") + .replace(/\s+/g, " ") + .trim() + .toLowerCase(); +} + +// The platform's "gone" page this body is, or null. +export function pageGoneMarker(url: string, html: string): PageGoneMarker | null { + const host = bareHost(url); + if (!host || !html) return null; + const text = foldPageText(html); + for (const m of PAGE_GONE_MARKERS) { + if (!m.hosts.some((h) => h.test(host))) continue; + if (m.text.test(text)) return m; + } + return null; +} + +// Two-label public suffixes the "same site" test must not stop at. +const SECOND_LEVEL = /^(?:co|com|net|org|gov|ac|edu|ne|or)\.[a-z]{2}$/; + +// A host's registrable part, roughly: its last two labels, or three under a +// two-label suffix (co.uk, com.au). +// Sites that moved house: a redirect between them stays on the site. +const SITE_ALIASES: Readonly<Record<string, string>> = { "twitter.com": "x.com", "youtu.be": "youtube.com" }; + +export function siteOf(host: string): string { + const labels = host.toLowerCase().replace(/^www\./, "").split(".").filter(Boolean); + const last2 = labels.slice(-2).join("."); + const site = labels.length > 2 && SECOND_LEVEL.test(last2) ? labels.slice(-3).join(".") : last2; + return SITE_ALIASES[site] ?? site; +} + +// Whether a redirect from `a` to `b` stayed on the same site (http→https, +// www, a subdomain of the same registrable domain: tumblr's blog → www). +export function sameSite(a: string, b: string): boolean { + const ha = bareHost(a); + const hb = bareHost(b); + if (!ha || !hb) return false; + return ha === hb || siteOf(ha) === siteOf(hb); +} + +// One check's verdict on an original URL. +export type OriginalCheck = { + url: string; + availability: PostAvailability; + // The final answer's HTTP status (null: no answer). + status: number | null; + // Where the redirects (if any) ended. + finalUrl?: string; + // Why, in a phrase (the marker's reason, the status, the redirect, the + // network error). + reason: string; +}; + +// THE VERDICT on one final answer. `body` is the page's text when it was +// read (a GET), else undefined (a HEAD). +export function classifyOriginalAnswer(a: { + url: string; + finalUrl: string; + status: number; + body?: string; +}): OriginalCheck { + const base = { url: a.url, status: a.status, ...(a.finalUrl !== a.url ? { finalUrl: a.finalUrl } : {}) }; + if (a.status === 404 || a.status === 410) { + return { ...base, availability: "deleted", reason: `HTTP ${a.status}` }; + } + if (a.status >= 200 && a.status < 300) { + if (!sameSite(a.url, a.finalUrl)) { + return { ...base, availability: "error", reason: `redirects to another site (${bareHost(a.finalUrl) || a.finalUrl})` }; + } + const marker = a.body !== undefined ? pageGoneMarker(a.finalUrl, a.body) : null; + if (marker) return { ...base, availability: marker.availability, reason: marker.reason }; + return { ...base, availability: "available", reason: `HTTP ${a.status}` }; + } + // A platform's gone page can come with another status (a 403 wall). + const marker = a.body !== undefined ? pageGoneMarker(a.finalUrl, a.body) : null; + if (marker) return { ...base, availability: marker.availability, reason: `${marker.reason} (HTTP ${a.status})` }; + return { ...base, availability: "error", reason: `HTTP ${a.status}` }; +} + +// A webpage record's ids grouped by the original URL they were captured +// from: one request per distinct URL, whatever number of records a capture +// split into. Order: the order of `records` (first appearance). +export function groupByOriginalUrl( + records: ReadonlyArray<{ id: string; page?: { originalUrl: string } }>, +): Map<string, string[]> { + const out = new Map<string, string[]>(); + for (const r of records) { + const url = r.page?.originalUrl; + if (!url) continue; + const list = out.get(url); + if (list) list.push(r.id); + else out.set(url, [r.id]); + } + return out; +} + +// What a reader is told about a page record whose original is gone (the +// source-gone label's page sentence, lib/sourceGone.ts SOURCE_GONE_LABELS +// for everything else). +export const PAGE_ORIGINAL_GONE_LABEL = "Original gone — the Wayback Machine copy is the only copy"; diff --git a/common/lib/waybackPages/savePageNow-server.ts b/common/lib/waybackPages/savePageNow-server.ts @@ -0,0 +1,63 @@ +// archive.org's S3 KEYS for Save Page Now (release 37 S5), kept the way the +// Claude API key is (lib/llm/anthropic.ts readApiKey): the environment first +// (ARCHIVE_ORG_S3_ACCESS + ARCHIVE_ORG_S3_SECRET, both), else a mode-600 +// file whose PATH is the setting `archiveOrg.s3KeyFile` (two lines +// `ARCHIVE_ORG_S3_ACCESS=…`, `ARCHIVE_ORG_S3_SECRET=…`). A file the group or +// others can read is refused. The keys are never a setting, never logged, +// never in an error, a job record or a result. + +import { readFileSync, statSync } from "node:fs"; +import os from "node:os"; +import { DEFAULT_ARCHIVE_ORG_S3_KEY_FILE } from "../archiveOrgTorrent"; +import { spnOffSentence, type SpnKeys } from "./savePageNow"; + +export type SpnKeysRead = { ok: true; keys: SpnKeys; from: "env" | "file" } | { ok: false; reason: string }; + +const expandHome = (p: string) => (p === "~" || p.startsWith("~/") ? os.homedir() + p.slice(1) : p); + +const unquote = (v: string) => v.trim().replace(/^(["'])(.*)\1$/, "$2").trim(); + +export function readSpnKeys(o: { + keyFile?: string; + env?: Readonly<Record<string, string | undefined>>; +}): SpnKeysRead { + const env = o.env ?? process.env; + const keyFile = o.keyFile?.trim() || DEFAULT_ARCHIVE_ORG_S3_KEY_FILE; + const envAccess = (env.ARCHIVE_ORG_S3_ACCESS ?? "").trim(); + const envSecret = (env.ARCHIVE_ORG_S3_SECRET ?? "").trim(); + if (envAccess && envSecret) return { ok: true, keys: { access: envAccess, secret: envSecret }, from: "env" }; + const file = expandHome(keyFile); + let mode: number; + try { + mode = statSync(file).mode; + } catch { + return { ok: false, reason: spnOffSentence(keyFile) }; + } + if (mode & 0o077) return { ok: false, reason: `${keyFile} is readable by others — chmod 600 it first; Save Page Now is off until then.` }; + let text: string; + try { + text = readFileSync(file, "utf8"); + } catch { + return { ok: false, reason: `${keyFile} could not be read; Save Page Now is off.` }; + } + let access = ""; + let secret = ""; + for (const raw of text.split("\n")) { + const line = raw.trim().replace(/^export\s+/, ""); + if (line.startsWith("ARCHIVE_ORG_S3_ACCESS=")) access = unquote(line.slice("ARCHIVE_ORG_S3_ACCESS=".length)); + if (line.startsWith("ARCHIVE_ORG_S3_SECRET=")) secret = unquote(line.slice("ARCHIVE_ORG_S3_SECRET=".length)); + } + if (!access || !secret) { + return { ok: false, reason: `${keyFile} has no ARCHIVE_ORG_S3_ACCESS= and ARCHIVE_ORG_S3_SECRET= lines; Save Page Now is off.` }; + } + return { ok: true, keys: { access, secret }, from: "file" }; +} + +// Replace the keys wherever they appear in a text: the last line of defence +// for a message that leaves the module. +export function redactSpnKeys(text: string, keys: SpnKeys | undefined): string { + if (!keys) return text; + let out = text; + for (const k of [keys.secret, keys.access]) if (k && k.length >= 4) out = out.split(k).join("[redacted]"); + return out; +} diff --git a/common/lib/waybackPages/savePageNow.ts b/common/lib/waybackPages/savePageNow.ts @@ -0,0 +1,106 @@ +// 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 <access>:<secret> (archive.org's S3 keys) +// Accept: application/json +// url=<page>&capture_outlinks=0 (the page alone) +// → {url, job_id} or {status: "error", status_ext, message} +// GET https://web.archive.org/save/status/<job_id> +// → {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<string, unknown> | null => { + try { + const v = JSON.parse(text) as unknown; + return v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : 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).` + ); +} diff --git a/common/publish/findCopyPages.test.ts b/common/publish/findCopyPages.test.ts @@ -0,0 +1,229 @@ +// Release 37 S5: find-copy's page mode on the fake Wayback — a cited page +// whose original is gone gets the capture nearest its date imported into the +// channel whose targets cover it, and the answer names the record to cite (and +// the citation as a post citation of it); a dry run imports nothing; a live +// page, an uncovered one and one the archive never captured are left with +// their reason; a page already held is not fetched again; a cited page record +// whose original is gone is "held" when its capture is stored, imported again +// when it is not. The original sites are a stub; no network. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test publish/findCopyPages.test.ts + +import test, { after } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { mkdir, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { + startFakeWayback, + PAGE_ARTICLE_LATER_TS, + PAGE_ARTICLE_TS, + PAGE_ARTICLE_URL, + PAGE_TOOLBAR_TS, + PAGE_TOOLBAR_URL, +} from "../testing/web/fakeWayback.mjs"; +import type { Paths } from "../lib/paths"; +import type { Citation } from "../lib/citations/schema"; +import type { ReportHost } from "./reportHost"; +import type { OriginalCheck } from "../lib/waybackPages/liveness"; +import { WaybackClient } from "../lib/waybackClient"; +import { readAllPosts, upsertPosts, writePostAvailability } from "../lib/posts-server"; +import { pageRecordId } from "../lib/waybackPages/types"; +import { importPage } from "../controller/importPage"; +import { captureAtOf, channelsCovering, findPageCopies, pageCitationAsPost, recordForQuote, targetCoversUrl } from "./findCopyPages"; + +const ROOT = mkdtempSync(path.join(tmpdir(), "find-page-copy-")); +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 SETTINGS = { social: { x: { visibility: "private" } } }; +const HOST = { id: "demo-site" } as unknown as ReportHost; +const NOW = new Date("2026-10-20T12:00:00Z"); + +async function pagesChannel(slug: string, target: string, match = "prefix") { + const dir = path.join(paths.channelsDir, slug); + await mkdir(dir, { recursive: true }); + await writeFile( + path.join(dir, "config.json"), + JSON.stringify({ + name: slug, + handling: "transcribe", + sourceKind: "social", + platform: "webpage", + socialHandle: target.split("/")[0], + url: `https://web.archive.org/web/*/${target}*`, + wayback: { targets: [{ url: target, match }] }, + }), + ); + return dir; +} + +const verdict = (url: string, availability: OriginalCheck["availability"], status: number | null): OriginalCheck => ({ + url, + availability, + status, + reason: status ? `HTTP ${status}` : "no answer", +}); + +test("which channel covers a page; the date a citation asks for; the record a quote is from; a page citation as a post", () => { + assert.equal(targetCoversUrl({ url: "blog.example/2014/", match: "prefix" }, "https://www.blog.example/2014/03/a.html"), true); + assert.equal(targetCoversUrl({ url: "blog.example/2015/", match: "prefix" }, "https://blog.example/2014/03/a.html"), false); + assert.equal(targetCoversUrl({ url: "https://blog.example/a", match: "exact" }, "http://blog.example/a/"), true); + assert.equal(targetCoversUrl({ url: "blog.example", match: "host" }, "https://sub.blog.example/"), false); + assert.equal(targetCoversUrl({ url: "blog.example", match: "domain" }, "https://sub.blog.example/"), true); + assert.deepEqual( + channelsCovering( + [ + { slug: "vids", config: { url: "x" } as never }, + { slug: "blog", config: { sourceKind: "social", platform: "webpage", wayback: { targets: [{ url: "blog.example", match: "host" }] } } }, + ], + "https://blog.example/a", + ), + ["blog"], + ); + assert.equal(captureAtOf({ date: "2015-06-01" }, NOW), "20150601"); + assert.equal(captureAtOf({ date: "2015" }, NOW), "2015"); + assert.equal(captureAtOf({ archiveUrl: `https://web.archive.org/web/${PAGE_ARTICLE_TS}/${PAGE_ARTICLE_URL}` }, NOW), PAGE_ARTICLE_TS); + assert.equal(captureAtOf({}, NOW), "20261020"); + assert.equal(recordForQuote([{ id: "a", text: "one thing" }, { id: "b", text: "Another “thing” said" }], 'another "thing"'), "b"); + assert.equal(recordForQuote([{ id: "a", text: "x" }], "not there"), "a"); + assert.deepEqual( + pageCitationAsPost({ kind: "page", url: PAGE_ARTICLE_URL, title: "T", archiveUrl: "https://web.archive.org/web/1/x", quote: "q", label: "L", note: "n" }, { channel: "blog", id: "r1" }), + { kind: "post", channel: "blog", id: "r1", quote: "q", label: "L", note: "n" }, + ); +}); + +test("a gone cited page: dry run names the nearest capture; the run imports it and names the record to cite; again = held", async () => { + const wb = await startFakeWayback(); + try { + const client = new WaybackClient({ fetch: wb.fetch, sleep: async () => {} }, { minGapMs: 0 }); + const dir = await pagesChannel("old-blog", "blog.example/"); + const citations: Record<string, Citation> = { + c1: { kind: "page", url: PAGE_ARTICLE_URL, date: "2015-06", quote: "Update: the fourth loaf rose.", label: "The post" }, + c2: { kind: "page", url: "https://live.example/up", quote: "still here" }, + c3: { kind: "page", url: "https://elsewhere.example/gone", quote: "nobody covers this" }, + c4: { kind: "page", url: "https://blog.example/never-captured.html", quote: "never captured" }, + c5: { kind: "video", channel: "v", id: "abc", start: 1, end: 2, quote: "a video" }, + }; + const reports = [ + { id: "r1", citations }, + { id: "r2", citations: { x1: { kind: "page", url: PAGE_ARTICLE_URL, quote: "The first loaf came out flat" } as Citation } }, + ]; + const checks = new Map<string, OriginalCheck>([ + [PAGE_ARTICLE_URL, verdict(PAGE_ARTICLE_URL, "deleted", 404)], + ["https://live.example/up", verdict("https://live.example/up", "available", 200)], + ["https://elsewhere.example/gone", verdict("https://elsewhere.example/gone", "deleted", 410)], + ["https://blog.example/never-captured.html", verdict("https://blog.example/never-captured.html", "deleted", 404)], + ]); + const asked: string[] = []; + const deps = { + reports: async () => reports, + check: async (url: string) => { + asked.push(url); + return checks.get(url) ?? verdict(url, "error", null); + }, + nearest: (url: string, at: string) => client.closestCapture(url, at), + importCapture: (o: { slug: string; url: string }) => importPage({ paths, slug: o.slug, url: o.url, client, settings: SETTINGS }), + now: () => NOW, + }; + const lines: string[] = []; + const dry = await findPageCopies({ paths, host: HOST, dryRun: true, deps, onLog: (l) => lines.push(l) }); + assert.deepEqual([dry.pages, dry.posts], [4, 0]); + const byUrl = (r: typeof dry) => new Map(r.items.map((i) => [i.url, i])); + const d = byUrl(dry); + assert.equal(d.get(PAGE_ARTICLE_URL)!.outcome, "would-import"); + assert.equal(d.get(PAGE_ARTICLE_URL)!.capture!.timestamp, PAGE_ARTICLE_LATER_TS, "the capture nearest 2015-06"); + assert.deepEqual(d.get(PAGE_ARTICLE_URL)!.citedBy, ["r1#c1", "r2#x1"]); + assert.equal(d.get("https://live.example/up")!.outcome, "live"); + assert.equal(d.get("https://elsewhere.example/gone")!.outcome, "no-channel"); + assert.equal(d.get("https://blog.example/never-captured.html")!.outcome, "none-found"); + assert.deepEqual(await readAllPosts(dir), [], "a dry run imports nothing"); + assert.ok(lines.some((l) => /1 capture\(s\) would be imported \(dry run: nothing imported\)/.test(l))); + + const run = await findPageCopies({ paths, host: HOST, deps }); + const item = byUrl(run).get(PAGE_ARTICLE_URL)!; + const id = pageRecordId(PAGE_ARTICLE_LATER_TS, PAGE_ARTICLE_URL); + assert.equal(item.outcome, "imported", item.detail); + assert.deepEqual(item.pointTo, { channel: "old-blog", id }); + assert.deepEqual(item.as, { kind: "post", channel: "old-blog", id, date: "2015-06", quote: "Update: the fourth loaf rose.", label: "The post" }); + assert.deepEqual((await readAllPosts(dir)).map((p) => p.id), [id]); + + // Again: the channel holds the page — nothing fetched. + const before = wb.requests.length; + const again = await findPageCopies({ paths, host: HOST, deps }); + assert.equal(byUrl(again).get(PAGE_ARTICLE_URL)!.outcome, "held"); + assert.deepEqual(byUrl(again).get(PAGE_ARTICLE_URL)!.pointTo, { channel: "old-blog", id }); + assert.equal(wb.requests.length - before, 1, "only the never-captured page's CDX lookup"); + + // `max` leaves the rest for a later run. + const capped = await findPageCopies({ paths, host: HOST, deps, max: 1, dryRun: true }); + assert.deepEqual([capped.items.length, capped.left], [1, 3]); + + // A named channel that is not a pages channel is refused. + await assert.rejects(findPageCopies({ paths, host: HOST, deps, channel: "nope" }), /not a Wayback pages channel/); + } finally { + await wb.close(); + } +}); + +test("a cited page record whose original is gone: held when its capture is stored, imported again when it is not", async () => { + const wb = await startFakeWayback(); + try { + const client = new WaybackClient({ fetch: wb.fetch, sleep: async () => {} }, { minGapMs: 0 }); + const dir = await pagesChannel("home-site", "home.example/"); + // One record whose capture is stored (imported), one whose is not (its + // record written alone). + const imp = await importPage({ paths, slug: "home-site", url: `https://web.archive.org/web/${PAGE_TOOLBAR_TS}/${PAGE_TOOLBAR_URL}`, client, settings: SETTINGS }); + assert.equal(imp.ok, true, imp.error); + const stored = imp.records![0]!; + const loose = (await readAllPosts(dir))[0]!; + const looseUrl = "https://home.example/links"; + const looseTs = "20150101000000"; + const looseId = pageRecordId(looseTs, looseUrl); + await upsertPosts(dir, [ + { + ...loose, + id: looseId, + slug: `home-site/${looseId}`, + url: looseUrl, + page: { ...loose.page!, originalUrl: looseUrl, captureTs: looseTs, waybackUrl: `https://web.archive.org/web/${looseTs}/${looseUrl}`, rawUrl: `https://web.archive.org/web/${looseTs}id_/${looseUrl}` }, + }, + ]); + await writePostAvailability(dir, { + [stored]: { availability: "deleted", checkedAt: "2026-10-19T00:00:00Z", status: 404, reason: "HTTP 404" }, + [looseId]: { availability: "deleted", checkedAt: "2026-10-19T00:00:00Z", status: 404, reason: "HTTP 404" }, + }); + const imported: string[] = []; + const deps = { + reports: async () => [ + { + id: "r9", + citations: { + a: { kind: "post", channel: "home-site", id: stored, quote: "zines" } as Citation, + b: { kind: "post", channel: "home-site", id: looseId, quote: "links" } as Citation, + c: { kind: "post", channel: "not-a-pages-channel", id: "1", quote: "x" } as Citation, + }, + }, + ], + check: async (url: string) => verdict(url, "error", null), + nearest: (url: string, at: string) => client.closestCapture(url, at), + importCapture: async (o: { slug: string; url: string }) => { + imported.push(o.url); + return { ok: true, slug: o.slug, url: o.url, written: 0, updated: 0, unchanged: 1, records: [looseId] }; + }, + now: () => NOW, + }; + const dry = await findPageCopies({ paths, host: HOST, dryRun: true, deps }); + assert.equal(dry.posts, 2); + const of = (r: typeof dry, id: string) => r.items.find((i) => i.record?.id === id)!; + assert.equal(of(dry, stored).outcome, "held"); + assert.equal(of(dry, looseId).outcome, "would-import"); + assert.deepEqual(imported, []); + const run = await findPageCopies({ paths, host: HOST, deps }); + assert.equal(of(run, looseId).outcome, "imported"); + assert.deepEqual(imported, [`https://web.archive.org/web/${looseTs}/${looseUrl}`]); + assert.deepEqual(of(run, stored).pointTo, { channel: "home-site", id: stored }); + } finally { + await wb.close(); + } +}); diff --git a/common/publish/findCopyPages.ts b/common/publish/findCopyPages.ts @@ -0,0 +1,420 @@ +// FIND A COPY OF A GONE PAGE A REPORT CITES (release 37 S5) — find-copy's +// page mode, beside its video modes (./findCopy.ts). A report cites a web page +// either as a `page` citation (`{url, archiveUrl?}`: the page is not in the +// corpus) or as a `post` citation of a page record (a Wayback Machine capture +// already imported into a Wayback pages channel). When the page's ORIGINAL is +// gone, the Wayback Machine's copy is the only copy, and the report should +// cite it as a record: +// +// a `page` citation its original URL asked at its own site +// (lib/waybackPages/liveness-server.ts, the web pacer); +// gone (deleted, or the account/document unavailable) → +// the capture NEAREST the citation's date (its `date`, +// else its archiveUrl's timestamp, else today: the latest) +// through ONE CDX request (WaybackClient.closestCapture), +// imported into the Wayback pages channel named +// (`channel`) or the one whose targets cover the URL +// (import-page, controller/importPage.ts) — unless that +// channel already holds a record of the page. Live: left +// (Save Page Now is the act for a live page). The answer +// names the record the citation should cite (`pointTo`) +// and the citation as a `post` citation of it (`as`). +// a `post` citation of a page record whose original the availability +// check found deleted: its capture is held (nothing to +// do) or, when its raw body is not stored, imported again. +// +// THE CITATION IS NOT REWRITTEN HERE: `pointTo`/`as` are what the report's +// citation becomes (the report editor's "Import this capture" rewrites a page +// citation to a post citation and keeps the page citation as its fallback; +// release 37 lane D). A dry run asks the same paced questions and imports +// nothing. +// +// PACED: one page at a time, at most `max` lookups per run; every Wayback +// request goes through the process's Wayback client (one stream, 2 s apart, +// 429s waited out — a refusal stops the run there), every original-site +// request through the web pacer. The job runs on the archive.org queue. + +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import type { Citation, PageCitation, PostCitation } from "../lib/citations/schema"; +import type { Post } from "../lib/posts"; +import { readAllPosts, readPostAvailability } from "../lib/posts-server"; +import { listChannelConfigs } from "../controller/channels"; +import { isWaybackPagesChannel, type WaybackTarget } from "../lib/waybackPages/config"; +import { bareHost, type OriginalCheck } from "../lib/waybackPages/liveness"; +import { checkOriginalUrl, type CheckOriginalOptions } from "../lib/waybackPages/liveness-server"; +import { hasStoredCapture } from "../lib/waybackPages/store-server"; +import { parseWaybackUrl, waybackPageUrl } from "../lib/wayback"; +import { ArchiveOrgRequestError } from "../lib/archiveOrgClient"; +import { waybackClient, type WaybackCapture, type WaybackClient } from "../lib/waybackClient"; +import { importPage, type ImportPageResult } from "../controller/importPage"; +import { loadHostReports } from "./reportMedia"; +import type { ReportHost } from "./reportHost"; + +export const FIND_PAGE_COPY_DEFAULT_MAX = 10; +export const FIND_PAGE_COPY_MAX_LIMIT = 100; + +// ─── Which channel a page belongs in ─── + +const bare = (u: string) => + u + .trim() + .replace(/^https?:\/\//i, "") + .replace(/^www\./i, "") + .replace(/#.*$/, "") + .replace(/\/+$/, "") + .toLowerCase(); + +// Whether a Wayback pages channel's target covers a page. +export function targetCoversUrl(target: Pick<WaybackTarget, "url" | "match">, url: string): boolean { + const host = bareHost(/^https?:\/\//i.test(url) ? url : `https://${url}`); + const targetHost = bareHost(/^https?:\/\//i.test(target.url) ? target.url : `https://${target.url}`); + if (!host || !targetHost) return false; + switch (target.match) { + case "exact": + return bare(url) === bare(target.url); + case "prefix": + return bare(url).startsWith(bare(target.url)); + case "host": + return host === targetHost; + case "domain": + return host === targetHost || host.endsWith(`.${targetHost}`); + default: + return false; + } +} + +// The Wayback pages channels whose targets cover `url`, by slug. +export function channelsCovering( + channels: ReadonlyArray<{ slug: string; config: { sourceKind?: string; platform?: string; wayback?: { targets?: WaybackTarget[] } } }>, + url: string, +): string[] { + return channels + .filter((c) => isWaybackPagesChannel(c.config) && (c.config.wayback?.targets ?? []).some((t) => targetCoversUrl(t, url))) + .map((c) => c.slug); +} + +// ─── What the reports cite ─── + +export type CitedPage = { + // `<report>#<citation id>` of each citation of it. + citedBy: string[]; + url: string; + // The citation's own date or archive copy, for the nearest capture. + at?: string; + // The first citation's words (to pick the record of a split capture). + quote: string; + citation: PageCitation; +}; + +export type CitedPageRecord = { + citedBy: string[]; + channel: string; + id: string; +}; + +// "2014-03-05…" / "2014-03" / "2014" → a capture time prefix. +export function captureAtOf(c: Pick<PageCitation, "date" | "archiveUrl">, today: Date): string { + const d = /^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?/.exec(c.date ?? ""); + if (d) return `${d[1]}${d[2] ?? ""}${d[3] ?? ""}`; + const ref = parseWaybackUrl(c.archiveUrl ?? ""); + if (ref && /^\d{4,14}$/.test(ref.captureTs)) return ref.captureTs; + return today.toISOString().slice(0, 10).replaceAll("-", ""); +} + +export function citedPages( + reports: ReadonlyArray<{ id: string; citations?: Record<string, Citation> }>, + today: Date, +): { pages: CitedPage[]; posts: CitedPageRecord[] } { + const pages = new Map<string, CitedPage>(); + const posts = new Map<string, CitedPageRecord>(); + for (const r of reports) { + for (const [cid, c] of Object.entries(r.citations ?? {})) { + const by = `${r.id}#${cid}`; + if (c.kind === "page") { + if (!/^https?:\/\//i.test(c.url)) continue; + const key = bare(c.url); + const seen = pages.get(key); + if (seen) seen.citedBy.push(by); + else pages.set(key, { citedBy: [by], url: c.url.trim(), at: captureAtOf(c, today), quote: c.quote, citation: c }); + } else if (c.kind === "post") { + const key = `${c.channel}/${c.id}`; + const seen = posts.get(key); + if (seen) seen.citedBy.push(by); + else posts.set(key, { citedBy: [by], channel: c.channel, id: c.id }); + } + } + } + return { pages: [...pages.values()], posts: [...posts.values()] }; +} + +// The record a quote is from, among a capture's records: the one whose text +// holds the quote's words, else the first (a whole page's one record). +export function recordForQuote(records: ReadonlyArray<Pick<Post, "id" | "text">>, quote: string): string | null { + if (records.length === 0) return null; + const fold = (s: string) => s.replace(/[‘’]/g, "'").replace(/[“”]/g, '"').replace(/\s+/g, " ").trim().toLowerCase(); + const q = fold(quote); + if (q) { + const hit = records.find((r) => fold(r.text).includes(q)); + if (hit) return hit.id; + } + return records[0]!.id; +} + +// A page citation as a post citation of the record: its words and editorial +// fields kept; the record carries the URL, the title and the Wayback copy. +export function pageCitationAsPost(c: PageCitation, pointTo: { channel: string; id: string }): PostCitation { + const { kind: _kind, url: _url, title: _title, archiveUrl: _archive, ...common } = c; + return { kind: "post", channel: pointTo.channel, id: pointTo.id, ...common }; +} + +// ─── find-copy, page mode ─── + +export type FindPageCopyOutcome = + // imported the nearest capture imported; `pointTo` is its record + // would-import (dry run) what an import would fetch + // held the channel already holds a record of the page (or the + // cited record's capture is stored): nothing fetched + // live the original still answers: left (Save Page Now it) + // none-found the Wayback Machine holds no capture that recorded a page + // no-channel no Wayback pages channel covers the URL and none was named + // refused the import was refused (its sentence: X, a video, …) + // error a check or a lookup failed: a later run asks again + | "imported" + | "would-import" + | "held" + | "live" + | "none-found" + | "no-channel" + | "refused" + | "error"; + +export type FindPageCopyItem = { + citedBy: string[]; + // The page cited, or the record cited. + url: string; + record?: { channel: string; id: string }; + original?: Pick<OriginalCheck, "availability" | "status" | "reason">; + channel?: string; + capture?: { timestamp: string; original: string; waybackUrl: string }; + outcome: FindPageCopyOutcome; + detail: string; + pointTo?: { channel: string; id: string }; + // The citation as a post citation of `pointTo` (a page citation only). + as?: PostCitation; + records?: string[]; +}; + +export type FindPageCopiesResult = { + host: string; + dryRun: boolean; + max: number; + pages: number; + posts: number; + items: FindPageCopyItem[]; + // Cited pages left for a later run by `max`. + left: number; + stopped?: string; +}; + +export type FindPageCopiesDeps = { + reports: (host: ReportHost) => Promise<ReadonlyArray<{ id: string; citations?: Record<string, Citation> }>>; + channels: (paths: Paths) => Promise<Array<{ slug: string; config: { sourceKind?: string; platform?: string; wayback?: { targets?: WaybackTarget[] } } }>>; + check: (url: string, signal?: AbortSignal) => Promise<OriginalCheck>; + // THE ONE CAPTURE LOOKUP: the capture of `url` nearest `at` (default: the + // Wayback Machine's CDX `closest`). An archive-source registry can stand in + // here without the rest of the mode changing. + nearest: (url: string, at: string, signal?: AbortSignal) => Promise<WaybackCapture | null>; + importCapture: (o: { slug: string; url: string; signal?: AbortSignal; onLog?: (line: string) => void }) => Promise<ImportPageResult>; + now: () => Date; +}; + +export function defaultFindPageCopiesDeps(paths: Paths, o: { check?: CheckOriginalOptions; client?: WaybackClient } = {}): FindPageCopiesDeps { + const client = o.client ?? waybackClient; + return { + reports: async (host) => (await loadHostReports(host)).reports, + channels: (p) => listChannelConfigs(p), + check: (url, signal) => checkOriginalUrl(url, { ...o.check, ...(signal ? { signal } : {}) }), + nearest: (url, at, signal) => client.closestCapture(url, at, signal ? { signal } : {}), + importCapture: (io) => importPage({ paths, slug: io.slug, url: io.url, client, ...(io.signal ? { signal: io.signal } : {}), ...(io.onLog ? { onLog: io.onLog } : {}) }), + now: () => new Date(), + }; +} + +const GONE = new Set(["deleted", "account_unavailable"]); + +export async function findPageCopies(opts: { + paths: Paths; + host: ReportHost; + // The Wayback pages channel every capture goes to (else: the one whose + // targets cover the page). + channel?: string; + dryRun?: boolean; + max?: number; + signal?: AbortSignal; + onLog?: (line: string) => void; + deps?: Partial<FindPageCopiesDeps>; +}): Promise<FindPageCopiesResult> { + const deps: FindPageCopiesDeps = { ...defaultFindPageCopiesDeps(opts.paths), ...opts.deps }; + const log = (line: string) => opts.onLog?.(line); + const signal = opts.signal; + const dryRun = opts.dryRun === true; + const max = Math.min(FIND_PAGE_COPY_MAX_LIMIT, Math.max(1, Math.floor(opts.max ?? FIND_PAGE_COPY_DEFAULT_MAX))); + const today = deps.now(); + const cited = citedPages(await deps.reports(opts.host), today); + const channels = await deps.channels(opts.paths); + const pagesChannels = new Set(channels.filter((c) => isWaybackPagesChannel(c.config)).map((c) => c.slug)); + if (opts.channel && !pagesChannels.has(opts.channel)) { + throw new Error(`${opts.channel} is not a Wayback pages channel; name one on platform "webpage", or none (the channel whose targets cover each page)`); + } + // The post citations of page records only. + const postCitations = cited.posts.filter((p) => pagesChannels.has(p.channel)); + const result: FindPageCopiesResult = { host: opts.host.id, dryRun, max, pages: cited.pages.length, posts: postCitations.length, items: [], left: 0 }; + log( + `find-copy ${opts.host.id} (pages${dryRun ? ", dry run" : ""}): ${cited.pages.length} cited page(s), ` + + `${postCitations.length} cited page record(s); at most ${max} looked up.`, + ); + const recordsOf = new Map<string, Post[]>(); + const channelRecords = async (slug: string): Promise<Post[]> => { + let list = recordsOf.get(slug); + if (!list) { + list = (await readAllPosts(path.join(opts.paths.channelsDir, slug)).catch(() => [] as Post[])).filter((p) => p.page); + recordsOf.set(slug, list); + } + return list; + }; + + let lookups = 0; + const stopOn = (e: unknown): string | null => + e instanceof ArchiveOrgRequestError && e.rateLimited ? `archive.org kept refusing (${e.message}); the rest are left for a later run` : null; + + // 1. Cited pages. + for (const page of cited.pages) { + if (signal?.aborted || result.stopped) break; + if (lookups >= max) { + result.left++; + continue; + } + lookups++; + const item: FindPageCopyItem = { citedBy: page.citedBy, url: page.url, outcome: "error", detail: "" }; + result.items.push(item); + const checked = await deps.check(page.url, signal); + item.original = { availability: checked.availability, status: checked.status, reason: checked.reason }; + if (checked.availability === "available") { + item.outcome = "live"; + item.detail = `the original still answers (${checked.reason}): left — Save Page Now captures a live page`; + } else if (!GONE.has(checked.availability)) { + item.outcome = "error"; + item.detail = `the original could not be checked (${checked.reason}): try again later`; + } else { + const covering = opts.channel ? [opts.channel] : channelsCovering(channels, page.url); + const slug = covering[0]; + if (!slug) { + item.outcome = "no-channel"; + item.detail = `the original is gone (${checked.reason}), and no Wayback pages channel covers ${bareHost(page.url) || page.url}: name one ("channel") or create one targeting it`; + } else { + item.channel = slug; + const held = (await channelRecords(slug)).filter((r) => bare(r.page!.originalUrl) === bare(page.url)); + if (held.length > 0) { + const id = recordForQuote(held, page.quote)!; + item.outcome = "held"; + item.pointTo = { channel: slug, id }; + item.as = pageCitationAsPost(page.citation, item.pointTo); + item.detail = `the original is gone (${checked.reason}); ${slug} already holds ${held.length} record(s) of the page`; + } else { + try { + const near: WaybackCapture | null = await deps.nearest(page.url, page.at ?? "", signal); + if (!near) { + item.outcome = "none-found"; + item.detail = `the original is gone (${checked.reason}), and the Wayback Machine holds no capture of it that recorded a page`; + } else { + const waybackUrl = waybackPageUrl({ captureTs: near.timestamp, originalUrl: near.original }); + item.capture = { timestamp: near.timestamp, original: near.original, waybackUrl }; + if (dryRun) { + item.outcome = "would-import"; + item.detail = `the original is gone (${checked.reason}); would import the capture ${near.timestamp} (nearest ${page.at}) into ${slug}`; + } else { + const imp = await deps.importCapture({ slug, url: waybackUrl, ...(signal ? { signal } : {}), onLog: (l) => log(` ${l}`) }); + if (!imp.ok) { + // archive.org kept refusing (the client's sentence): stop the run there. + const busy = /did not answer .* attempts/.test(imp.error ?? ""); + item.outcome = busy ? "error" : "refused"; + item.detail = busy ? (imp.error ?? "") : `the import was refused: ${imp.error}`; + if (busy) result.stopped = `archive.org kept refusing (${imp.error}); the rest are left for a later run`; + } else { + recordsOf.delete(slug); + const records = (await channelRecords(slug)).filter((r) => (imp.records ?? []).includes(r.id)); + const id = recordForQuote(records.length ? records : (imp.records ?? []).map((rid) => ({ id: rid, text: "" })), page.quote); + item.outcome = "imported"; + item.records = imp.records ?? []; + if (id) { + item.pointTo = { channel: slug, id }; + item.as = pageCitationAsPost(page.citation, item.pointTo); + } + item.detail = `the original is gone (${checked.reason}); ${imp.already ? "the capture was already stored" : "imported"} the capture ${imp.captureTs} into ${slug}`; + } + } + } + } catch (e) { + if (signal?.aborted) break; + item.outcome = "error"; + item.detail = (e as Error).message; + const stop = stopOn(e); + if (stop) result.stopped = stop; + } + } + } + } + log(` ${page.url} (${page.citedBy.join(", ")}): ${item.outcome} — ${item.detail}${item.pointTo ? ` → cite ${item.pointTo.channel}/${item.pointTo.id}` : ""}`); + } + + // 2. Cited page records whose original the availability check found gone. + for (const cite of postCitations) { + if (signal?.aborted || result.stopped) break; + const channelRoot = path.join(opts.paths.channelsDir, cite.channel); + const av = (await readPostAvailability(channelRoot))[cite.id]; + if (!av || !GONE.has(av.availability)) continue; + const record = (await channelRecords(cite.channel)).find((r) => r.id === cite.id); + if (!record?.page) continue; + const item: FindPageCopyItem = { + citedBy: cite.citedBy, + url: record.page.originalUrl, + record: { channel: cite.channel, id: cite.id }, + original: { availability: av.availability, status: av.status ?? null, reason: av.reason ?? "the availability check" }, + channel: cite.channel, + capture: { timestamp: record.page.captureTs, original: record.page.originalUrl, waybackUrl: record.page.waybackUrl }, + outcome: "held", + detail: "", + pointTo: { channel: cite.channel, id: cite.id }, + }; + result.items.push(item); + if (await hasStoredCapture(channelRoot, record.page.captureTs, record.page.originalUrl)) { + item.detail = `the original is gone (${item.original!.reason}); the record's capture is held — the Wayback copy is the only copy`; + } else if (dryRun) { + item.outcome = "would-import"; + item.detail = `the original is gone; the record's capture is not stored: would import ${record.page.waybackUrl} into ${cite.channel}`; + } else { + try { + const imp = await deps.importCapture({ slug: cite.channel, url: record.page.waybackUrl, ...(signal ? { signal } : {}), onLog: (l) => log(` ${l}`) }); + item.outcome = imp.ok ? "imported" : "refused"; + item.records = imp.records ?? []; + item.detail = imp.ok ? `the original is gone; the record's capture imported again into ${cite.channel}` : `the import was refused: ${imp.error}`; + } catch (e) { + if (signal?.aborted) break; + item.outcome = "error"; + item.detail = (e as Error).message; + const stop = stopOn(e); + if (stop) result.stopped = stop; + } + } + log(` ${cite.channel}/${cite.id} (${cite.citedBy.join(", ")}): ${item.outcome} — ${item.detail}`); + } + + if (signal?.aborted && !result.stopped) result.stopped = "cancelled; the rest are left for a later run"; + if (result.stopped) log(`find-copy: ${result.stopped}.`); + if (result.left > 0) log(`find-copy: ${result.left} more cited page(s) are left for a later run (max ${max}).`); + const imported = result.items.filter((i) => i.outcome === "imported").length; + const would = result.items.filter((i) => i.outcome === "would-import").length; + log(`find-copy: ${dryRun ? `${would} capture(s) would be imported (dry run: nothing imported)` : `${imported} capture(s) imported`}.`); + return result; +} diff --git a/common/testing/README.md b/common/testing/README.md @@ -23,7 +23,7 @@ transcript, channel or person goes in these fixtures, ever. | `draft/manifests/full`, `flips` | Release 28: every media field a draft task writes, as the build accepts it today — per-entry `onscreen`, a narrated card, a teaser, `claim` verdicts, `render.chrome.threads` with a `thread` per clip (`full`), or `render.chrome.flips` (`flips`: one THEN/NOW pair over clips of different dates). Hand-written, not derived; `umtool/report-to-video/fixtures-r28.test.mjs` keeps them lint-clean. | | `draft/reports/ruled.report.json` | Release 28: a synthetic fact-check whose claims carry verdicts standing for operator rulings — every verdict at least once, each cited quote a cue of the corpus. The verdict bench's tests read it. | | `social/fakeBluesky.mjs` | Release 29: a fake Bluesky on loopback — the public AppView (`resolveHandle`, `getPosts` answering only live posts, images as `embed.images[].fullsize`), a bsky.app-shaped post page (`pageUrl(handle, rkey)`: the post in `[data-testid="postThreadItem-by-<handle>"]` inside page chrome, "Post not found" for a deleted one) for a headless screenshot, and PNG images. `bsky.fetch` sends `https://public.api.bsky.app`, `https://bsky.app` and `https://cdn.bsky.app` to it; `busyTimes` answers 429 first. | -| `web/fakeWayback.mjs` | Release 29: a fake Wayback Machine — the CDX API (`/cdx/search/cdx`, `output=json` with its header row, `[]` for none, `filter=statuscode:`, `limit`, `matchType=prefix`) and capture pages (`/web/<ts>[id_]/<url>`). `wb.fetch` sends `https://web.archive.org` to it; `busyTimes` 429s, `downTimes` 503s. Release 32 R8: a format's stream at `/web/<ts>id_/<googlevideo url>` (yt-dlp's `2id_` form) serves bytes (206 for a Range) for an id in `streams` (default `videos`), else 404 — `videos` without `streams` is the live "page captured, no video" case; `streamBusyTimes` 429s. Release 37 (lane A): PAGE captures served raw (`PAGE_CAPTURES`, `opts.pageCaptures`) — an article with nav/header/footer around an `<article>` (two captures), a body still carrying the toolbar insert and rewritten hrefs, a 3 MB page, a `text/plain` and an `image/jpeg` capture, and one that redirects off the archive; a timestamp with no capture of a known page answers 302 to the nearest; CDX honours `closest=`. | +| `web/fakeWayback.mjs` | Release 29: a fake Wayback Machine — the CDX API (`/cdx/search/cdx`, `output=json` with its header row, `[]` for none, `filter=statuscode:`, `limit`, `matchType=prefix`) and capture pages (`/web/<ts>[id_]/<url>`). `wb.fetch` sends `https://web.archive.org` to it; `busyTimes` 429s, `downTimes` 503s. Release 32 R8: a format's stream at `/web/<ts>id_/<googlevideo url>` (yt-dlp's `2id_` form) serves bytes (206 for a Range) for an id in `streams` (default `videos`), else 404 — `videos` without `streams` is the live "page captured, no video" case; `streamBusyTimes` 429s. Release 37 (lane A): PAGE captures served raw (`PAGE_CAPTURES`, `opts.pageCaptures`) — an article with nav/header/footer around an `<article>` (two captures), a body still carrying the toolbar insert and rewritten hrefs, a 3 MB page, a `text/plain` and an `image/jpeg` capture, and one that redirects off the archive; a timestamp with no capture of a known page answers 302 to the nearest; CDX honours `closest=`. Release 37 (lane E): Save Page Now — `POST /save` (the fake keys `FAKE_SPN_ACCESS`/`FAKE_SPN_SECRET` in `Authorization: LOW …`, else 401; `spn.busyTimes` 429s; `spn.refuseUrls` answered `error:blocked-url`) and `GET /save/status/<job>` (`spn.pendingPolls` pending, then success at `SPN_CAPTURE_TS`, or `spn.failUrls` → `error:not-found`); a saved page is then served raw like a page capture (`spn.pages[url]` or a synthetic page); `wb.spnForms`, `wb.spnCaptures`. | | `web/fakeRangedCdn.mjs` | Release 32 R7: a fake media CDN shaped like Odysee's `player.odycdn.com` — ranged GETs with a Referer answer 206 (`Content-Range`), unranged 429, no Referer 403, past the end 416; `refuseAfterBytes` (429/403 once a budget is served), `corruptOnce`, `ignoreRange`, `requireUnlock` + `unlockBytes` (served only after `cdn.unlock()` — a player's page open — lapsing after a budget; `cdn.lock()` takes it back). Release 32 R10: `dropAfterBytes` / `drops` / `dropGapBytes` cut the connection mid-body (undici's body read throws) or before any response (the fetch throws `fetch failed`); a cut request is `dropped: true`. `cdn.fetch` sends `https://player.odycdn.com` to it. | | `draft/corpus.mjs` `GONE_RECORD`, `GONE_AVAILABILITY` | Release 29: a recording deleted on its platform (`state: "deleted"`, cues kept; add it with `withRecords`) and the `availability.json` it carries on disk. The fake Wayback has one capture of its watch page. | | `audio/corruptAudio.mjs` | Release 30 lane Q: damaged audio for the salvage and refetch tests — `makeToneFile` (an AAC-in-MP4 tone-burst recording: a 0.3 s burst every 4 s, the bursts being the clock), `corruptBytes` (the same with a seeded run of its bytes overwritten: the frames there fail to decode, their timestamps survive), `readWavMono16`, `toneOnsets` (burst onsets in decoded samples), `burstTimes`, `hasFfmpeg`. Needs ffmpeg; the tests that use it skip without. | diff --git a/common/testing/web/fakeWayback.d.mts b/common/testing/web/fakeWayback.d.mts @@ -27,9 +27,17 @@ export const PAGE_JUMP_URL: string; export const PAGE_JUMP_TS: string; export const VIDEOS: string[]; +// Release 37 (lane E): Save Page Now. +export const FAKE_SPN_ACCESS: string; +export const FAKE_SPN_SECRET: string; +export const SPN_CAPTURE_TS: string; + export type FakeWayback = { base: string; - requests: { path: string; at: number }[]; + requests: { path: string; at: number; method?: string }[]; + // (release 37 lane E) the SPN forms posted, and the captures SPN made. + spnForms: Record<string, string>[]; + spnCaptures: FakePageCapture[]; fetch(url: string | URL, init?: RequestInit): Promise<Response>; close(): Promise<void>; }; @@ -46,6 +54,19 @@ export function startFakeWayback(opts?: { pageCaptures?: FakePageCapture[]; // (release 37 S2) the Nth scan listing request and every one after answer 503. scanRefuseFrom?: number; + // (release 37 lane E) Save Page Now: the keys it takes, 429s first, polls + // answered pending, URLs whose capture fails or is refused, bodies by URL, + // the capture timestamp. + spn?: { + access?: string; + secret?: string; + busyTimes?: number; + pendingPolls?: number; + failUrls?: string[]; + refuseUrls?: string[]; + pages?: Record<string, string>; + timestamp?: string; + }; }): Promise<FakeWayback>; // (release 37 S2) the scan listing: a blog with posts, assets, a 404, a second host. diff --git a/common/testing/web/fakeWayback.mjs b/common/testing/web/fakeWayback.mjs @@ -174,6 +174,88 @@ function pageCaptureAnswer(pageCaptures, ts, mod, original, send, res) { return true; } +// ─── Release 37 (lane E): Save Page Now (SPN2) ────────────────────────────── +// +// POST /save url=<page>&capture_outlinks=0, Authorization +// `LOW <access>:<secret>` → {url, job_id}; a wrong +// or missing key → 401; opts.spn.busyTimes → 429 +// (Retry-After: 1) first; a url in opts.spn.refuseUrls +// → 200 {status: "error", status_ext: "error:blocked-url"} +// GET /save/status/<job_id> {status: "pending"} for opts.spn.pendingPolls polls +// (default 1), then {status: "success", timestamp, +// original_url} — and the capture is served raw like a +// page capture from then on (opts.spn.pages[url] or a +// synthetic page) — or, for a url in opts.spn.failUrls, +// {status: "error", status_ext: "error:not-found"} +// The keys are FAKE_SPN_ACCESS / FAKE_SPN_SECRET; nothing real. +export const FAKE_SPN_ACCESS = "FAKEACCESS0001"; +export const FAKE_SPN_SECRET = "FAKESECRET0001"; +export const SPN_CAPTURE_TS = "20261020120000"; + +const spnPageHtml = (url) => `<!doctype html><html lang="en"><head><meta charset="utf-8"> +<title>A page saved now</title></head><body> +<nav><a href="/">Home</a></nav> +<main><h1>A page saved now</h1> +<p>This synthetic page stands for ${url}, captured by the fake Save Page Now while it was still up.</p> +<p>It says what the page said on the day it was saved, which is the point of saving it.</p></main> +<footer>Footer</footer></body></html>`; + +function readBody(req) { + return new Promise((resolve) => { + const chunks = []; + req.on("data", (c) => chunks.push(c)); + req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8"))); + }); +} + +// The SPN routes; true when the request was one of them. +function spnAnswer(spn, req, u, send) { + if (u.pathname === "/save" && req.method === "POST") { + void readBody(req).then((body) => { + if (req.headers.authorization !== `LOW ${spn.access}:${spn.secret}`) { + return send(401, "application/json", JSON.stringify({ message: "You need to be logged in to use Save Page Now." })); + } + if (spn.busy > 0) { + spn.busy--; + return send(429, "application/json", JSON.stringify({ message: "You have already reached the limit of active sessions." }), { "retry-after": "1" }); + } + const url = new URLSearchParams(body).get("url") ?? ""; + spn.forms.push(Object.fromEntries(new URLSearchParams(body))); + if (spn.refuseUrls.includes(url)) { + return send(200, "application/json", JSON.stringify({ status: "error", status_ext: "error:blocked-url", message: "This URL is in the Save Page Now service block list." })); + } + const jobId = `spn2-fake-${++spn.seq}`; + spn.jobs.set(jobId, { url, polls: 0 }); + return send(200, "application/json", JSON.stringify({ url, job_id: jobId })); + }); + return true; + } + const st = /^\/save\/status\/([^/]+)$/.exec(u.pathname); + if (st && req.method === "GET") { + const job = spn.jobs.get(decodeURIComponent(st[1])); + if (!job) { + send(404, "application/json", JSON.stringify({ status: "error", message: "Job not found." })); + return true; + } + job.polls++; + if (job.polls <= spn.pendingPolls) { + send(200, "application/json", JSON.stringify({ status: "pending", job_id: st[1] })); + return true; + } + if (spn.failUrls.includes(job.url)) { + send(200, "application/json", JSON.stringify({ status: "error", status_ext: "error:not-found", message: "Server returned a 404 for this page." })); + return true; + } + if (!spn.captured.some((c) => c.original === job.url)) { + const page = spn.pages[job.url]; + spn.captured.push({ original: job.url, timestamp: spn.timestamp, statuscode: "200", mimetype: "text/html", body: () => page ?? spnPageHtml(job.url) }); + } + send(200, "application/json", JSON.stringify({ status: "success", job_id: st[1], timestamp: spn.timestamp, original_url: job.url, duration_sec: 3 })); + return true; + } + return false; +} + // YouTube ids whose video (not only its page) the fake archive holds. export const VIDEOS = ["gone-video-05"]; @@ -189,13 +271,32 @@ export async function startFakeWayback(opts = {}) { let busy = opts.busyTimes ?? 0; let down = opts.downTimes ?? 0; let scanRequests = 0; + // Release 37 (lane E): Save Page Now's state. + const spn = { + access: opts.spn?.access ?? FAKE_SPN_ACCESS, + secret: opts.spn?.secret ?? FAKE_SPN_SECRET, + busy: opts.spn?.busyTimes ?? 0, + pendingPolls: opts.spn?.pendingPolls ?? 1, + failUrls: opts.spn?.failUrls ?? [], + refuseUrls: opts.spn?.refuseUrls ?? [], + pages: opts.spn?.pages ?? {}, + timestamp: opts.spn?.timestamp ?? SPN_CAPTURE_TS, + jobs: new Map(), + seq: 0, + forms: [], + captured: [], + }; const server = http.createServer((req, res) => { const u = new URL(req.url ?? "/", "http://fake"); - requests.push({ path: u.pathname + u.search, at: Date.now() }); + requests.push({ path: u.pathname + u.search, at: Date.now(), method: req.method }); const send = (status, type, body, headers = {}) => { res.writeHead(status, { "content-type": type, ...headers }); res.end(body); }; + // Release 37 (lane E): Save Page Now, and the captures it made (raw). + if (spnAnswer(spn, req, u, send)) return; + const spc = /^\/web\/(\d{1,14})(id_|if_)?\/(.+)$/.exec(u.pathname + u.search); + if (spc && pageCaptureAnswer(spn.captured, spc[1], spc[2] ?? "", spc[3], send, res)) return; if (u.pathname === "/cdx/search/cdx") { if (busy > 0) { busy--; @@ -264,6 +365,9 @@ export async function startFakeWayback(opts = {}) { return { base, requests, + // Release 37 (lane E): the SPN forms posted (no headers), and the captures made. + spnForms: spn.forms, + spnCaptures: spn.captured, fetch: (url, init) => fetch(String(url).replace(/^https?:\/\/web\.archive\.org/, base), init), close: () => new Promise((r) => server.close(() => r())), }; diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -124,6 +124,11 @@ // pnpm ops import-page --json '{"slug":"demo-pages","url":"https://web.archive.org/web/20140305120000/https://blog.example/a-post.html","dryRun":true}' // pnpm ops import-page --json '{"slug":"demo-pages","url":"https://blog.example/a-post.html","at":"20140301"}' --wait // pnpm ops reextract-pages --json '{"slug":"demo-pages","dryRun":true}' --wait +// pnpm ops check-post-availability --json '{"slug":"demo-pages","mode":"unchecked"}' --wait +// pnpm ops save-page-now --json '{"url":"https://blog.example/a-post.html","slug":"demo-pages","dryRun":true}' +// pnpm ops save-page-now --json '{"url":"https://blog.example/a-post.html","slug":"demo-pages"}' --wait +// pnpm ops find-copy --json '{"article":"demo-article","pages":true,"dryRun":true}' --wait +// pnpm ops find-copy --json '{"siteId":"demo-site","pages":true,"channel":"demo-pages"}' --wait // pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait // pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}' // pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait @@ -452,6 +457,13 @@ const ACTIONS = [ // re-derived from its stored captures ({slug, dryRun?}), offline, as a job. "import-page", "reextract-pages", + // WAYBACK PAGES, LIVE (release 37 S5): a posts channel's availability check + // ({slug, mode?, limit?}; a Wayback pages channel: each record's ORIGINAL + // URL at its own site), as a job; and Save Page Now ({url, slug?, dryRun?}): + // the Wayback Machine asked to capture a live page now (archive.org's S3 + // keys), the capture imported into slug, as a save-page-now job. + "check-post-availability", + "save-page-now", // EVIDENCE GAPS (release 29 E2): the Wayback Machine's captures of a page // ({url} or a record's {slug, id}), read only and paced; and find-copy — a // copy of every gone recording a report cites (Wayback, then archive.org), @@ -1457,6 +1469,20 @@ export function usage() { " with @@find-copy {scope, gone, dryRun, max, channels, eligible, skipped,", " looked: [{slug, id, gone, noTranscript, watchUrl, youtubeId, tried,", " copy?, via?, outcome}], left, items, stopped?, fetchJobId?, refused?}.", + ' The page mode (release 37): {"article"} | {"articles": true} |', + ' {"siteId"}, "pages": true, "channel"?, "max"? (10, at most 100),', + ' "dryRun"? -> {jobId}. Every page a report cites ("page" citations) whose', + " original is gone at its own site gets the Wayback capture nearest the", + " citation's date (one CDX lookup) imported into the Wayback pages channel", + " named, else the one whose targets cover the page; a cited page record", + " whose original is gone has its capture imported again when it is not", + " stored. A live page is left (save-page-now it). The answer names the", + " record each citation should cite (pointTo) and the citation as a post", + " citation of it (as); the report is not rewritten. A find-copy job on the", + " archive.org queue; dryRun asks the same paced questions and imports", + " nothing. The log ends with @@find-copy {host, dryRun, max, pages, posts,", + " items: [{citedBy, url, original, channel?, capture?, outcome, detail,", + " pointTo?, as?, records?}], left, stopped?}.", "", 'wayback-scan lists the Wayback Machine\'s captures of a Wayback pages', ' channel\'s targets (config wayback.targets) into its wayback-scan.json,', @@ -1525,6 +1551,32 @@ export function usage() { " {captures, stale, records: {added, changed, removed, unchanged, kept},", " written}.", "", + "check-post-availability checks which of a posts channel's archived posts", + ' are gone at their source: {"slug", "mode"?: "stale" (default) |', + ' "unchecked" | "all", "limit"?: 200}, as a check-post-availability job.', + " A Wayback pages channel's records are checked by their ORIGINAL URL at", + " its own site (never the Wayback Machine), one request per distinct URL", + " through the editor's web pacer (3 s apart): HEAD, then GET when the HEAD", + " is refused or the platform has a \"gone\" page; available (2xx on the", + " same site), deleted (404/410, or X's, Tumblr's, Google Docs' or", + ' YouTube\'s "does not exist" page), account_unavailable (suspended, not', + " shared), error otherwise — with the status. A deleted original means the", + " Wayback copy is the only copy. Verdicts go to posts-availability.json.", + "", + "save-page-now asks the Wayback Machine to capture a live page now (Save", + ' Page Now, with archive.org\'s S3 keys): {"url", "slug"?, "dryRun"?}. A', + " save-page-now job on the archive.org queue: the capture asked (the page", + " alone, no outlinks), its status polled until it is made, then — with", + " slug, a Wayback pages channel — an import-page job of the new capture.", + " Refused, before any job: no keys (ARCHIVE_ORG_S3_ACCESS and", + " ARCHIVE_ORG_S3_SECRET in the editor's environment, or the mode-600 file", + " settings archiveOrg.s3KeyFile names), a URL that is not http(s), a page", + " on the Wayback Machine, not a Wayback pages channel, a video, an X page", + " outside an X channel while X is private. The keys are never logged.", + ' "dryRun" answers what it would ask and starts nothing. The log ends with', + " @@save-page-now {ok, url, slug?, spnJobId, captureTs, originalUrl,", + " waybackUrl, importJobId?, importError?, polls, error?}.", + "", 'report-draft runs a generation over an article\'s iteration as a', ' report-draft job: {"task": "sweep" | "revise-report" | "revise-video" |', ' "research" | a media draft, "article", ...} -> {jobId, iteration,', diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs @@ -910,3 +910,21 @@ test("import-page and reextract-pages are POSTs to their routes, named in the us assert.match(usage(), /Actions:.*import-post, import-page, reextract-pages/); assert.match(usage(), /import-page imports ONE Wayback Machine capture/); }); + +// Release 37 S5: a posts channel's availability check, Save Page Now and +// find-copy's page mode are POSTs to their routes, named in the usage. +test("check-post-availability, save-page-now and find-copy's page mode are POSTs, named in the usage", () => { + const c = parseArgs(["check-post-availability", "--json", '{"slug":"old-blog","mode":"unchecked"}', "--wait"]); + assert.equal(c.method, "POST"); + assert.equal(c.path, "/api/ops/check-post-availability"); + assert.deepEqual(c.body, { slug: "old-blog", mode: "unchecked" }); + const s = parseArgs(["save-page-now", "--json", '{"url":"https://blog.example/a.html","slug":"old-blog","dryRun":true}']); + assert.equal(s.path, "/api/ops/save-page-now"); + assert.deepEqual(s.body, { url: "https://blog.example/a.html", slug: "old-blog", dryRun: true }); + const f = parseArgs(["find-copy", "--json", '{"siteId":"demo-site","pages":true,"channel":"old-blog"}', "--wait"]); + assert.equal(f.path, "/api/ops/find-copy"); + assert.deepEqual(f.body, { siteId: "demo-site", pages: true, channel: "old-blog" }); + assert.match(usage(), /Actions:.*reextract-pages, check-post-availability, save-page-now/); + assert.match(usage(), /save-page-now asks the Wayback Machine to capture a live page now/); + assert.match(usage(), /The page mode \(release 37\)/); +}); diff --git a/settings.json.example b/settings.json.example @@ -195,7 +195,8 @@ "stallMinutes": 5, "maxPeers": 30, "maxDownloadKiBps": 0, - "maxUploadKiBps": 0 + "maxUploadKiBps": 0, + "s3KeyFile": "~/.config/archilyzer/archive-org.env" }, "publish": { "enabled": false,