Archilyzer · Source

archilyzer

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

commit 0f19472e2899de9844aff05a41473381329d4100
parent e7825351f779938a100a5eb27d5dc52290371be7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 20 Oct 2026 20:53:43 -0400

Merge r37/archive-sources: archive.today as a second archive source (one registry, paced client, unwrapped copies, import-page and archive-lookup, Connect archive session)

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

Diffstat:
MCHANNEL.md | 2+-
MCOMMANDS.md | 8+++++---
MENVIRONMENT.md | 1+
MOPERATING.md | 34++++++++++++++++++++++++++++++++++
MSETTINGS.md | 25+++++++++++++++++++++++++
Mcommon/bin/archilyzer.ts | 25+++++++++++++++++++++++--
Mcommon/bin/wayback-pages.ts | 26+++++++++++++++++++++++++-
Acommon/controller/importPage.archiveToday.test.ts | 208+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/importPage.ts | 458+++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------
Mcommon/controller/reextractPages.ts | 14+++++---------
Acommon/lib/archives/archiveToday.test.ts | 140+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/archives/archiveToday.ts | 318+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/archives/archiveTodayClient.test.ts | 231+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/archives/archiveTodayClient.ts | 537+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/archives/archiveTodaySession.ts | 205+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/archives/ask.ts | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/archives/index.ts | 168+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/archives/mementos.test.ts | 143+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/archives/mementos.ts | 183+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/archives/settings.ts | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/archives/types.ts | 140+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/archives/wayback.test.ts | 136+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/archives/wayback.ts | 83+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/channelConfig.ts | 2+-
Mcommon/lib/envVars.ts | 1+
Mcommon/lib/settingsDocs.ts | 8++++++++
Mcommon/lib/settingsSchema.test.ts | 5++++-
Mcommon/lib/settingsSchema.ts | 5+++++
Mcommon/lib/waybackClient.ts | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mcommon/lib/waybackPages/config.ts | 30++++++++++++++++++++++++++++++
Mcommon/lib/waybackPages/parse.ts | 6++++++
Mcommon/lib/waybackPages/store-server.ts | 31+++++++++++++++++++++++++++++++
Mcommon/lib/waybackPages/toPost.ts | 14++++++++++++--
Mcommon/lib/waybackPages/types.ts | 10++++++++++
Mcommon/lib/waybackPages/urls.ts | 7+++++++
Mcommon/lib/waybackPages/view.ts | 16+++++++++++++---
Mcommon/publish/findCopyPages.ts | 20+++++++++++++++++---
Acommon/testing/web/fakeArchiveToday.d.mts | 33+++++++++++++++++++++++++++++++++
Acommon/testing/web/fakeArchiveToday.mjs | 240+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/testing/web/fakeWayback.d.mts | 2++
Mcommon/testing/web/fakeWayback.mjs | 12++++++++++++
Meditor/CHANGELOG.md | 2++
Aeditor/app/api/ops/archive-lookup/route.ts | 34++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/import-page/route.ts | 14+++++++++++---
Meditor/app/api/ops/wayback-lookup/route.ts | 7+++++++
Meditor/app/channels/[slug]/components/WaybackPageRecords.tsx | 3++-
Meditor/app/channels/[slug]/components/WaybackPagesPanel.tsx | 138++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Meditor/app/channels/[slug]/page.tsx | 10+++++++++-
Meditor/app/channels/[slug]/waybackPagesActions.ts | 35+++++++++++++++++++++++++++++++++--
Meditor/app/channels/components/ChannelForm.tsx | 4++--
Meditor/app/channels/components/WaybackTargetsField.tsx | 44+++++++++++++++++++++++++++++++++++++++++---
Meditor/app/channels/components/parseChannelForm.test.ts | 7+++++--
Aeditor/app/settings/archiveSessionActions.ts | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/settings/components/ArchiveSessionSection.tsx | 138+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/settings/page.tsx | 7+++++++
Aeditor/e2e/archive-today-pages.spec.ts | 175+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/e2e/servers.ts | 8++++++++
Meditor/playwright.config.ts | 3+++
Mplans/FACTS.md | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aplans/release-37/archive-sources.md | 132+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 31++++++++++++++++++++++++++++++-
Mscripts/archilyzer-ops.test.mjs | 14++++++++++++++
Msettings.json.example | 6++++++
Mumtool/lib/articles/evidence.ts | 4+++-
64 files changed, 4488 insertions(+), 181 deletions(-)

diff --git a/CHANNEL.md b/CHANNEL.md @@ -50,7 +50,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | `browserLookup` | config | `true`, with `storedUrlDownloads` `fallback` or `only`: when a video's record stores no media URL — `only`, or a `fallback` whose yt-dlp lookup was refused (a 429) — the managed download opens the video's page in a headless browser, reads the record from the page's own API answers and writes `metadata.info.json` (marked `_source: "browser"`), then downloads from the media URL the page named. Odysee only; one page a minute; the channel's `--match-filter title~='…'` and download filters still decide. Absent = off. The video page's **Read from the page** and the channel's **List from the page** ask for it once, whatever this says. | | `recordedDate` | config | For a channel that MIRRORS another's streams (a VOD archive): how to read the date a video was RECORDED from its title, since its `upload_date` is the date of the copy. The index stores the result as the record's `recordedDate` (`YYYYMMDD`), which coverage reads before the upload date. A title it does not match, a date that is not a real day, or one after the upload date gives none. Changing the rule re-derives the channel's records on the next index build. An object without a usable `titlePattern` is dropped. See [`recordedDate`](#recordeddate). | | `mirror` | config | For a channel that MIRRORS another creator's streams: the creator's channels it copies (`of`, their slugs). The mirror scan (`pnpm ops mirror-scan`) pairs each of this channel's videos with the creator's by date and title and writes `transcripts/mirrors/<slug>.json`: which videos the creator still has public, removed or never uploaded, and which of the creator's removed videos this channel holds. Private: never published. An object without a usable `of` is dropped. See [`mirror`](#mirror). | -| `wayback` | config | A WAYBACK PAGES channel (platform `"webpage"`, `sourceKind` `"social"`): which Wayback Machine captures of pages that are not videos are in scope. `{targets: [{url, match, from?, to?, mime?, include?, exclude?}], collapse?: "digest", auto?: true}` — `match` is `"exact"` (one page), `"prefix"` (every URL under a path), `"host"` (one host) or `"domain"` (a host and its subdomains); `from`/`to` bound the capture time (a Wayback timestamp prefix, 4–14 digits, inclusive); `mime` the mimetypes kept (default `text/html`); `include`/`exclude` regex sources over a capture's original URL. Each capture imported (`pnpm ops import-page`, the channel page's **Import a capture**) becomes a page record in the channel's posts, its raw body kept under `pages/` (OPERATING.md, "Import from the Wayback Machine"). A target without a URL or a valid `match` is dropped; an object with no valid target is dropped. `auto: true` lets the download lane import the captures a later scan (`pnpm ops wayback-scan`, the **Captures** tab) adds, one job each at archive.org's pace; absent, nothing is imported unasked. | +| `wayback` | config | A WAYBACK PAGES channel (platform `"webpage"`, `sourceKind` `"social"`): which Wayback Machine captures of pages that are not videos are in scope. `{targets: [{url, match, from?, to?, mime?, include?, exclude?}], collapse?: "digest", auto?: true}` — `match` is `"exact"` (one page), `"prefix"` (every URL under a path), `"host"` (one host) or `"domain"` (a host and its subdomains); `from`/`to` bound the capture time (a Wayback timestamp prefix, 4–14 digits, inclusive); `mime` the mimetypes kept (default `text/html`); `include`/`exclude` regex sources over a capture's original URL. Each capture imported (`pnpm ops import-page`, the channel page's **Import a capture**) becomes a page record in the channel's posts, its raw body kept under `pages/` (OPERATING.md, "Import from the Wayback Machine"). A target without a URL or a valid `match` is dropped; an object with no valid target is dropped. `auto: true` lets the download lane import the captures a later scan (`pnpm ops wayback-scan`, the **Captures** tab) adds, one job each at archive.org's pace; absent, nothing is imported unasked. Release 37 lane F: a target's `sources` (`["wayback", "archive.today"]`; absent = the Wayback Machine alone) says which archives hold its copies, and an archive.today copy imported into the channel is a page record like a capture (OPERATING.md, "Archived pages: the Wayback Machine and archive.today"); the form calls the kind "Archived pages". | | `xSearch` | config | An X SEARCH channel (platform `"twitter"`, `sourceKind` `"social"`, `url` the search page): a saved X search across accounts, its records the matching posts from ANY author. `{query, since?, until?, windowMonths?, lang?, exclude?}` — `query` as X's search box takes it (words, `"phrases"`, `OR`, `-term`, `from:`, `to:`, `@mention`, `url:`, `filter:`, `lang:` pass through; `since:`, `until:` and `max_id:` are refused — the walk adds them); `since`/`until` the days walked between (YYYY-MM-DD; `since` inclusive, `until` exclusive; absent `until` = tomorrow, and each later fetch searches what is new); `windowMonths` each search window's span (1–12, default 3); `lang` a language code added as `lang:<code>`; `exclude` the handles **Never archive** hid from the leads view (lower case). A fetch walks the windows newest first through gallery-dl's search, resumable, at the older walk's pace and with its login (OPERATING.md, "X search"). Never on a site. An object without a valid query is dropped. | #### `downloadFilter` diff --git a/COMMANDS.md b/COMMANDS.md @@ -57,7 +57,8 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `archilyzer archive-org refresh` | `<slug> [--dry-run]` | bring a channel's archive.org file records up to their provenance: a name-only mirror's title (where the item gives the file none) and upload date from its file name; offline, through the metadata history; prints old → new | | `archilyzer wayback refresh` | `<slug> [--titles <json>] [--dry-run]` | bring a channel's Wayback Machine copies up to the Wayback rules: wayback.json (original URL, capture time), the dir renamed to its canonical id through the snapshot's reconcile (roster moved with it), and with --titles (a file of id → {title, upload\_date}) a raw file's title and date; offline, skips a record a live job holds; prints old → new | | `archilyzer wayback scan` | `<slug> [--dry-run] [--max-rows N] [--full]` | list the Wayback Machine's captures of a Wayback pages channel's targets (config wayback.targets) into its wayback-scan.json: the CDX API per target, paged with a resume key, collapse=digest, status 200, at most N rows (50000) a run, no bodies; a cut run continues next time, a complete one starts a new pass (--full: from each target's start); paced as archive.org asks, in this process — with the editor running use `pnpm ops wayback-scan`; --dry-run asks nothing and prints the next request per target | -| `archilyzer wayback pages import` | `<slug> <url> [--at YYYYMMDD] [--dry-run]` | import ONE Wayback Machine capture of a page that is not a video into a Wayback pages channel: a capture's replay URL, or the page's URL and --at for the capture nearest that date; the raw body stored under pages/, its records in the channel's posts. In-process, through this process's own paced client — while an editor runs, prefer `pnpm ops import-page` | +| `archilyzer wayback pages import` | `<slug> <url> [--at YYYYMMDD] [--source archive.today] [--dry-run]` | import ONE Wayback Machine capture (or archive.today copy) of a page that is not a video into a Wayback pages channel: a capture's replay URL, an archive.today copy's URL (archive.ph/&lt;id&gt;), or the page's URL and --at for the capture nearest that date (--source archive.today: its archive.today copy); the body stored under pages/, its records in the channel's posts. In-process, through this process's own paced clients — while an editor runs, prefer `pnpm ops import-page` | +| `archilyzer archive lookup` | `<url> [--source wayback\|archive.today] [--limit N]` | the copies of a page each archive source holds (the Wayback Machine's CDX, archive.today's timemap), oldest first, at most N per source (50): read only, each source through its own paced client. A source that refuses says why (excluded from the Wayback Machine, a check, a 429). While an editor runs, `pnpm ops archive-lookup` shares its clients | | `archilyzer wayback pages reextract` | `<slug> [--dry-run]` | re-derive a Wayback pages channel's records from the raw captures it stores (no request): every capture read by the extractor it goes to now, the records replaced when anything differs; --dry-run counts. Writes the channel's posts — with the editor stopped, or use `pnpm ops reextract-pages` | | `archilyzer feeds backfill-metadata` | `<slug> [--feed <url>] [--dry-run]` | complete a podcast channel's records (title, date, description, duration) from its RSS feed: one fetch of the feed (default: the channel's url), no media; --dry-run counts matched / unmatched / already complete and writes nothing | | `archilyzer media attach` | `<slug> <source> [--items <json\|@file>] [--match <regex>] [--create-records] [--replace] [--dry-run]` | give a channel's held videos their media from a LOCAL archive (a directory, a .zip read in place, a .7z) into the saved-video store, provenance recorded (archive, entry, sha256); the id from the folder's "(&lt;id&gt;)" or the file's yt-dlp suffix; --create-records writes a record for a video not held; --dry-run lists each folder's class and writes nothing; offline, nothing fetched | @@ -158,12 +159,13 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `archive-search` | archive-search searches archive.org (its advanced-search syntax) and answers the items: {"query", "limit"?: 50 (at most 500)} -&gt; {found, items: \[{identifier, title?}\]}, in identifier order. One request through the editor's archive.org client, paced and backed off as an import is. Read only; import-archive-org with "query" imports what a search finds. {"youtubeId", "limit"?: 10} looks for mirrors of one YouTube upload instead: items OF it (their identifier, a file name or their original URL names the id; a title or description that mentions it is not enough), each read for its files -&gt; {query, found, items: \[{identifier, title?, file, url, source, size?, seconds?, namedBy}\], skipped: \[{identifier, why}\]}: each mirror's direct video file URL, an original preferred. | `pnpm ops archive-search --json '{"query":"title:(kitchen) AND mediatype:movies","limit":20}'`<br>`pnpm ops archive-search --json '{"youtubeId":"dQw4w9WgXcQ"}'` | | `archive-item` | archive-item answers one archive.org item's files from its metadata: {"item"} -&gt; {item: {identifier, url, title?, date?, mediatype?, creator?, collections, restricted, mediaFiles, mediaBytes, files: \[{name, format?, source?, size?, seconds?, media, restricted, original?}\]}}. media marks the originals an import takes (one record each); restricted, what archive.org will not hand out. Read only; nothing is downloaded. | `pnpm ops archive-item --json '{"item":"example-item"}'` | | `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` | +| `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?}. archive.today (release 37 lane F): "url" may be an archive.today copy (archive.ph/&lt;id&gt;, /&lt;timestamp&gt;/&lt;page&gt;, /newest/&lt;page&gt;), or the page's own URL with "at" and "source": "archive.today" for its copy nearest that date (one timemap request); the job runs on the platform:archive.today queue at archive.today's pace (one request at a time, 8 s apart; a 429 stops it and rests the client). The copy is stored as served with its source and URL. A check page (a CAPTCHA) is refused, never solved: Connect archive session on the channel page or Settings, then again. The result carries "source", "mementoUrl" and, for a refusal, "refusal": "excluded" (the Wayback Machine answered 403 for the page), "challenge", "rate-limited", …. | `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`<br>`pnpm ops import-page --json '{"slug":"demo-pages","url":"https://archive.ph/AbCdE","dryRun":true}'`<br>`pnpm ops import-page --json '{"slug":"demo-pages","url":"https://blog.example/a-post.html","at":"20190601","source":"archive.today"}' --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` | +| `archive-lookup` | archive-lookup answers the copies of a page each archive source holds: {"url"} (the page's own URL), "source"?: "wayback" \| "archive.today" (default both), "limit"?: 50 per source (at most 500) -&gt; {url, found, sources: \[{source, label, ok, captures: \[{source, captureTs, originalUrl, mementoUrl, status?, mimetype?}\], refusal?, error?}\]}, oldest first. Each source through its own paced client; one that refuses is its own entry's sentence (refusal "excluded": excluded from the Wayback Machine (cause unknown); "challenge"; "rate-limited"). Read only. wayback-lookup stays. | `pnpm ops archive-lookup --json '{"url":"https://blog.example/a-post.html"}'` | | `x-search-lead` | x-search-lead acts on one lead of an X search channel (the accounts its posts came from — `get channel <slug> --leads [--limit <n>]` lists them, most matches first): {"slug", "handle", "action": "archive" \| "never" \| "restore"}. "archive" creates &lt;handle&gt;-x, an X channel on NO site, by the New channel form's path and starts its first post fetch ("fetch": false skips it; "name"? names it; "dryRun" answers the fields and creates nothing) -&gt; {slug, jobIds}. Refused: not an X search channel, an account an X channel archives already, a slug taken. "never" hides the handle (the channel's xSearch.exclude), "restore" un-hides it -&gt; {exclude, changed}. No model, no request but the new channel's fetch. | `pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"archive","dryRun":true}'`<br>`pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"never"}'` | -| `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}'` | +| `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. A URL the Wayback Machine answers 403 for is excluded: HTTP 403, "refusal": "excluded" ("excluded from the Wayback Machine (cause unknown)"). | `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?}. 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}'` | diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -238,6 +238,7 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one | `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, 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_ARCHIVE_TODAY_ORIGIN_FILE` | unset (the real archive.today) | A file holding one loopback origin; while it exists, the editor's archive.today client sends every request for any archive.today name (archive.ph, archive.today, archive.is, …) there — the fake archive.today a spec starts (`common/testing/web/fakeArchiveToday.mjs`) — and never opens the archive session's browser. The editor's e2e server names a file in each slot's test data (`archive-today-pages.spec`); anything but a loopback origin in it is ignored. | common/lib/archives/archiveTodayClient.ts, common/lib/archives/index.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/OPERATING.md b/OPERATING.md @@ -111,6 +111,40 @@ pnpm ops reextract-pages --json '{"slug":"old-blog","dryRun":true}' --wait `pnpm archilyzer wayback pages reextract <slug> --dry-run`. - An x.com / twitter.com capture is private exactly as X posts are (`social.x.visibility`): while X is private, only a Wayback pages channel whose target is on X takes one, and a public site leaves that channel out. +- A URL the Wayback Machine answers 403 for (while it answers others) is **excluded** — "excluded from the Wayback + Machine (cause unknown)": `wayback-lookup` answers 403 with `refusal: "excluded"`, `import-page` and + `archive-lookup` carry the same code and sentence. + +### Archived pages: the Wayback Machine and archive.today + +```sh +pnpm ops archive-lookup --json '{"url":"https://blog.example/a-post.html"}' +pnpm ops import-page --json '{"slug":"old-blog","url":"https://archive.ph/<id>","dryRun":true}' +pnpm ops import-page --json '{"slug":"old-blog","url":"https://archive.ph/<id>"}' --wait +pnpm ops import-page --json '{"slug":"old-blog","url":"https://blog.example/a-post.html","at":"20190601","source":"archive.today"}' --wait +pnpm archilyzer archive lookup https://blog.example/a-post.html --source archive.today +``` + +- The channel kind is **Archived pages** in the New channel form (the config key stays `wayback`). A target names + where its copies are looked for: `sources: ["wayback", "archive.today"]` (absent = the Wayback Machine alone); an + archive.today copy's URL in the form (`archive.ph/newest/<page>`) makes a channel whose target is that page on + archive.today. +- `import-page` takes an archive.today copy (`archive.ph/<id>`, `/<timestamp>/<page>`, `/newest/<page>`; any of its + names — archive.ph, .today, .is, .li, .vn, .fo, .md — is read from the one in `settings.archives`), or the page's + own URL with `at` and `source: "archive.today"` (its timemap, one request). The job runs on + `platform:archive.today`, one request at a time, 8 s apart (jittered); a 429 stops it and nothing is sent to + archive.today for 30 minutes. The copy is stored as served (`capture.json` gains `source` and `mementoUrl`) and + unwrapped each time it is read, so `reextract-pages` re-reads it offline like any capture. Its records carry + `page.source: "archive.today"` and `page.archiveUrl`; their images are archive.today's cached copies. +- **A check is never solved.** archive.today often answers a client that is not a browser with a CAPTCHA: the + import is refused (`refusal: "challenge"`), never parsed. With `settings.archives.archiveTodayBrowser` (the + default) the copy is read once more through the headless browser on the archive session's profile; when that + check still stands, open **Connect archive session** (the channel page, or Settings → Archive sources), pass the + check once in the window on the editor's machine and close it, then import again — the profile keeps the + clearance (`transcripts/.archive-session/archive.today/`). +- The channel page's **Look up a page** (and `archive-lookup`) lists each source's copies of a page, with an Import + button per copy; a source that refuses says why in its own line. +- Adding another archive service is one module: `plans/release-37/archive-sources.md`, "Adding an archive source". ### Wayback pages: scan, then choose diff --git a/SETTINGS.md b/SETTINGS.md @@ -47,6 +47,7 @@ A copied example PINS every default it spells — including each lane's `autoQue | [`backfill`](#backfill) | object — see below | | [`attribution`](#attribution) | object — see below | | [`archiveOrg`](#archiveorg) | object — see below | +| [`archives`](#archives) | object — see below | | [`publish`](#publish) | object — see below | | [`reportSchedule`](#reportschedule) | object — see below | | [`seeder`](#seeder) | object — see below | @@ -838,6 +839,30 @@ Default: } ``` +## `archives` + +The archive sources a page import reads besides the Wayback Machine (release 37 lane F, lib/archives/): archive.today's one canonical host, its pace (one request at a time, a long gap, a rest after a 429) and whether a check it answers with is read once more through the archive session's headless browser. The Wayback Machine keeps archive.org's own client and pace. See ArchivesSettings. + +#### `archives` + +| Key | Default | Description | +|---|---|---| +| `archiveTodayHost` | `"archive.ph"` | The archive.today name every request goes to (archive.ph, archive.today, archive.is, archive.li, archive.vn, archive.fo or archive.md — one service). A copy's URL on any of them is read from this one. Anything else falls back to archive.ph. | +| `archiveTodayGapSeconds` | `8` | The least time between two archive.today requests, seconds, from the end of one to the start of the next, with up to a quarter more at random. One request at a time, always. Clamped to [4, 120]; default 8. | +| `archiveTodayCooldownMinutes` | `30` | After archive.today answers HTTP 429 (too many requests) the run stops, and no request goes to it for this long (or its Retry-After, when longer). Clamped to [5, 1440]; default 30. | +| `archiveTodayBrowser` | `true` | When archive.today answers with a check (a CAPTCHA, a browser check) instead of a copy, read the copy once more through the headless browser on the archive session's profile (Connect archive session keeps a cleared check there). Nothing is ever solved by code: a check the browser cannot pass is refused with a sentence. False = refuse at the check. | + +Default: + +```json +{ + "archiveTodayHost": "archive.ph", + "archiveTodayGapSeconds": 8, + "archiveTodayCooldownMinutes": 30, + "archiveTodayBrowser": true +} +``` + ## `publish` The publish LANE (release 18): a runner that, when the index is stale, updates it and then builds — and, where a site's own `publish.auto` (site.json) says so, deploys — what changed, one stage at a time on the `publish` queue. OFF by default; the manual stages (Publish now, Build, Deploy) work either way. See PublishSettings and common/publish/publishRunner.ts. diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -699,8 +699,8 @@ export const COMMANDS: Command[] = [ { path: ["wayback", "pages", "import"], usage: - "<slug> <url> [--at YYYYMMDD] [--dry-run] import ONE Wayback Machine capture of a page that is not a video into a Wayback pages channel: a capture's replay URL, or the page's URL and --at for the capture nearest that date; the raw body stored under pages/, its records in the channel's posts. In-process, through this process's own paced client — while an editor runs, prefer `pnpm ops import-page`", - flags: { at: "string", "dry-run": "boolean" }, + "<slug> <url> [--at YYYYMMDD] [--source archive.today] [--dry-run] import ONE Wayback Machine capture (or archive.today copy) of a page that is not a video into a Wayback pages channel: a capture's replay URL, an archive.today copy's URL (archive.ph/<id>), or the page's URL and --at for the capture nearest that date (--source archive.today: its archive.today copy); the body stored under pages/, its records in the channel's posts. In-process, through this process's own paced clients — while an editor runs, prefer `pnpm ops import-page`", + flags: { at: "string", source: "string", "dry-run": "boolean" }, maxPositionals: 2, run: async ({ positionals, flags }) => { const [slug, url] = positionals; @@ -712,11 +712,32 @@ export const COMMANDS: Command[] = [ slug, url, ...(typeof flags.at === "string" ? { at: flags.at } : {}), + ...(typeof flags.source === "string" ? { source: flags.source } : {}), dryRun: flags["dry-run"] === true, signal: interrupted(), }); }, }, + // Release 37 lane F: the copies of a page across archive sources. + { + path: ["archive", "lookup"], + usage: + "<url> [--source wayback|archive.today] [--limit N] the copies of a page each archive source holds (the Wayback Machine's CDX, archive.today's timemap), oldest first, at most N per source (50): read only, each source through its own paced client. A source that refuses says why (excluded from the Wayback Machine, a check, a 429). While an editor runs, `pnpm ops archive-lookup` shares its clients", + flags: { source: "string", limit: "string" }, + maxPositionals: 1, + run: async ({ positionals, flags }) => { + const [url] = positionals; + if (!url || !/^https?:\/\//.test(url)) { + console.error("archive lookup: pass a page's own http(s) URL."); + return 2; + } + return (await import("./wayback-pages")).lookupMain({ + url, + ...(typeof flags.source === "string" ? { source: flags.source } : {}), + ...(typeof flags.limit === "string" ? { limit: Number(flags.limit) } : {}), + }); + }, + }, { path: ["wayback", "pages", "reextract"], usage: diff --git a/common/bin/wayback-pages.ts b/common/bin/wayback-pages.ts @@ -1,4 +1,4 @@ -// `archilyzer wayback pages import <slug> <url> [--at YYYYMMDD] [--dry-run]` +// `archilyzer wayback pages import <slug> <url> [--at YYYYMMDD] [--source archive.today] [--dry-run]` // and `archilyzer wayback pages reextract <slug> [--dry-run]` — a Wayback pages // channel (release 37 S1) from the command line, in-process. // @@ -21,6 +21,7 @@ export async function importMain(opts: { slug: string; url: string; at?: string; + source?: string; dryRun: boolean; paths?: Paths; signal?: AbortSignal; @@ -34,6 +35,7 @@ export async function importMain(opts: { slug: opts.slug, url: opts.url, ...(opts.at ? { at: opts.at } : {}), + ...(opts.source ? { source: opts.source } : {}), dryRun: opts.dryRun, onLog: (line) => console.log(line), ...(opts.signal ? { signal: opts.signal } : {}), @@ -65,3 +67,25 @@ export async function reextractMain(opts: { slug: string; dryRun: boolean; paths } return 0; } + +// `archilyzer archive lookup <url>` (release 37 lane F): the copies each archive +// source holds of a page, read only. +export async function lookupMain(opts: { url: string; source?: string; limit?: number }): Promise<number> { + const { archiveLookup } = await import("../lib/archives/index"); + const { isArchiveSourceId } = await import("../lib/archives/types"); + if (opts.source && !isArchiveSourceId(opts.source)) { + console.error(`archive lookup: --source must be "wayback" or "archive.today", not "${opts.source}"`); + return 2; + } + const limit = opts.limit && Number.isInteger(opts.limit) && opts.limit > 0 ? Math.min(opts.limit, 500) : 50; + const r = await archiveLookup(opts.url, { ...(opts.source ? { source: opts.source as "wayback" | "archive.today" } : {}), limit }); + for (const s of r.sources) { + if (!s.ok) { + console.log(`${s.label}: ${s.error}`); + continue; + } + console.log(`${s.label}: ${s.captures.length} cop${s.captures.length === 1 ? "y" : "ies"}`); + for (const c of s.captures) console.log(` ${c.captureTs} ${c.mementoUrl}`); + } + return r.sources.some((s) => s.ok) ? 0 : 1; +} diff --git a/common/controller/importPage.archiveToday.test.ts b/common/controller/importPage.archiveToday.test.ts @@ -0,0 +1,208 @@ +// Release 37 lane F: `import-page` of an archive.today copy end to end on the +// fake archive.today — the copy by its short id and nearest a date, stored AS +// SERVED with its source, records that say where they are from, never fetched +// twice, a check refused with its code and nothing written, and a re-extract +// that reads the stored copy unwrapped. Also the Wayback exclusion (a CDX 403) +// as an import's typed refusal. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/importPage.archiveToday.test.ts + +import test, { after } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { gunzipSync } from "node:zlib"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { + startFakeArchiveToday, + fixtureCopy, + COPIES, + AT_ARTICLE_ID, + AT_ARTICLE_LATER_ID, + AT_ARTICLE_LATER_TS, + AT_ARTICLE_TS, + AT_ARTICLE_URL, + AT_CHECKED_ID, +} from "../testing/web/fakeArchiveToday.mjs"; +import { startFakeWayback } from "../testing/web/fakeWayback.mjs"; +import type { Paths } from "../lib/paths"; +import { ArchiveTodayClient } from "../lib/archives/archiveTodayClient"; +import { WaybackClient } from "../lib/waybackClient"; +import { importPage, importPageQueueOf, planImportPage } from "./importPage"; +import { reextractPages } from "./reextractPages"; +import { readAllPosts } from "../lib/posts-server"; +import { pageRecordId } from "../lib/waybackPages/types"; +import { listStoredCaptures, pageCaptureDir } from "../lib/waybackPages/store-server"; +import { pageArchiveLink } from "../lib/archives/mementos"; + +const ROOT = mkdtempSync(path.join(tmpdir(), "import-page-at-")); +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 PUBLIC = { social: { x: { visibility: "public" } } }; + +async function pagesChannel(slug: string, target: string) { + 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, + sourceKind: "social", + platform: "webpage", + socialHandle: target.split("/")[0], + url: `https://web.archive.org/web/*/${target}*`, + wayback: { targets: [{ url: target, match: "prefix", sources: ["wayback", "archive.today"] }] }, + }), + ); + return dir; +} + +const TWEET_URL = "https://twitter.com/TeapotFan/status/697374449464250369"; +const TWEET_ID = "Tw33t"; +const TWEET_TS = "20160211000000"; + +async function withFake(fn: (client: ArchiveTodayClient, at: Awaited<ReturnType<typeof startFakeArchiveToday>>) => Promise<void>, opts: Parameters<typeof startFakeArchiveToday>[0] = {}) { + const at = await startFakeArchiveToday({ + copies: [...COPIES, fixtureCopy("x-2016-status.html", { id: TWEET_ID, original: TWEET_URL, timestamp: TWEET_TS })], + ...opts, + }); + try { + await fn(new ArchiveTodayClient({ fetch: at.fetch, sleep: async () => {} }, { minGapMs: 0 }), at); + } finally { + await at.close(); + } +} + +test("planned per source: an archive.today copy runs on its own queue; a short id is checked again after the read", async () => { + await pagesChannel("deleted-journal", "journal.example/"); + const p = await planImportPage(paths, { slug: "deleted-journal", url: `https://archive.ph/${AT_ARTICLE_ID}`, settings: PUBLIC }); + assert.ok(p.ok); + assert.equal(importPageQueueOf(p.plan.ask), "platform:archive.today"); + const w = await planImportPage(paths, { slug: "deleted-journal", url: "https://web.archive.org/web/2019/https://journal.example/", settings: PUBLIC }); + assert.ok(w.ok); + assert.equal(importPageQueueOf(w.plan.ask), "platform:archive.org"); + const video = await planImportPage(paths, { slug: "deleted-journal", url: "https://archive.ph/newest/https://www.youtube.com/watch?v=abcdefghijk", settings: PUBLIC }); + assert.equal(video.ok, false); + assert.match(video.ok ? "" : video.error, /use import-video/); +}); + +test("a copy by its short id: stored as served with its source, records that name archive.today, never fetched twice", async () => { + const channelRoot = await pagesChannel("deleted-journal", "journal.example/"); + await withFake(async (client, at) => { + const dry = await importPage({ paths, slug: "deleted-journal", url: `https://archive.is/${AT_ARTICLE_ID}`, dryRun: true, archiveTodayClient: client, settings: PUBLIC }); + assert.equal(dry.ok, true); + assert.match(String(dry.wouldFetch), new RegExp(`https://archive\\.ph/${AT_ARTICLE_ID}`)); + assert.equal(at.requests.length, 0, "a dry run asks nothing"); + + const res = await importPage({ paths, slug: "deleted-journal", url: `https://archive.is/${AT_ARTICLE_ID}`, archiveTodayClient: client, settings: PUBLIC }); + assert.equal(res.ok, true, res.error); + assert.equal(res.source, "archive.today"); + assert.equal(res.captureTs, AT_ARTICLE_TS); + assert.equal(res.originalUrl, AT_ARTICLE_URL); + assert.equal(res.mementoUrl, `https://archive.ph/${AT_ARTICLE_ID}`); + assert.equal(res.written, 1); + + const dir = pageCaptureDir(channelRoot, AT_ARTICLE_TS, AT_ARTICLE_URL); + const capture = JSON.parse(await readFile(path.join(dir, "capture.json"), "utf8")) as Record<string, unknown>; + assert.equal(capture.source, "archive.today"); + assert.equal(capture.mementoUrl, `https://archive.ph/${AT_ARTICLE_ID}`); + assert.equal(capture.extractor, "generic"); + const raw = gunzipSync(await readFile(path.join(dir, "raw.html.gz"))).toString("utf8"); + assert.match(raw, /id="HEADER"/, "the copy as served, bar and all"); + + const [post] = (await readAllPosts(channelRoot)).filter((p) => p.page); + assert.equal(post.id, pageRecordId(AT_ARTICLE_TS, AT_ARTICLE_URL)); + assert.equal(post.platform, "webpage"); + assert.equal(post.url, AT_ARTICLE_URL); + assert.equal(post.author, "Sam Example"); + assert.doesNotMatch(post.text, /webpage capture|Saved from/); + assert.equal(post.page?.source, "archive.today"); + assert.equal(post.page?.archiveUrl, `https://archive.ph/${AT_ARTICLE_ID}`); + assert.equal(post.page?.waybackUrl, `https://archive.ph/${AT_ARTICLE_ID}`); + assert.deepEqual(pageArchiveLink(post.page!), { source: "archive.today", label: "archive.today", url: `https://archive.ph/${AT_ARTICLE_ID}` }); + assert.match(String(post.media?.[0]?.url), new RegExp(`^https://archive\\.ph/${AT_ARTICLE_ID}/`), "the image is archive.today's cached copy"); + assert.deepEqual(post.links, ["https://journal.example/2019/05/minutes.html", "https://other.example/account"]); + + // Again, by another of its names: nothing fetched. + const n = at.requests.length; + const again = await importPage({ paths, slug: "deleted-journal", url: `https://archive.ph/${AT_ARTICLE_ID}`, archiveTodayClient: client, settings: PUBLIC }); + assert.equal(again.already, true); + assert.equal(at.requests.length, n); + const dryAgain = await importPage({ paths, slug: "deleted-journal", url: `https://archive.li/${AT_ARTICLE_ID}`, dryRun: true, archiveTodayClient: client, settings: PUBLIC }); + assert.equal(dryAgain.already, true); + }); +}); + +test("the copy nearest a date (one timemap request), a later version of the page; re-extract reads the stored copy unwrapped", async () => { + const channelRoot = await pagesChannel("deleted-journal", "journal.example/"); + await withFake(async (client, at) => { + const res = await importPage({ paths, slug: "deleted-journal", url: AT_ARTICLE_URL, at: "20191201", source: "archive.today", archiveTodayClient: client, settings: PUBLIC }); + assert.equal(res.ok, true, res.error); + assert.equal(res.captureTs, AT_ARTICLE_LATER_TS); + assert.equal(res.mementoUrl, `https://archive.ph/${AT_ARTICLE_LATER_ID}`); + assert.deepEqual(at.requests.map((r) => r.path), [`/timemap/${AT_ARTICLE_URL}`, `/${AT_ARTICLE_LATER_ID}`]); + const posts = (await readAllPosts(channelRoot)).filter((p) => p.page); + const later = posts.find((p) => p.page!.captureTs === AT_ARTICLE_LATER_TS)!; + assert.equal(later.page?.versionOf, pageRecordId(AT_ARTICLE_TS, AT_ARTICLE_URL), "a later copy is a version of the first held"); + assert.match(later.text, /a second meeting is planned/); + + const re = await reextractPages({ paths, slug: "deleted-journal" }); + assert.equal(re.ok, true, re.error); + assert.equal(re.stale, 0, "nothing stale: the stored copies read the same unwrapped"); + assert.equal(re.records.changed, 0); + assert.equal(re.records.removed, 0); + assert.equal((await listStoredCaptures(channelRoot)).every((e) => e.capture.source === "archive.today"), true); + }); +}); + +test("a tweet held by archive.today goes to the X extractor, as from the Wayback Machine", async () => { + const channelRoot = await pagesChannel("teapot-x", "twitter.com/TeapotFan"); + await withFake(async (client) => { + const res = await importPage({ paths, slug: "teapot-x", url: `https://archive.ph/${TWEET_ID}`, archiveTodayClient: client, settings: PUBLIC }); + assert.equal(res.ok, true, res.error); + assert.match(String(res.extractor), /^x v\d+$/); + const tweets = (await readAllPosts(channelRoot)).filter((p) => p.page?.kind === "tweet"); + assert.ok(tweets.length > 0); + assert.ok(tweets.every((t) => t.page?.source === "archive.today")); + }); +}); + +test("a check: refused with its code, nothing stored; a 429 refused as rate-limited", async () => { + const channelRoot = await pagesChannel("checked-pages", "checked.example/"); + await withFake( + async (client) => { + const res = await importPage({ paths, slug: "checked-pages", url: `https://archive.ph/${AT_CHECKED_ID}`, archiveTodayClient: client, settings: PUBLIC }); + assert.equal(res.ok, false); + assert.equal(res.refusal, "challenge"); + assert.equal(res.source, "archive.today"); + assert.match(String(res.error), /Connect archive session/); + assert.deepEqual(await listStoredCaptures(channelRoot), []); + assert.deepEqual(await readAllPosts(channelRoot), []); + }, + { challenge: [AT_CHECKED_ID] }, + ); + await withFake( + async (client) => { + const res = await importPage({ paths, slug: "checked-pages", url: `https://archive.ph/${AT_CHECKED_ID}`, archiveTodayClient: client, settings: PUBLIC }); + assert.equal(res.refusal, "rate-limited"); + assert.match(String(res.error), /too many requests/); + }, + { busyTimes: 1 }, + ); +}); + +test("a Wayback exclusion (a CDX 403) is an import's typed refusal", async () => { + await pagesChannel("excluded-pages", "gone.example/"); + const wb = await startFakeWayback({ excluded: ["https://gone.example/profile"] }); + try { + const client = new WaybackClient({ fetch: wb.fetch }, { minGapMs: 0 }); + const res = await importPage({ paths, slug: "excluded-pages", url: "https://gone.example/profile", at: "2014", client, settings: PUBLIC }); + assert.equal(res.ok, false); + assert.equal(res.refusal, "excluded"); + assert.match(String(res.error), /excluded from the Wayback Machine \(cause unknown\)/); + } finally { + await wb.close(); + } +}); diff --git a/common/controller/importPage.ts b/common/controller/importPage.ts @@ -26,6 +26,18 @@ // stream, the 2 s gap, 429/503 waited out), and the job runs on the // `platform:archive.org` queue — one import at a time. A capture already // stored is not fetched again. +// +// ARCHIVE.TODAY (release 37 lane F, lib/archives/): the same pipeline for a +// copy on archive.today — +// {slug, url: <archive.today copy>} archive.ph/<id>, /<ts>/<page>, /newest/<page> +// {slug, url: <original>, at, source: "archive.today"} the copy nearest `at` (its timemap) +// — through the archive.today client (one stream, an 8 s gap, a 429 stops +// the job and rests the client, a check page is refused or read once through +// the archive session's browser, never solved), on the +// `platform:archive.today` queue. The copy is stored AS SERVED with +// `source` and its URL in capture.json, and unwrapped for the extractors each +// time it is read. A refusal's code is in the result (`refusal`: "excluded" +// for a Wayback 403, "challenge", "rate-limited", …). import path from "node:path"; import { getPaths, type Paths } from "../lib/paths"; @@ -36,17 +48,18 @@ import { getSettings } from "../lib/settings"; import { queueKeyForUrl } from "../lib/platform"; import { waybackPageUrl, waybackRawUrl } from "../lib/wayback"; import { ArchiveOrgRequestError } from "../lib/archiveOrgClient"; -import { - waybackClient as defaultWaybackClient, - WaybackCaptureRefusal, - type WaybackClient, -} from "../lib/waybackClient"; +import { waybackClient as defaultWaybackClient, type WaybackClient } from "../lib/waybackClient"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { isWaybackPagesChannel } from "../lib/waybackPages/config"; -import { isXHostUrl, parsePageCaptureAsk, videoPageOf, type PageCaptureAsk } from "../lib/waybackPages/urls"; +import { isXHostUrl, videoPageOf } from "../lib/waybackPages/urls"; +import { parseArchiveCaptureAsk, type ArchiveCaptureAsk } from "../lib/archives/ask"; +import { unwrapArchiveTodayHtml, mapArchiveTodayMedia } from "../lib/archives/archiveToday"; +import { ARCHIVE_TODAY_QUEUE, ArchiveTodayRequestError, type ArchiveTodayClient } from "../lib/archives/archiveTodayClient"; +import { archiveRefusalOf, archiveTodayClient as defaultArchiveTodayClient, type ArchiveRefusalCode } from "../lib/archives/index"; import { decodeCaptureBody, extractPage } from "../lib/waybackPages/extract"; import { assignPageVersions, draftToPost } from "../lib/waybackPages/toPost"; import { + findStoredCaptureByMemento, hasStoredCapture, pageCaptureDir, readStoredCapture, @@ -67,9 +80,16 @@ type VisibilitySettings = { social?: { x?: { visibility?: unknown } } }; export type ImportPagePlan = { config: ChannelConfig; - ask: PageCaptureAsk; + // Release 37 lane F: the ask names its source ("wayback", or + // "archive.today" — lib/archives/ask.ts). + ask: ArchiveCaptureAsk; }; +// The queue an import of this ask runs on: its source's. +export function importPageQueueOf(ask: Pick<ArchiveCaptureAsk, "source">): string { + return ask.source === "archive.today" ? ARCHIVE_TODAY_QUEUE : WAYBACK_PAGES_QUEUE; +} + // The refusal an X capture meets in this channel, or null. export function xCaptureRefusal( config: ChannelConfig, @@ -89,7 +109,7 @@ export function xCaptureRefusal( // Everything checked before a job: the plan, or the refusal. export async function planImportPage( paths: Paths, - opts: { slug: string; url: string; at?: string; settings?: VisibilitySettings }, + opts: { slug: string; url: string; at?: string; source?: string; settings?: VisibilitySettings }, ): Promise<{ ok: true; plan: ImportPagePlan } | { ok: false; error: string }> { const config = await readChannelConfig(paths, opts.slug); if (!config) return { ok: false, error: `No such channel: ${opts.slug}` }; @@ -99,17 +119,22 @@ export async function planImportPage( error: `${opts.slug} is not a Wayback pages channel; import-page imports into a channel on platform "webpage"`, }; } - const parsed = parsePageCaptureAsk(opts.url, opts.at); + const parsed = parseArchiveCaptureAsk(opts.url, opts.at, opts.source); if (!parsed.ok) return parsed; - const video = videoPageOf(parsed.ask.originalUrl); - if (video) { - return { - ok: false, - error: `${parsed.ask.originalUrl} is a video (${video}), not a page: use import-video for a capture of a video`, - }; + // An archive.today short id names no page: these two are asked again of + // the copy once it is read. + const original = parsed.ask.originalUrl; + if (original) { + const video = videoPageOf(original); + if (video) { + return { + ok: false, + error: `${original} is a video (${video}), not a page: use import-video for a capture of a video`, + }; + } + const x = xCaptureRefusal(config, opts.slug, original, opts.settings ?? getSettings()); + if (x) return { ok: false, error: x }; } - const x = xCaptureRefusal(config, opts.slug, parsed.ask.originalUrl, opts.settings ?? getSettings()); - if (x) return { ok: false, error: x }; return { ok: true, plan: { config, ask: parsed.ask } }; } @@ -131,6 +156,12 @@ export type ImportPageResult = { updated: number; unchanged: number; extractor?: string; + // Release 37 lane F: the source the copy is from ("wayback", + // "archive.today"), the copy's URL there, and — when the source refused — + // the refusal's code ("excluded", "challenge", "rate-limited", …). + source?: string; + mementoUrl?: string; + refusal?: ArchiveRefusalCode; error?: string; }; @@ -141,50 +172,113 @@ export function recordsOfCapture( capture: StoredCapture, body: Buffer, ): { posts: Post[]; extractor: { name: string; version: number }; fallback?: StoredCapture["extractorFallback"] } { - const html = decodeCaptureBody(body, capture.contentType ?? capture.mimetype); + const { input, images, source } = extractInputOfCapture(capture, body); const facts = { originalUrl: capture.originalUrl, captureTs: capture.captureTs, mimetype: capture.mimetype, ...(capture.digest ? { digest: capture.digest } : {}), }; - const res = extractPage({ - html, - capture: { - ...facts, - waybackUrl: waybackPageUrl(facts), - rawUrl: waybackRawUrl(facts), - }, - }); + const res = extractPage(input); const posts = res.drafts.map((d) => - draftToPost(d, { + draftToPost(images ? { ...d, ...(d.media ? { media: mapArchiveTodayMedia(d.media, images) } : {}) } : d, { channelSlug: slug, capture: facts, extractor: res.extractor, ...(res.fallback ? { fallback: res.fallback } : {}), + ...(source ? { source } : {}), }), ); return { posts, extractor: res.extractor, ...(res.fallback ? { fallback: res.fallback } : {}) }; } +// WHAT THE EXTRACTORS READ of a stored capture (release 37 lane F): its body +// decoded and — for a copy from archive.today — unwrapped (its header bar off, +// its rewritten links put back; lib/archives/archiveToday.ts), with the +// capture's provenance. Shared by an import, a re-extract and its staleness +// check. `images`: archive.today's cached copy of each image the copy names. +export function extractInputOfCapture( + capture: StoredCapture, + body: Buffer, +): { + input: { html: string; capture: { originalUrl: string; captureTs: string; mimetype?: string; digest?: string; waybackUrl: string; rawUrl: string } }; + images?: ReadonlyMap<string, string>; + source?: { id: string; mementoUrl: string }; +} { + let html = decodeCaptureBody(body, capture.contentType ?? capture.mimetype); + const facts = { + originalUrl: capture.originalUrl, + captureTs: capture.captureTs, + mimetype: capture.mimetype, + ...(capture.digest ? { digest: capture.digest } : {}), + }; + if (capture.source && capture.source !== "wayback") { + const memento = capture.mementoUrl ?? capture.originalUrl; + let images: ReadonlyMap<string, string> | undefined; + if (capture.source === "archive.today") { + const un = unwrapArchiveTodayHtml(html, memento); + html = un.html; + images = un.images; + } + return { + input: { html, capture: { ...facts, waybackUrl: memento, rawUrl: memento } }, + ...(images ? { images } : {}), + source: { id: capture.source, mementoUrl: memento }, + }; + } + return { input: { html, capture: { ...facts, waybackUrl: waybackPageUrl(facts), rawUrl: waybackRawUrl(facts) } } }; +} + export async function importPage(opts: { paths: Paths; slug: string; url: string; at?: string; + // Release 37 lane F: "archive.today" with a page's own URL and `at`; a + // copy's URL names its source itself. + source?: string; dryRun?: boolean; settings?: VisibilitySettings; client?: WaybackClient; + archiveTodayClient?: ArchiveTodayClient; onLog?: (line: string) => void; signal?: AbortSignal; now?: () => Date; }): Promise<ImportPageResult> { - const log = (line: string) => opts.onLog?.(line); const base: ImportPageResult = { ok: false, slug: opts.slug, url: opts.url, written: 0, updated: 0, unchanged: 0 }; const settings = opts.settings ?? getSettings(); - const planned = await planImportPage(opts.paths, { slug: opts.slug, url: opts.url, at: opts.at, settings }); + const planned = await planImportPage(opts.paths, { slug: opts.slug, url: opts.url, at: opts.at, source: opts.source, settings }); if (!planned.ok) return { ...base, error: planned.error }; - const { config, ask } = planned.plan; + const { ask } = planned.plan; + try { + if (ask.source === "archive.today") return await importArchiveTodayCopy({ ...opts, settings, base, plan: planned.plan }); + return await importWaybackCapture({ ...opts, settings, base, plan: planned.plan }); + } catch (e) { + const refusal = archiveRefusalOf(e); + if (refusal) return { ...base, source: refusal.source, refusal: refusal.code, error: refusal.message }; + if (e instanceof ArchiveOrgRequestError) return { ...base, error: e.message }; + if (e instanceof ArchiveTodayRequestError) return { ...base, source: "archive.today", error: e.message }; + throw e; + } +} + +type ImportCtx = { + paths: Paths; + slug: string; + settings: VisibilitySettings; + base: ImportPageResult; + plan: ImportPagePlan; + dryRun?: boolean; + onLog?: (line: string) => void; + signal?: AbortSignal; + now?: () => Date; +}; + +async function importWaybackCapture(opts: ImportCtx & { client?: WaybackClient }): Promise<ImportPageResult> { + const log = (line: string) => opts.onLog?.(line); + const { base } = opts; + const { config } = opts.plan; + const ask = opts.plan.ask as Extract<ArchiveCaptureAsk, { source: "wayback" }>; const client = opts.client ?? defaultWaybackClient; const channelRoot = path.join(opts.paths.channelsDir, opts.slug); @@ -205,134 +299,247 @@ export async function importPage(opts: { }; } - try { - let ts: string; - // The URL as the archive captured it: CDX's `original` for a nearest - // lookup (it may differ from the one typed: http/https, a trailing slash). - let original = ask.originalUrl; - if (ask.kind === "nearest") { - log(`Looking up the capture of ${ask.originalUrl} nearest ${ask.at} (CDX).`); - const near = await client.closestCapture(ask.originalUrl, ask.at, { signal: opts.signal }); - if (!near) return { ...base, error: `the Wayback Machine holds no capture of ${ask.originalUrl} that recorded a page (HTTP 200)` }; - ts = near.timestamp; - original = near.original; - log(`Nearest capture: ${near.timestamp} (${near.original}).`); - } else { - ts = ask.captureTs; - } - if (/^\d{14}$/.test(ts) && (await hasStoredCapture(channelRoot, ts, original))) { - log(`The capture ${ts} of ${original} is already in ${opts.slug}; nothing fetched.`); - return { - ...base, - ok: true, - already: true, - captureTs: ts, - originalUrl: original, - waybackUrl: waybackPageUrl({ captureTs: ts, originalUrl: original }), - }; - } - log(`Fetching ${waybackRawUrl({ captureTs: ts, originalUrl: original })}`); - const cap = await client.getCapture(ts, original, { raw: true, signal: opts.signal }); - if (cap.finalTs !== ts || cap.originalUrl !== ask.originalUrl) { - log(`The archive answered with the capture ${cap.finalTs} of ${cap.originalUrl}.`); - const video = videoPageOf(cap.originalUrl); - if (video) return { ...base, error: `the capture redirects to a video (${video}, ${cap.originalUrl}): use import-video for it` }; - const x = xCaptureRefusal(config, opts.slug, cap.originalUrl, settings); - if (x) return { ...base, error: x }; - } - const fetchedAt = (opts.now?.() ?? new Date()).toISOString(); - const stored: StoredCapture = { - originalUrl: cap.originalUrl, - captureTs: cap.finalTs, - mimetype: cap.mimetype, - contentType: cap.contentType, - bytes: cap.bytes, - sha256: cap.sha256, - fetchedAt, - extractor: "", - extractorVersion: 0, - ...(cap.finalTs !== ts ? { requestedTs: ts } : {}), - ...(cap.originalUrl !== ask.originalUrl ? { requestedUrl: ask.originalUrl } : {}), + let ts: string; + // The URL as the archive captured it: CDX's `original` for a nearest + // lookup (it may differ from the one typed: http/https, a trailing slash). + let original = ask.originalUrl; + if (ask.kind === "nearest") { + log(`Looking up the capture of ${ask.originalUrl} nearest ${ask.at} (CDX).`); + const near = await client.closestCapture(ask.originalUrl, ask.at, { signal: opts.signal }); + if (!near) return { ...base, error: `the Wayback Machine holds no capture of ${ask.originalUrl} that recorded a page (HTTP 200)` }; + ts = near.timestamp; + original = near.original; + log(`Nearest capture: ${near.timestamp} (${near.original}).`); + } else { + ts = ask.captureTs; + } + if (/^\d{14}$/.test(ts) && (await hasStoredCapture(channelRoot, ts, original))) { + log(`The capture ${ts} of ${original} is already in ${opts.slug}; nothing fetched.`); + return { + ...base, + ok: true, + already: true, + captureTs: ts, + originalUrl: original, + waybackUrl: waybackPageUrl({ captureTs: ts, originalUrl: original }), }; - const made = recordsOfCapture(opts.slug, stored, cap.body); - stored.extractor = made.extractor.name; - stored.extractorVersion = made.extractor.version; - if (made.fallback) { - stored.extractorFallback = made.fallback; - log(`The ${made.fallback.from} extractor failed (${made.fallback.error}); the generic extractor read the page.`); - } - stored.records = made.posts.map((p) => p.id); - const dir = await writeStoredCapture(channelRoot, stored, cap.body); - log(`Stored ${cap.bytes} bytes (${cap.mimetype}) in ${path.relative(opts.paths.channelsDir, dir)}.`); + } + log(`Fetching ${waybackRawUrl({ captureTs: ts, originalUrl: original })}`); + const cap = await client.getCapture(ts, original, { raw: true, signal: opts.signal }); + if (cap.finalTs !== ts || cap.originalUrl !== ask.originalUrl) { + log(`The archive answered with the capture ${cap.finalTs} of ${cap.originalUrl}.`); + const video = videoPageOf(cap.originalUrl); + if (video) return { ...base, error: `the capture redirects to a video (${video}, ${cap.originalUrl}): use import-video for it` }; + const x = xCaptureRefusal(config, opts.slug, cap.originalUrl, opts.settings); + if (x) return { ...base, error: x }; + } + const stored: StoredCapture = { + originalUrl: cap.originalUrl, + captureTs: cap.finalTs, + mimetype: cap.mimetype, + contentType: cap.contentType, + bytes: cap.bytes, + sha256: cap.sha256, + fetchedAt: (opts.now?.() ?? new Date()).toISOString(), + extractor: "", + extractorVersion: 0, + ...(cap.finalTs !== ts ? { requestedTs: ts } : {}), + ...(cap.originalUrl !== ask.originalUrl ? { requestedUrl: ask.originalUrl } : {}), + }; + const res = await storeAndUpsert(opts, stored, cap.body); + return { + ...base, + ...res, + ok: true, + captureTs: cap.finalTs, + originalUrl: cap.originalUrl, + waybackUrl: waybackPageUrl({ captureTs: cap.finalTs, originalUrl: cap.originalUrl }), + }; +} - // Versions of one page: the earliest held capture of the original is the - // one the others are versions of. - const held = (await readAllPosts(channelRoot)).filter((p) => p.page); - const byId = new Map(held.map((p) => [p.id, p])); - for (const p of made.posts) byId.set(p.id, { ...(byId.get(p.id) ?? {}), ...p } as Post); - const versioned = new Map(assignPageVersions([...byId.values()]).map((p) => [p.id, p])); - const own = new Set(made.posts.map((p) => p.id)); - const batch = made.posts.map((p) => { - const v = versioned.get(p.id); - return v ? { ...p, page: v.page } : p; - }); - // Earlier-held versions that now point at a new first capture. - for (const v of versioned.values()) if (!own.has(v.id)) batch.push(v); +// ONE archive.today COPY (release 37 lane F): its URL, or the copy of a page +// nearest a date (one timemap request), then its bytes — through the paced +// archive.today client (one stream, a long gap, a 429 stops the job, a check +// is refused or read once through the archive session's browser). Stored AS +// SERVED (its rewritten snapshot) with `source: "archive.today"` and the +// copy's URL; unwrapped for the extractors each time it is read. +async function importArchiveTodayCopy(opts: ImportCtx & { archiveTodayClient?: ArchiveTodayClient }): Promise<ImportPageResult> { + const log = (line: string) => opts.onLog?.(line); + const base: ImportPageResult = { ...opts.base, source: "archive.today" }; + const { config } = opts.plan; + const ask = opts.plan.ask as Extract<ArchiveCaptureAsk, { source: "archive.today" }>; + const client = opts.archiveTodayClient ?? defaultArchiveTodayClient; + const channelRoot = path.join(opts.paths.channelsDir, opts.slug); - const res = await upsertPosts(channelRoot, batch); - log( - `${made.posts.length} record(s) from the capture (${made.extractor.name} v${made.extractor.version}): ` + - `${res.written} new, ${res.updated} updated, ${res.unchanged} unchanged. The index picks them up on its next build.`, - ); + const storedByMemento = async (mementoUrl: string) => { + const hit = await findStoredCaptureByMemento(channelRoot, mementoUrl); + return hit + ? { + ...base, + ok: true, + already: true, + captureTs: hit.capture.captureTs, + originalUrl: hit.capture.originalUrl, + mementoUrl: hit.capture.mementoUrl ?? mementoUrl, + waybackUrl: hit.capture.mementoUrl ?? mementoUrl, + } + : null; + }; + + if (opts.dryRun) { + const held = ask.kind === "memento" ? await storedByMemento(ask.ref.mementoUrl) : null; return { ...base, ok: true, - captureTs: cap.finalTs, - originalUrl: cap.originalUrl, - waybackUrl: waybackPageUrl({ captureTs: cap.finalTs, originalUrl: cap.originalUrl }), - records: made.posts.map((p) => p.id), - written: res.written, - updated: res.updated, - unchanged: res.unchanged, - extractor: `${made.extractor.name} v${made.extractor.version}`, + dryRun: true, + ...(held ? { already: true, captureTs: held.captureTs } : {}), + wouldFetch: held + ? "nothing (the copy is already stored)" + : ask.kind === "memento" + ? `${client.canonical(ask.ref.mementoUrl)} (archive.today, at its pace)` + : `the archive.today copy of ${ask.originalUrl} nearest ${ask.at} (one timemap request), then the copy`, + ...(ask.originalUrl ? { originalUrl: ask.originalUrl } : {}), }; - } catch (e) { - if (e instanceof WaybackCaptureRefusal) return { ...base, error: e.message }; - if (e instanceof ArchiveOrgRequestError) return { ...base, error: e.message }; - throw e; } + + let memento: string; + if (ask.kind === "nearest") { + log(`Looking up the archive.today copy of ${ask.originalUrl} nearest ${ask.at} (its timemap).`); + const near = await client.closestCapture(ask.originalUrl, ask.at, { signal: opts.signal }); + if (!near) return { ...base, error: `archive.today holds no copy of ${ask.originalUrl}` }; + memento = near.mementoUrl; + log(`Nearest copy: ${near.captureTs} (${near.mementoUrl}).`); + } else { + memento = ask.ref.mementoUrl; + } + const already = await storedByMemento(memento); + if (already) { + log(`The copy ${memento} is already in ${opts.slug}; nothing fetched.`); + return already; + } + log(`Fetching ${client.canonical(memento)} (archive.today).`); + const cap = await client.getCapture(memento, { signal: opts.signal }); + if (cap.viaBrowser) log("archive.today answered with a check; the copy was read through the archive session's headless browser."); + log(`The copy is of ${cap.originalUrl}, captured ${cap.finalTs} (${cap.mementoUrl}).`); + const video = videoPageOf(cap.originalUrl); + if (video) return { ...base, error: `the copy is of a video (${video}, ${cap.originalUrl}): use import-video for it` }; + const x = xCaptureRefusal(config, opts.slug, cap.originalUrl, opts.settings); + if (x) return { ...base, error: x }; + if (await hasStoredCapture(channelRoot, cap.finalTs, cap.originalUrl)) { + log(`A capture of ${cap.originalUrl} at ${cap.finalTs} is already in ${opts.slug}; not stored again.`); + return { ...base, ok: true, already: true, captureTs: cap.finalTs, originalUrl: cap.originalUrl, mementoUrl: cap.mementoUrl, waybackUrl: cap.mementoUrl }; + } + const stored: StoredCapture = { + originalUrl: cap.originalUrl, + captureTs: cap.finalTs, + mimetype: cap.mimetype, + contentType: cap.contentType, + bytes: cap.bytes, + sha256: cap.sha256, + fetchedAt: (opts.now?.() ?? new Date()).toISOString(), + extractor: "", + extractorVersion: 0, + source: "archive.today", + mementoUrl: cap.mementoUrl, + ...(ask.kind === "memento" && client.canonical(ask.ref.mementoUrl) !== cap.mementoUrl ? { requestedUrl: ask.ref.mementoUrl } : {}), + }; + const res = await storeAndUpsert(opts, stored, cap.body); + return { + ...base, + ...res, + ok: true, + captureTs: cap.finalTs, + originalUrl: cap.originalUrl, + mementoUrl: cap.mementoUrl, + waybackUrl: cap.mementoUrl, + }; +} + +// The capture stored, extracted and its records upserted (with versions). +async function storeAndUpsert( + opts: Pick<ImportCtx, "paths" | "slug" | "onLog">, + stored: StoredCapture, + body: Buffer, +): Promise<Pick<ImportPageResult, "records" | "written" | "updated" | "unchanged" | "extractor">> { + const log = (line: string) => opts.onLog?.(line); + const channelRoot = path.join(opts.paths.channelsDir, opts.slug); + const made = recordsOfCapture(opts.slug, stored, body); + stored.extractor = made.extractor.name; + stored.extractorVersion = made.extractor.version; + if (made.fallback) { + stored.extractorFallback = made.fallback; + log(`The ${made.fallback.from} extractor failed (${made.fallback.error}); the generic extractor read the page.`); + } + stored.records = made.posts.map((p) => p.id); + const dir = await writeStoredCapture(channelRoot, stored, body); + log(`Stored ${stored.bytes} bytes (${stored.mimetype}) in ${path.relative(opts.paths.channelsDir, dir)}.`); + + // Versions of one page: the earliest held capture of the original is the + // one the others are versions of. + const held = (await readAllPosts(channelRoot)).filter((p) => p.page); + const byId = new Map(held.map((p) => [p.id, p])); + for (const p of made.posts) byId.set(p.id, { ...(byId.get(p.id) ?? {}), ...p } as Post); + const versioned = new Map(assignPageVersions([...byId.values()]).map((p) => [p.id, p])); + const own = new Set(made.posts.map((p) => p.id)); + const batch = made.posts.map((p) => { + const v = versioned.get(p.id); + return v ? { ...p, page: v.page } : p; + }); + // Earlier-held versions that now point at a new first capture. + for (const v of versioned.values()) if (!own.has(v.id)) batch.push(v); + + const res = await upsertPosts(channelRoot, batch); + log( + `${made.posts.length} record(s) from the capture (${made.extractor.name} v${made.extractor.version}): ` + + `${res.written} new, ${res.updated} updated, ${res.unchanged} unchanged. The index picks them up on its next build.`, + ); + return { + records: made.posts.map((p) => p.id), + written: res.written, + updated: res.updated, + unchanged: res.unchanged, + extractor: `${made.extractor.name} v${made.extractor.version}`, + }; } -// THE JOB: an `import-page` job on the archive.org queue, refused (no job) -// with the plan's sentence. What the channel page's field, the ops action and -// lane B's batch all start. The job's log ends with `@@import-page {…}`. +// THE JOB: an `import-page` job on its source's queue (the archive.org queue +// for the Wayback Machine, `platform:archive.today` for archive.today), +// refused (no job) with the plan's sentence. What the channel page's field, +// the ops action and lane B's batch all start. The job's log ends with +// `@@import-page {…}`. export async function queueImportPage(opts: { paths: Paths; slug: string; url: string; at?: string; + source?: string; requestedBy?: string; settings?: VisibilitySettings; client?: WaybackClient; + archiveTodayClient?: ArchiveTodayClient; onDone?: (result: ImportPageResult) => void; }): Promise<StreamActionResult> { const settings = opts.settings ?? getSettings(); - const planned = await planImportPage(opts.paths, { slug: opts.slug, url: opts.url, at: opts.at, settings }); + const planned = await planImportPage(opts.paths, { slug: opts.slug, url: opts.url, at: opts.at, source: opts.source, settings }); if (!planned.ok) return { ok: false, error: planned.error }; return runManagedFunction({ kind: IMPORT_PAGE_JOB_KIND, - queueKey: WAYBACK_PAGES_QUEUE, + queueKey: importPageQueueOf(planned.plan.ask), paths: opts.paths, channelSlug: opts.slug, fn: async (onLog, signal) => { - onLog(`Import page: ${opts.url}${opts.at ? ` nearest ${opts.at}` : ""} into ${opts.slug}${opts.requestedBy ? ` for ${opts.requestedBy}` : ""}`); + onLog( + `Import page: ${opts.url}${opts.at ? ` nearest ${opts.at}` : ""}${planned.plan.ask.source === "archive.today" ? " (archive.today)" : ""} into ${opts.slug}${opts.requestedBy ? ` for ${opts.requestedBy}` : ""}`, + ); const result = await importPage({ paths: opts.paths, slug: opts.slug, url: opts.url, ...(opts.at ? { at: opts.at } : {}), + ...(opts.source ? { source: opts.source } : {}), settings, ...(opts.client ? { client: opts.client } : {}), + ...(opts.archiveTodayClient ? { archiveTodayClient: opts.archiveTodayClient } : {}), onLog, signal, }); @@ -352,10 +559,13 @@ export class ImportPageRefusal extends Error { // LANE B's DOOR (release 37 S2, "Import selected"): one `import-page` job for // one capture. Throws ImportPageRefusal with the sentence when it is refused. +// Release 37 lane F: `url` may be an archive.today copy's URL, or a page's +// own URL with `at` and `source: "archive.today"`. export async function startImportPageJob(opts: { slug: string; url: string; at?: string; + source?: string; requestedBy?: string; paths?: Paths; }): Promise<{ jobId: string }> { diff --git a/common/controller/reextractPages.ts b/common/controller/reextractPages.ts @@ -22,7 +22,7 @@ import type { Post } from "../lib/posts"; import { readAllPosts, replaceChannelPosts } from "../lib/posts-server"; import { readChannelConfig } from "./channels"; import { isWaybackPagesChannel } from "../lib/waybackPages/config"; -import { chooseExtractor, decodeCaptureBody } from "../lib/waybackPages/extract"; +import { chooseExtractor } from "../lib/waybackPages/extract"; import { asStored, assignPageVersions, mergePageRecord, stableRecordJson } from "../lib/waybackPages/toPost"; import { listStoredCaptures, @@ -30,9 +30,8 @@ import { readStoredCaptureBody, updateStoredCapture, } from "../lib/waybackPages/store-server"; -import { waybackPageUrl, waybackRawUrl } from "../lib/wayback"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; -import { recordsOfCapture, WAYBACK_PAGES_QUEUE } from "./importPage"; +import { extractInputOfCapture, recordsOfCapture, WAYBACK_PAGES_QUEUE } from "./importPage"; export const REEXTRACT_PAGES_JOB_KIND = "reextract-pages"; export const REEXTRACT_PAGES_RESULT_MARKER = "@@reextract-pages "; @@ -96,12 +95,9 @@ export async function reextractPages(opts: { continue; } derivable.add(name); - const html = decodeCaptureBody(body, capture.contentType ?? capture.mimetype); - const facts = { originalUrl: capture.originalUrl, captureTs: capture.captureTs }; - const now = chooseExtractor({ - html, - capture: { ...facts, mimetype: capture.mimetype, waybackUrl: waybackPageUrl(facts), rawUrl: waybackRawUrl(facts) }, - }); + // Release 37 lane F: what the extractors read (an archive.today copy + // unwrapped), as an import reads it. + const now = chooseExtractor(extractInputOfCapture(capture, body).input); const isStale = now.name !== capture.extractor || now.version !== capture.extractorVersion || !!capture.extractorFallback; if (isStale) out.stale++; diff --git a/common/lib/archives/archiveToday.test.ts b/common/lib/archives/archiveToday.test.ts @@ -0,0 +1,140 @@ +// Release 37 lane F: archive.today's answers read — its timemap, a copy's facts, +// its check page, and a copy unwrapped so the extractors read it as they read a +// raw Wayback body: lane C's synthetic tweet and Tumblr pages, wrapped the way +// archive.today wraps a copy, give the SAME records. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/archives/archiveToday.test.ts + +import test from "node:test"; +import assert from "node:assert/strict"; +import { + blockById, + copyFactsFromHeaders, + copyFactsFromHtml, + isArchiveTodayChallenge, + mapArchiveTodayMedia, + nearestCapture, + parseArchiveTodayTimemap, + parseLinkFormat, + unwrapArchiveTodayHtml, + withinCaptureRange, +} from "./archiveToday"; +import { CHALLENGE_HTML, COPIES, wrapLikeArchiveToday, AT_ARTICLE_URL, AT_ARTICLE_ID, AT_ARTICLE_TS } from "../../testing/web/fakeArchiveToday.mjs"; +import { extractPage } from "../waybackPages/extract"; +import { captureOf, fixture } from "../waybackPages/extractors/__fixtures__/capture"; + +test("the timemap's copies, oldest first; URLs with commas survive; the original is rel=original", () => { + const text = [ + `<https://journal.example/a,b.html>; rel="original"`, + `<https://archive.ph/timegate/https://journal.example/a,b.html>; rel="timegate"`, + `<https://archive.ph/timemap/https://journal.example/a,b.html>; rel="self"; type="application/link-format"`, + `<https://archive.ph/Fg7hJ>; rel="last memento"; datetime="Wed, 01 Jan 2020 10:15:00 GMT"`, + `<https://archive.ph/Ab3dE>; rel="first memento"; datetime="Sun, 12 May 2019 08:30:00 GMT"`, + ].join(",\n"); + assert.equal(parseLinkFormat(text).length, 5); + assert.deepEqual(parseArchiveTodayTimemap(text, "https://ignored.example/"), [ + { source: "archive.today", captureTs: "20190512083000", originalUrl: "https://journal.example/a,b.html", mementoUrl: "https://archive.ph/Ab3dE", status: "200", mimetype: "text/html" }, + { source: "archive.today", captureTs: "20200101101500", originalUrl: "https://journal.example/a,b.html", mementoUrl: "https://archive.ph/Fg7hJ", status: "200", mimetype: "text/html" }, + ]); + assert.equal(withinCaptureRange("20190512083000", "2019", "2019"), true); + assert.equal(withinCaptureRange("20200101101500", "2019", "2019"), false); + assert.equal(withinCaptureRange("20190512083000", "201906"), false); + const rows = parseArchiveTodayTimemap(text, ""); + assert.equal(nearestCapture(rows, "20191201")?.mementoUrl, "https://archive.ph/Fg7hJ"); + assert.equal(nearestCapture(rows, "2019")?.mementoUrl, "https://archive.ph/Ab3dE"); + assert.equal(nearestCapture([], "2019"), null); +}); + +test("a copy's facts: from its Memento headers, else from its header bar", () => { + const h = new Headers({ + "memento-datetime": "Sun, 12 May 2019 08:30:00 GMT", + link: `<${AT_ARTICLE_URL}>; rel="original", <https://archive.ph/${AT_ARTICLE_ID}>; rel="memento"; datetime="Sun, 12 May 2019 08:30:00 GMT"`, + }); + assert.deepEqual(copyFactsFromHeaders(h), { captureTs: "20190512083000", originalUrl: AT_ARTICLE_URL }); + const wrapped = wrapLikeArchiveToday(COPIES[0].page(), { id: AT_ARTICLE_ID, original: AT_ARTICLE_URL, timestamp: AT_ARTICLE_TS }); + assert.deepEqual(copyFactsFromHtml(wrapped), { originalUrl: AT_ARTICLE_URL, captureTs: AT_ARTICLE_TS }); + assert.deepEqual(copyFactsFromHtml("<html><body><p>no bar</p></body></html>"), {}); +}); + +test("a check page is told apart from a copy — and a copy OF a page with a captcha form is still a copy", () => { + assert.equal(isArchiveTodayChallenge(CHALLENGE_HTML), true); + assert.equal(isArchiveTodayChallenge("<html><head><title>Just a moment...</title></head><body>Checking your browser</body></html>"), true); + const page = wrapLikeArchiveToday(COPIES[0].page(), { id: AT_ARTICLE_ID, original: AT_ARTICLE_URL, timestamp: AT_ARTICLE_TS }); + assert.equal(isArchiveTodayChallenge(page), false); + const signup = wrapLikeArchiveToday( + '<html><head><title>Sign up</title></head><body><form><div class="g-recaptcha" data-sitekey="k"></div></form><p>Join us.</p></body></html>', + { id: "Zz9yX", original: "https://club.example/signup", timestamp: "20180101000000" }, + ); + assert.equal(isArchiveTodayChallenge(signup), false); +}); + +test("blockById matches its own element's close, not a nested one's, and not a longer id", () => { + const html = '<div id="CONTENTS">no</div><div id="CONTENT"><div><div>in</div></div><p>x</p></div><div>after</div>'; + const b = blockById(html, "CONTENT"); + assert.equal(b?.inner, "<div><div>in</div></div><p>x</p>"); +}); + +test("unwrapped: the bar gone, links out restored to the original, images back to their originals with the cached copies kept", () => { + const wrapped = wrapLikeArchiveToday(COPIES[0].page(), { id: AT_ARTICLE_ID, original: AT_ARTICLE_URL, timestamp: AT_ARTICLE_TS }); + const un = unwrapArchiveTodayHtml(wrapped, `https://archive.ph/${AT_ARTICLE_ID}`); + assert.equal(un.framed, true); + assert.doesNotMatch(un.html, /webpage capture|id="HEADER"|archive\.ph\/o\//); + assert.match(un.html, /<title>Notes I Later Deleted \| Journal<\/title>/); + assert.match(un.html, /property="og:title"/); + assert.doesNotMatch(un.html, /og:url/); + assert.match(un.html, /href="https:\/\/journal\.example\/2019\/05\/minutes\.html"/); + assert.match(un.html, /href="https:\/\/other\.example\/account"/); + assert.match(un.html, /src="https:\/\/journal\.example\/img\/whiteboard\.png"/); + assert.doesNotMatch(un.html, /old-src/); + const cached = un.images.get("https://journal.example/img/whiteboard.png"); + assert.match(String(cached), /^https:\/\/archive\.ph\/Ab3dE\/[0-9a-f]{8}\.png$/); + + // The generic extractor reads it as the page it is, and the record's image + // is archive.today's cached copy — never a Wayback URL it was not checked against. + const res = extractPage({ html: un.html, capture: { ...captureOf(AT_ARTICLE_URL, AT_ARTICLE_TS), mimetype: "text/html" } }); + assert.equal(res.extractor.name, "generic"); + const [draft] = res.drafts; + assert.equal(draft.title, "Notes I Later Deleted"); + assert.equal(draft.author, "Sam Example"); + assert.match(draft.text, /written down the same night/); + assert.doesNotMatch(draft.text, /webpage capture|Saved from/); + assert.deepEqual(draft.links, ["https://journal.example/2019/05/minutes.html", "https://other.example/account"]); + assert.deepEqual(mapArchiveTodayMedia(draft.media, un.images), [{ kind: "image", url: cached, name: "The whiteboard after the meeting" }]); +}); + +test("lane C's tweet and Tumblr pages, wrapped like archive.today, make the same records as raw", () => { + const cases: [string, string, string, string][] = [ + ["x-2016-status.html", "https://twitter.com/TeapotFan/status/697374449464250369", "20160211000000", "x"], + ["tumblr-2012-classic-post.html", "http://teapot-notes.tumblr.com/post/20000000001/on-spouts", "20120601000000", "tumblr"], + ["tumblr-2012-classic-index.html", "http://teapot-notes.tumblr.com/", "20120601000000", "tumblr"], + ]; + for (const [name, url, ts, extractor] of cases) { + const raw = extractPage({ html: fixture(name), capture: captureOf(url, ts) }); + assert.equal(raw.extractor.name, extractor, name); + const wrapped = wrapLikeArchiveToday(fixture(name), { id: "Qr5sT", original: url, timestamp: ts }); + const un = unwrapArchiveTodayHtml(wrapped, "https://archive.ph/Qr5sT"); + const viaArchive = extractPage({ html: un.html, capture: { ...captureOf(url, ts), waybackUrl: "https://archive.ph/Qr5sT", rawUrl: "https://archive.ph/Qr5sT" } }); + assert.equal(viaArchive.extractor.name, extractor, `${name}: the site extractor still claims it`); + assert.equal(viaArchive.fallback, undefined, name); + assert.deepEqual(viaArchive.drafts, raw.drafts, name); + // Each image a record names becomes archive.today's cached copy. + for (const d of viaArchive.drafts) { + for (const m of mapArchiveTodayMedia(d.media, un.images) ?? []) { + assert.match(m.url, /^https:\/\/archive\.ph\/Qr5sT\/|^https?:\/\/(?!web\.archive\.org)/, `${name}: ${m.url}`); + } + } + } +}); + +test("a body that is not archive.today's frame passes through, its links still restored", () => { + const un = unwrapArchiveTodayHtml('<html><body><a href="https://archive.ph/o/Ab3dE/https://a.example/x">x</a></body></html>', "https://archive.ph/Ab3dE"); + assert.equal(un.framed, false); + assert.match(un.html, /href="https:\/\/a\.example\/x"/); +}); + +test("media: a Wayback image form of an uncached original becomes the original", () => { + assert.deepEqual( + mapArchiveTodayMedia([{ kind: "image", url: "https://web.archive.org/web/2019im_/https://journal.example/a.png" }], new Map()), + [{ kind: "image", url: "https://journal.example/a.png" }], + ); +}); diff --git a/common/lib/archives/archiveToday.ts b/common/lib/archives/archiveToday.ts @@ -0,0 +1,318 @@ +// archive.today's ANSWERS, read (release 37 lane F). Pure: no network, no disk, +// no clock — the client (archiveTodayClient.ts) fetches, this reads. +// +// - its TIMEMAP (the Memento protocol's link format) as capture rows; +// - a copy's FACTS from its answer's headers (Memento-Datetime, Link +// rel="original") or, when a copy was read through a browser and has no +// headers, from the copy's own header bar; +// - its CHECK PAGE (a CAPTCHA, "one more step", a browser check) told apart +// from a copy, so a check is a typed refusal and never a parsed record; +// - a copy UNWRAPPED: archive.today serves its snapshot rewritten — its own +// header bar on top, the page inside `#CONTENT`, links out of it as +// `/o/<id>/<url>`, images as its own cached copies (the original kept as +// `old-src` where it keeps it). Unwrapping takes the bar off, puts the +// original hrefs (and image srcs) back, and keeps the title and the page's +// own <meta>s, so the extractors (generic, and the site ones) read it the +// way they read a raw Wayback body. The images a record names afterwards +// are archive.today's cached copies (`mapArchiveTodayMedia`). +// +// The layout is archive.today's as known on 2026-10-20 (no live copy was read +// to write this: synthetic fixtures only). The stored body is the copy AS +// SERVED, so a better unwrap re-derives every record offline (reextract-pages). + +import { isArchiveTodayHost, timestampOfDate, unwrapArchiveTodayOutlink } from "./mementos"; +import { parseWaybackUrl } from "../wayback"; +import type { PostMedia } from "../posts"; +import type { ArchiveCaptureRow } from "./types"; + +// ─── The timemap ─── + +export type LinkEntry = { url: string; params: Record<string, string> }; + +// RFC 6690 link format: `<url>; rel="…"; datetime="…", <url>; …`. URLs may +// hold commas, so entries are read by their `<…>` brackets, not split. +export function parseLinkFormat(text: string): LinkEntry[] { + const out: LinkEntry[] = []; + const re = /<([^>]*)>((?:\s*;\s*[A-Za-z][\w-]*\s*=\s*(?:"[^"]*"|[^;,<]*))*)/g; + for (const m of text.matchAll(re)) { + const params: Record<string, string> = {}; + for (const p of m[2].matchAll(/;\s*([A-Za-z][\w-]*)\s*=\s*(?:"([^"]*)"|([^;,<]*))/g)) { + params[p[1].toLowerCase()] = (p[2] ?? p[3] ?? "").trim(); + } + out.push({ url: m[1].trim(), params }); + } + return out; +} + +const relsOf = (e: LinkEntry) => (e.params.rel ?? "").toLowerCase().split(/\s+/).filter(Boolean); + +// A timemap's copies, oldest first. The original is the entry rel="original" +// (else `fallbackOriginal`). +export function parseArchiveTodayTimemap(text: string, fallbackOriginal: string): ArchiveCaptureRow[] { + const entries = parseLinkFormat(text); + const original = entries.find((e) => relsOf(e).includes("original"))?.url || fallbackOriginal; + const rows: ArchiveCaptureRow[] = []; + const seen = new Set<string>(); + for (const e of entries) { + if (!relsOf(e).includes("memento")) continue; + const ts = timestampOfDate(e.params.datetime); + if (!ts || seen.has(e.url)) continue; + seen.add(e.url); + rows.push({ source: "archive.today", captureTs: ts, originalUrl: original, mementoUrl: e.url, status: "200", mimetype: "text/html" }); + } + return rows.sort((a, b) => a.captureTs.localeCompare(b.captureTs) || a.mementoUrl.localeCompare(b.mementoUrl)); +} + +// The rows within capture-time prefixes `from`/`to` (inclusive), like CDX's. +export function withinCaptureRange(ts: string, from?: string, to?: string): boolean { + if (from && ts.slice(0, from.length) < from) return false; + if (to && ts.slice(0, to.length) > to) return false; + return true; +} + +// A 4–14 digit timestamp as epoch ms (the missing units the start of the +// period); NaN for one that is not a time. +function tsMs(ts: string): number { + const p = ts.padEnd(14, "0"); + return Date.UTC(+p.slice(0, 4), Math.max(0, +p.slice(4, 6) - 1), Math.max(1, +p.slice(6, 8)), +p.slice(8, 10), +p.slice(10, 12), +p.slice(12, 14)); +} + +// The row nearest `at` (4–14 digits) IN TIME — not by the digits, where +// 20191201 is "nearer" 20190512 than 20200101 — the earlier of two as near. +export function nearestCapture<T extends { captureTs: string }>(rows: readonly T[], at: string): T | null { + const want = tsMs(at); + let best: T | null = null; + let bestD = Infinity; + for (const r of rows) { + const d = Math.abs(tsMs(r.captureTs) - want); + if (d < bestD || (d === bestD && best && r.captureTs < best.captureTs)) { + best = r; + bestD = d; + } + } + return best; +} + +// ─── A copy's facts ─── + +export type CopyFacts = { captureTs?: string; originalUrl?: string }; + +// From the answer's headers: Memento-Datetime, and the Link header's +// rel="original". +export function copyFactsFromHeaders(headers: { get(name: string): string | null }): CopyFacts { + const out: CopyFacts = {}; + const ts = timestampOfDate(headers.get("memento-datetime")); + if (ts) out.captureTs = ts; + const link = headers.get("link"); + if (link) { + const orig = parseLinkFormat(link).find((e) => relsOf(e).includes("original"))?.url; + if (orig && /^https?:\/\//i.test(orig)) out.originalUrl = orig; + } + return out; +} + +const attr = (tag: string, name: string): string | undefined => { + const m = new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i").exec(tag); + return m ? decodeEntities(m[1] ?? m[2] ?? m[3] ?? "") : undefined; +}; + +function decodeEntities(s: string): string { + return s + .replace(/&quot;/g, '"') + .replace(/&#39;|&#x27;/gi, "'") + .replace(/&lt;/g, "<") + .replace(/&gt;/g, ">") + .replace(/&amp;/g, "&"); +} + +// From the copy's own header bar (a copy read through a browser has no +// headers): the "saved from" URL box and the capture's <time datetime>. +export function copyFactsFromHtml(html: string): CopyFacts { + const out: CopyFacts = {}; + const header = blockById(html, "HEADER")?.outer ?? ""; + if (!header) return out; + for (const m of header.matchAll(/<input\b[^>]*>/gi)) { + const value = attr(m[0], "value"); + if (value && /^https?:\/\//i.test(value)) { + try { + if (!isArchiveTodayHost(new URL(value).hostname)) { + out.originalUrl = value; + break; + } + } catch { + // not a URL + } + } + } + const time = /<time\b[^>]*\sdatetime\s*=\s*["']([^"']+)["']/i.exec(header)?.[1]; + const ts = timestampOfDate(time); + if (ts) out.captureTs = ts; + return out; +} + +// ─── The check page ─── + +const CHALLENGE_MARKERS: RegExp[] = [ + /\bg-recaptcha\b/i, + /\bh-captcha\b/i, + /hcaptcha\.com\/1\/api\.js/i, + /google\.com\/recaptcha\//i, + /challenges\.cloudflare\.com/i, + /\bcf-chl-/i, + /<title>\s*(?:just a moment|attention required|one more step)/i, + /please complete the security check/i, + /checking (?:if the site connection is secure|your browser)/i, +]; + +// Whether an answer is a CHECK in front of the copy, not the copy: a +// CAPTCHA, a "one more step" page, a browser check. A copy holds archive.today's +// header bar and its content block; a check holds neither. +export function isArchiveTodayChallenge(html: string): boolean { + const head = html.slice(0, 64 * 1024); + if (!CHALLENGE_MARKERS.some((re) => re.test(head))) return false; + // A copy OF a page that itself carried a captcha (a sign-up form) keeps + // archive.today's own frame around it. + return !(blockById(html, "CONTENT") && blockById(html, "HEADER")); +} + +// A short phrase for a check page, for the refusal sentence. +export function challengeDetail(html: string): string { + if (/recaptcha|hcaptcha|h-captcha/i.test(html)) return "a CAPTCHA"; + if (/challenges\.cloudflare\.com|cf-chl-/i.test(html)) return "a browser check"; + return "a check page"; +} + +// ─── Unwrapping ─── + +// The element with `id="<id>"`: its outer HTML, inner HTML and offsets, by +// counting its tag's opens and closes. +export function blockById(html: string, id: string): { outer: string; inner: string; start: number; end: number } | null { + const open = new RegExp(`<([a-zA-Z][\\w-]*)\\b[^>]*\\sid\\s*=\\s*(?:"${id}"|'${id}'|${id}(?=[\\s/>]))[^>]*>`, "i").exec(html); + if (!open) return null; + const tag = open[1].toLowerCase(); + const start = open.index; + const innerStart = start + open[0].length; + const re = new RegExp(`<(/?)${tag}\\b[^>]*>`, "gi"); + re.lastIndex = innerStart; + let depth = 1; + for (let m = re.exec(html); m; m = re.exec(html)) { + if (m[0].endsWith("/>")) continue; + depth += m[1] ? -1 : 1; + if (depth === 0) { + return { outer: html.slice(start, m.index + m[0].length), inner: html.slice(innerStart, m.index), start, end: m.index + m[0].length }; + } + } + return { outer: html.slice(start), inner: html.slice(innerStart), start, end: html.length }; +} + +export type UnwrappedCopy = { + // The copy as a page: <head> with the title and the page's own metas, + // <body> the copied page. + html: string; + // An image's original URL → archive.today's cached copy, for each image the + // copy names both of. + images: Map<string, string>; + // Whether the copy carried archive.today's frame (a body without one is + // passed through as it is). + framed: boolean; +}; + +function absolute(href: string, base: string): string { + try { + return new URL(href, base).toString(); + } catch { + return href; + } +} + +// One tag with its href/src restored: `/o/<id>/<url>` → <url>, `old-href` / +// `old-src` → the attribute, a relative cached image made absolute on the +// copy's host. +function restoreTag(tag: string, mementoUrl: string, images: Map<string, string>): string { + let out = tag; + const name = /^<([a-zA-Z][\w-]*)/.exec(tag)?.[1].toLowerCase() ?? ""; + const oldHref = attr(tag, "old-href"); + const href = attr(tag, "href"); + if (oldHref && /^https?:\/\//i.test(oldHref)) { + out = setAttr(out, "href", oldHref); + } else if (href) { + const un = unwrapArchiveTodayOutlink(href); + if (un !== href) out = setAttr(out, "href", un); + } + if (name === "img" || name === "source") { + const src = attr(tag, "src"); + const oldSrc = attr(tag, "old-src"); + const cached = src ? absolute(src, mementoUrl) : undefined; + if (oldSrc && /^https?:\/\//i.test(oldSrc)) { + out = setAttr(out, "src", oldSrc); + if (cached && cached !== oldSrc) images.set(oldSrc, cached); + } else if (cached && src !== cached) { + out = setAttr(out, "src", cached); + } + } + return out.replace(/\s(?:old-href|old-src)\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, ""); +} + +function setAttr(tag: string, name: string, value: string): string { + const v = value.replace(/&/g, "&amp;").replace(/"/g, "&quot;"); + const re = new RegExp(`(\\s${name}\\s*=\\s*)(?:"[^"]*"|'[^']*'|[^\\s>]+)`, "i"); + if (re.test(tag)) return tag.replace(re, `$1"${v}"`); + return tag.replace(/^(<[a-zA-Z][\w-]*)/, `$1 ${name}="${v}"`); +} + +// The <meta>s of the copy's head that are the PAGE's (archive.today's own — +// anything naming one of its hosts — left out). +function pageMetas(head: string): string[] { + const out: string[] = []; + for (const m of head.matchAll(/<meta\b[^>]*>/gi)) { + const content = attr(m[0], "content") ?? ""; + if (/archive\.(?:ph|today|is|li|vn|fo|md)\b/i.test(content)) continue; + if (/\bhttp-equiv\s*=/i.test(m[0])) continue; + out.push(m[0]); + } + return out; +} + +const SCRIPT_RE = /<script\b[\s\S]*?<\/script\s*>/gi; + +// THE COPY AS A PAGE (see the head of this file). A body that is not an +// archive.today frame (no #CONTENT) keeps its markup, with the hrefs and +// srcs restored all the same. +export function unwrapArchiveTodayHtml(html: string, mementoUrl: string): UnwrappedCopy { + const images = new Map<string, string>(); + const content = blockById(html, "CONTENT"); + const headEnd = /<\/head\s*>/i.exec(html); + const head = headEnd ? html.slice(0, headEnd.index) : ""; + const title = /<title\b[^>]*>([\s\S]*?)<\/title\s*>/i.exec(head || html)?.[1]?.trim() ?? ""; + const restore = (s: string) => s.replace(/<(?:a|area|link|img|source)\b[^>]*>/gi, (tag) => restoreTag(tag, mementoUrl, images)); + if (!content) { + return { html: restore(html), images, framed: false }; + } + const metas = pageMetas(head); + const body = restore(content.inner.replace(SCRIPT_RE, "")); + const out = + "<!doctype html>\n<html><head>" + + '<meta charset="utf-8">' + + (title ? `<title>${title}</title>` : "") + + metas.join("") + + `</head><body>${body}</body></html>`; + return { html: out, images, framed: true }; +} + +// A record's media, as archive.today holds them: an image the copy cached is +// its cached copy (an original the extractor named, or a Wayback form the +// generic extractor gave it), an archive.today URL stays, and a Wayback image +// URL of anything else becomes the original it wraps — a record from +// archive.today links no Wayback copy it was never checked against. +export function mapArchiveTodayMedia(media: PostMedia[] | undefined, images: ReadonlyMap<string, string>): PostMedia[] | undefined { + if (!media) return media; + const out: PostMedia[] = []; + for (const m of media) { + let url = m.url; + const wb = parseWaybackUrl(url); + if (wb) url = wb.originalUrl; + url = images.get(url) ?? url; + if (!out.some((x) => x.url === url && x.kind === m.kind)) out.push({ ...m, url }); + } + return out; +} diff --git a/common/lib/archives/archiveTodayClient.test.ts b/common/lib/archives/archiveTodayClient.test.ts @@ -0,0 +1,231 @@ +// Release 37 lane F: the archive.today client on the fake archive.today — +// timemaps, copies in every URL form, one canonical host, the long gap, a 429 +// that stops and rests the client, a check page refused (never parsed), and a +// check read once more through a (fake) browser. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/archives/archiveTodayClient.test.ts + +import test from "node:test"; +import assert from "node:assert/strict"; +import { + startFakeArchiveToday, + wrapLikeArchiveToday, + CHALLENGE_HTML, + COPIES, + AT_ARTICLE_ID, + AT_ARTICLE_LATER_ID, + AT_ARTICLE_LATER_TS, + AT_ARTICLE_TS, + AT_ARTICLE_URL, + AT_CHECKED_ID, + AT_CHECKED_TS, + AT_CHECKED_URL, +} from "../../testing/web/fakeArchiveToday.mjs"; +import { ArchiveTodayClient, ARCHIVE_TODAY_USER_AGENT, type ArchiveTodayBrowser } from "./archiveTodayClient"; +import { ArchiveRefusal } from "./types"; + +// A clock the client's sleeps move, so the gap is measured, not waited. +function fakeClock() { + let t = 1_000_000; + const sleeps: number[] = []; + return { + now: () => t, + sleep: async (ms: number) => { + sleeps.push(ms); + t += ms; + }, + sleeps, + }; +} + +async function withFake( + opts: Parameters<typeof startFakeArchiveToday>[0], + fn: (at: Awaited<ReturnType<typeof startFakeArchiveToday>>, clock: ReturnType<typeof fakeClock>) => Promise<void>, +) { + const at = await startFakeArchiveToday(opts); + const clock = fakeClock(); + try { + await fn(at, clock); + } finally { + await at.close(); + } +} + +const refusalOf = async (p: Promise<unknown>) => { + try { + await p; + } catch (e) { + if (e instanceof ArchiveRefusal) return e; + throw e; + } + assert.fail("expected a refusal"); +}; + +test("the timemap's copies, oldest first, bounded; a page it holds nothing of is none; the nearest copy", async () => { + await withFake({}, async (at, clock) => { + const c = new ArchiveTodayClient({ fetch: at.fetch, now: clock.now, sleep: clock.sleep, random: () => 0 }); + const rows = await c.listCaptures(AT_ARTICLE_URL); + assert.deepEqual( + rows.map((r) => [r.captureTs, r.mementoUrl]), + [ + [AT_ARTICLE_TS, `https://archive.ph/${AT_ARTICLE_ID}`], + [AT_ARTICLE_LATER_TS, `https://archive.ph/${AT_ARTICLE_LATER_ID}`], + ], + ); + assert.deepEqual((await c.listCaptures(AT_ARTICLE_URL, { from: "2020" })).map((r) => r.captureTs), [AT_ARTICLE_LATER_TS]); + assert.equal((await c.listCaptures(AT_ARTICLE_URL, { limit: 1 })).length, 1); + assert.deepEqual(await c.listCaptures("https://nothing.example/"), []); + assert.equal((await c.closestCapture(AT_ARTICLE_URL, "20191215"))?.mementoUrl, `https://archive.ph/${AT_ARTICLE_LATER_ID}`); + assert.equal(await c.closestCapture("https://nothing.example/", "2019"), null); + assert.ok(at.requests.every((r) => r.ua === ARCHIVE_TODAY_USER_AGENT), "identified on every request"); + }); +}); + +test("one copy by its short id, its time and page from its Memento headers; the bytes as served, the page unwrapped", async () => { + await withFake({}, async (at, clock) => { + const c = new ArchiveTodayClient({ fetch: at.fetch, now: clock.now, sleep: clock.sleep, random: () => 0 }); + const cap = await c.getCapture(`https://archive.is/${AT_ARTICLE_ID}`); + assert.equal(cap.source, "archive.today"); + assert.equal(cap.finalTs, AT_ARTICLE_TS); + assert.equal(cap.originalUrl, AT_ARTICLE_URL); + assert.equal(cap.mementoUrl, `https://archive.ph/${AT_ARTICLE_ID}`); + assert.equal(cap.mimetype, "text/html"); + assert.equal(cap.unwrapped, true); + assert.match(cap.body.toString("utf8"), /id="HEADER"/, "the body is the copy as served"); + assert.doesNotMatch(cap.page, /id="HEADER"/, "the page is unwrapped"); + assert.equal(cap.bytes, cap.body.byteLength); + assert.match(cap.sha256, /^[0-9a-f]{64}$/); + // Asked on archive.ph whatever name the URL used. + assert.deepEqual(at.requests.map((r) => r.path), [`/${AT_ARTICLE_ID}`]); + }); +}); + +test("a timestamp URL, newest and oldest: redirected inside archive.today to the copy", async () => { + await withFake({}, async (at, clock) => { + const c = new ArchiveTodayClient({ fetch: at.fetch, now: clock.now, sleep: clock.sleep, random: () => 0 }); + assert.equal((await c.getCapture(`https://archive.ph/2019.12.20-000000/${AT_ARTICLE_URL}`)).mementoUrl, `https://archive.ph/${AT_ARTICLE_LATER_ID}`); + assert.equal((await c.getCapture(`https://archive.ph/oldest/${AT_ARTICLE_URL}`)).finalTs, AT_ARTICLE_TS); + assert.equal((await c.getCapture(`https://archive.ph/newest/${AT_ARTICLE_URL}`)).finalTs, AT_ARTICLE_LATER_TS); + const none = await refusalOf(c.getCapture("https://archive.ph/Zz0zZ")); + assert.equal(none.code, "not-archived"); + }); +}); + +test("ONE stream, the long gap from the end of one request to the start of the next, jittered", async () => { + await withFake({}, async (at, clock) => { + const c = new ArchiveTodayClient({ fetch: at.fetch, now: clock.now, sleep: clock.sleep, random: () => 0.5 }, { minGapMs: 8_000, jitter: 0.25 }); + await Promise.all([c.listCaptures(AT_ARTICLE_URL), c.getCapture(`https://archive.ph/${AT_ARTICLE_ID}`), c.getCapture(`https://archive.ph/${AT_ARTICLE_LATER_ID}`)]); + assert.equal(c.requests, 3); + // The first request waits for nothing; each later one 8 s × (1 + 0.5 × 0.25). + assert.deepEqual(clock.sleeps, [9_000, 9_000]); + }); +}); + +test("a 429 stops the run with a sentence and rests the client: nothing more is sent until the cool-down ends", async () => { + await withFake({ busyTimes: 1 }, async (at, clock) => { + const c = new ArchiveTodayClient({ fetch: at.fetch, now: clock.now, sleep: clock.sleep, random: () => 0 }, { cooldownMs: 30 * 60_000 }); + const r = await refusalOf(c.getCapture(`https://archive.ph/${AT_ARTICLE_ID}`)); + assert.equal(r.code, "rate-limited"); + assert.match(r.message, /HTTP 429 \(too many requests\).*stopped.*30 min/); + assert.equal(at.requests.length, 1, "no retry of a 429"); + const again = await refusalOf(c.listCaptures(AT_ARTICLE_URL)); + assert.equal(again.code, "rate-limited"); + assert.match(again.message, /was not asked/); + assert.equal(at.requests.length, 1, "nothing sent during the cool-down"); + assert.ok(c.cooldownUntil > clock.now()); + await clock.sleep(31 * 60_000); + assert.equal((await c.listCaptures(AT_ARTICLE_URL)).length, 2); + }); +}); + +test("a check page is a typed refusal and never a record; it names Connect archive session", async () => { + for (const challengeStatus of [200, 429, 503]) { + await withFake({ challenge: [AT_CHECKED_ID], challengeStatus }, async (at, clock) => { + const c = new ArchiveTodayClient({ fetch: at.fetch, now: clock.now, sleep: clock.sleep, random: () => 0 }); + const r = await refusalOf(c.getCapture(`https://archive.ph/${AT_CHECKED_ID}`)); + assert.equal(r.code, "challenge", `status ${challengeStatus}`); + assert.match(r.message, /a CAPTCHA instead of the copy; nothing was read\. Connect archive session/); + assert.equal(c.cooldownUntil, 0, "a check is not a rate limit"); + }); + } +}); + +test("a check read once more through the browser: cleared there, the copy is read from the page; still there, refused", async () => { + await withFake({ challenge: [AT_CHECKED_ID] }, async (at, clock) => { + const wrapped = wrapLikeArchiveToday(COPIES[2].page(), { id: AT_CHECKED_ID, original: AT_CHECKED_URL, timestamp: AT_CHECKED_TS }); + let opened = 0; + let closed = 0; + const cleared = async (): Promise<ArchiveTodayBrowser> => { + opened++; + return { + load: async (url) => ({ html: wrapped, text: "", url }), + close: async () => { + closed++; + }, + }; + }; + const c = new ArchiveTodayClient({ fetch: at.fetch, now: clock.now, sleep: clock.sleep, random: () => 0, openBrowser: cleared }); + const cap = await c.getCapture(`https://archive.ph/${AT_CHECKED_ID}`); + assert.equal(cap.viaBrowser, true); + assert.equal(cap.finalTs, AT_CHECKED_TS, "time read from the copy's header bar"); + assert.equal(cap.originalUrl, AT_CHECKED_URL); + assert.match(cap.page, /A page held behind a check/); + assert.equal(c.browserLoads, 1); + assert.deepEqual([opened, closed], [1, 1], "the browser is closed after the one read"); + + const stillChecked = new ArchiveTodayClient({ + fetch: at.fetch, + now: clock.now, + sleep: clock.sleep, + random: () => 0, + openBrowser: async () => ({ load: async (url) => ({ html: CHALLENGE_HTML, text: "", url }), close: async () => {} }), + }); + const r = await refusalOf(stillChecked.getCapture(`https://archive.ph/${AT_CHECKED_ID}`)); + assert.equal(r.code, "challenge"); + assert.match(r.message, /in the headless browser too/); + + const off = new ArchiveTodayClient({ fetch: at.fetch, now: clock.now, sleep: clock.sleep, random: () => 0, openBrowser: cleared, browserEnabled: () => false }); + assert.equal((await refusalOf(off.getCapture(`https://archive.ph/${AT_CHECKED_ID}`))).code, "challenge"); + assert.equal(opened, 1, "a browser turned off in settings is not opened"); + }); +}); + +test("the canonical host comes from settings; every name is sent there", async () => { + await withFake({}, async (at, clock) => { + const hosts: string[] = []; + const c = new ArchiveTodayClient({ + fetch: (url, init) => { + hosts.push(new URL(url).hostname); + return at.fetch(url, init); + }, + now: clock.now, + sleep: clock.sleep, + random: () => 0, + host: () => "archive.li", + }); + const cap = await c.getCapture(`https://archive.vn/oldest/${AT_ARTICLE_URL}`); + assert.equal(cap.mementoUrl, `https://archive.li/${AT_ARTICLE_ID}`); + assert.deepEqual([...new Set(hosts)], ["archive.li"]); + }); +}); + +test("an answer that is not a page, and one over the cap, are refused", async () => { + const fetchOf = (body: string, type: string) => async () => new Response(body, { status: 200, headers: { "content-type": type, "memento-datetime": "Sun, 12 May 2019 08:30:00 GMT" } }); + const clock = fakeClock(); + const img = new ArchiveTodayClient({ fetch: fetchOf("x", "image/png"), now: clock.now, sleep: clock.sleep }); + assert.equal((await refusalOf(img.getCapture("https://archive.ph/Ab3dE"))).code, "mimetype"); + const big = new ArchiveTodayClient({ fetch: fetchOf("x".repeat(5000), "text/html"), now: clock.now, sleep: clock.sleep }); + assert.equal((await refusalOf(big.getCapture("https://archive.ph/Ab3dE", { maxBytes: 1000 }))).code, "too-large"); + const nameless = new ArchiveTodayClient({ + fetch: async () => new Response("<html><body>a page</body></html>", { status: 200, headers: { "content-type": "text/html" } }), + now: clock.now, + sleep: clock.sleep, + }); + assert.equal((await refusalOf(nameless.getCapture("https://archive.ph/Ab3dE"))).code, "unreadable"); + const away = new ArchiveTodayClient({ + fetch: async () => new Response("", { status: 302, headers: { location: "https://elsewhere.example/" } }), + now: clock.now, + sleep: clock.sleep, + }); + assert.equal((await refusalOf(away.getCapture("https://archive.ph/Ab3dE"))).code, "offsite-redirect"); +}); diff --git a/common/lib/archives/archiveTodayClient.ts b/common/lib/archives/archiveTodayClient.ts @@ -0,0 +1,537 @@ +// THE POLITE archive.today CLIENT (release 37 lane F): every request this app +// makes to archive.today — a page's timemap, one copy's bytes. archive.today is +// one person's service and says so; the rules here are the operator's "polite +// scraping", made mechanical: +// +// ONE AT A TIME requests are chained: a second caller waits for the first +// to finish, and then for the gap. +// A LONG GAP at least `minGapMs` (8 s; settings.archives) between the +// end of one request and the start of the next, plus up to +// a quarter more at random. +// IDENTIFIED a User-Agent naming the project and its URL. +// STOPS AT A 429 "too many requests" is not waited out and retried: the +// run stops with a sentence (ArchiveRefusal +// "rate-limited"), and the client sends NOTHING to +// archive.today for `cooldownMs` (30 min) or the +// Retry-After, whichever is longer. A 502/503/504 (or a +// dropped connection) is retried after an exponential +// wait, a few times. +// NEVER SOLVES archive.today often answers a client that is not a +// browser with a check (a CAPTCHA, a browser check). That +// is told apart from a copy (lib/archives/archiveToday.ts +// isArchiveTodayChallenge) and never parsed as one. With a +// browser (`openBrowser`), the copy is read once more +// through the headless browser on the archive session's +// profile — a check the operator cleared in Connect +// archive session stays cleared there — and a check that +// still stands is refused ("challenge"). Nothing is ever +// clicked or answered by code. +// +// Every URL is sent to ONE canonical host (settings.archives.archiveTodayHost, +// default archive.ph), whichever of archive.today's names a copy's URL used. + +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { PROJECT_NAME, PROJECT_URL } from "../project"; +import { bareMimetype, isPageMimetype, PAGE_MIMETYPES } from "../waybackPages/urls"; +import { + archiveTodayHostOf, + isArchiveTodayHost, + parseArchiveTodayUrl, +} from "./mementos"; +import { + challengeDetail, + copyFactsFromHeaders, + copyFactsFromHtml, + isArchiveTodayChallenge, + nearestCapture, + parseArchiveTodayTimemap, + unwrapArchiveTodayHtml, + withinCaptureRange, +} from "./archiveToday"; +import { ArchiveRefusal, type ArchiveCaptureRow, type ArchiveMementoRef, type ArchiveRawCapture } from "./types"; + +export const ARCHIVE_TODAY_QUEUE = "platform:archive.today"; +export const ARCHIVE_TODAY_USER_AGENT = `${PROJECT_NAME} archive.today import (+${PROJECT_URL})`; +export const ARCHIVE_TODAY_MAX_REDIRECTS = 5; +// A copy's body is read up to this (the Wayback page cap's size). +export const ARCHIVE_TODAY_PAGE_MAX_BYTES = 2 * 1024 * 1024; +// A non-200 answer's body is read this far (enough to tell a check page). +const ERROR_BODY_BYTES = 256 * 1024; + +const PAGE_ACCEPT = "text/html,application/xhtml+xml;q=0.9,*/*;q=0.1"; +const RETRYABLE = new Set([502, 503, 504]); + +// The connect sentence every challenge refusal ends with. +export const CONNECT_ARCHIVE_SESSION_HINT = + "Connect archive session (the channel page's Archived pages panel, or Settings), pass the check once in the window, then try again"; + +export class ArchiveTodayRequestError extends Error { + readonly status: number | null; + constructor(message: string, status: number | null) { + super(message); + this.name = "ArchiveTodayRequestError"; + this.status = status; + } +} + +// What the headless browser hands back for one URL. +export type ArchiveTodayBrowserLoad = { html: string; text: string; url: string; status?: number }; +export type ArchiveTodayBrowser = { + load(url: string, signal?: AbortSignal): Promise<ArchiveTodayBrowserLoad>; + close(): Promise<void>; +}; + +export type ArchiveTodayClientDeps = { + fetch?: (url: string, init: RequestInit) => Promise<Response>; + now?: () => number; + sleep?: (ms: number, signal?: AbortSignal) => Promise<void>; + random?: () => number; + // The headless browser on the archive session's profile, opened only when a + // check stands in the way; null/absent = refuse at the check. + openBrowser?: (() => Promise<ArchiveTodayBrowser>) | null; + // Read per check: false = refuse at the check (settings can change while + // the editor runs). + browserEnabled?: () => boolean; + // The canonical host, read per request (settings can change while the + // editor runs). + host?: () => string; +}; + +export type ArchiveTodayClientOpts = { + minGapMs?: number | (() => number); + // Up to this fraction of the gap again, at random. + jitter?: number; + cooldownMs?: number | (() => number); + maxAttempts?: number; + baseBackoffMs?: number; + maxBackoffMs?: number; + timeoutMs?: number; +}; + +type Answer = { + status: number; + headers: Headers; + location: string | null; + body: Buffer | null; + bytes: number; + tooLarge: boolean; + url: string; +}; + +function defaultSleep(ms: number, signal?: AbortSignal): Promise<void> { + return new Promise((resolve, reject) => { + if (signal?.aborted) return reject(signal.reason ?? new Error("aborted")); + const t = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, ms); + const onAbort = () => { + clearTimeout(t); + reject(signal?.reason ?? new Error("aborted")); + }; + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} + +function retryAfterMs(value: string | null, nowMs: number): number | null { + if (!value) return null; + const v = value.trim(); + if (/^\d+$/.test(v)) return Number(v) * 1000; + const at = Date.parse(v); + return Number.isFinite(at) ? Math.max(0, at - nowMs) : null; +} + +const minutes = (ms: number) => Math.max(1, Math.round(ms / 60_000)); + +export class ArchiveTodayClient { + private readonly deps: Required<Omit<ArchiveTodayClientDeps, "openBrowser" | "host" | "browserEnabled">> & + Pick<ArchiveTodayClientDeps, "openBrowser" | "host" | "browserEnabled">; + private readonly opts: Required<Omit<ArchiveTodayClientOpts, "minGapMs" | "cooldownMs">> & { + minGapMs: () => number; + cooldownMs: () => number; + }; + private chain: Promise<unknown> = Promise.resolve(); + private lastDoneAt = -Infinity; + private coolUntil = 0; + // Requests actually sent (each attempt), and copies read through the + // browser — for tests and logs. + requests = 0; + browserLoads = 0; + + constructor(deps: ArchiveTodayClientDeps = {}, opts: ArchiveTodayClientOpts = {}) { + this.deps = { + fetch: deps.fetch ?? ((url, init) => fetch(url, init)), + now: deps.now ?? (() => Date.now()), + sleep: deps.sleep ?? defaultSleep, + random: deps.random ?? Math.random, + ...(deps.openBrowser ? { openBrowser: deps.openBrowser } : {}), + ...(deps.host ? { host: deps.host } : {}), + ...(deps.browserEnabled ? { browserEnabled: deps.browserEnabled } : {}), + }; + const gap = opts.minGapMs ?? 8_000; + const cool = opts.cooldownMs ?? 30 * 60_000; + this.opts = { + minGapMs: typeof gap === "function" ? gap : () => gap, + cooldownMs: typeof cool === "function" ? cool : () => cool, + jitter: opts.jitter ?? 0.25, + maxAttempts: opts.maxAttempts ?? 3, + baseBackoffMs: opts.baseBackoffMs ?? 10_000, + maxBackoffMs: opts.maxBackoffMs ?? 120_000, + timeoutMs: opts.timeoutMs ?? 60_000, + }; + } + + get host(): string { + return archiveTodayHostOf(this.deps.host?.() ?? undefined); + } + + // When the client will next send a request after a 429 (epoch ms), or 0. + get cooldownUntil(): number { + return this.coolUntil > this.deps.now() ? this.coolUntil : 0; + } + + // Any archive.today URL on the canonical host. + canonical(url: string): string { + const u = new URL(url); + if (isArchiveTodayHost(u.hostname)) { + u.hostname = this.host; + u.protocol = "https:"; + u.port = ""; + } + return u.toString(); + } + + private serial<T>(fn: () => Promise<T>): Promise<T> { + const run = this.chain.then(fn, fn); + this.chain = run.catch(() => {}); + return run; + } + + private assertNotCooling(url: string): void { + const now = this.deps.now(); + if (this.coolUntil > now) { + throw new ArchiveRefusal( + "archive.today", + "rate-limited", + `archive.today answered "too many requests" earlier; nothing is sent to it before ${new Date(this.coolUntil).toISOString()} ` + + `(${minutes(this.coolUntil - now)} min) — ${url} was not asked`, + { retryAt: this.coolUntil }, + ); + } + } + + private async waitGap(signal?: AbortSignal): Promise<void> { + const gap = this.opts.minGapMs() * (1 + this.deps.random() * this.opts.jitter); + const wait = this.lastDoneAt + gap - this.deps.now(); + if (wait > 0) await this.deps.sleep(Math.round(wait), signal); + } + + // ONE GET (no redirect followed), the gap before it, its body read up to + // `maxBytes` (an error answer's to 256 KB). 502/503/504 and a dropped + // connection are retried; a 429 that is not a check page starts the + // cool-down and throws. Every other status is answered for the caller. + private async send(url: string, o: { accept: string; maxBytes: number; signal?: AbortSignal }): Promise<Answer> { + let lastError = ""; + for (let attempt = 1; attempt <= this.opts.maxAttempts; attempt++) { + this.assertNotCooling(url); + await this.waitGap(o.signal); + this.requests++; + let res: Response | null = null; + let answer: Answer | null = null; + try { + const timeout = AbortSignal.timeout(this.opts.timeoutMs); + res = await this.deps.fetch(url, { + signal: o.signal ? AbortSignal.any([o.signal, timeout]) : timeout, + redirect: "manual", + headers: { accept: o.accept, "user-agent": ARCHIVE_TODAY_USER_AGENT }, + }); + answer = await readAnswer(res, url, res.status >= 200 && res.status < 300 ? o.maxBytes : ERROR_BODY_BYTES); + } catch (err) { + if (o.signal?.aborted) throw err; + lastError = (err as Error).message; + } finally { + this.lastDoneAt = this.deps.now(); + } + if (answer) { + if (answer.status === 429 && !(answer.body && isArchiveTodayChallenge(answer.body.toString("utf8")))) { + const wait = Math.max(this.opts.cooldownMs(), retryAfterMs(answer.headers.get("retry-after"), this.deps.now()) ?? 0); + this.coolUntil = this.deps.now() + wait; + throw new ArchiveRefusal( + "archive.today", + "rate-limited", + `archive.today answered HTTP 429 (too many requests) for ${url}; stopped, and nothing is sent to it for ` + + `${minutes(wait)} min (until ${new Date(this.coolUntil).toISOString()})`, + { retryAt: this.coolUntil }, + ); + } + if (!RETRYABLE.has(answer.status) || (answer.body && isArchiveTodayChallenge(answer.body.toString("utf8")))) return answer; + lastError = `HTTP ${answer.status}`; + } + if (attempt === this.opts.maxAttempts) break; + const exp = Math.min(this.opts.maxBackoffMs, this.opts.baseBackoffMs * 2 ** (attempt - 1)); + await this.deps.sleep(Math.round(exp * (1 + (this.deps.random() * 0.4 - 0.2))), o.signal); + } + throw new ArchiveTodayRequestError( + `archive.today did not answer ${url} after ${this.opts.maxAttempts} attempts (${lastError}); stopping`, + null, + ); + } + + // The same URL through the headless browser, in the chain and after the + // gap. Null when no browser is offered. + private async viaBrowser(url: string, signal?: AbortSignal): Promise<ArchiveTodayBrowserLoad | null> { + if (!this.deps.openBrowser || this.deps.browserEnabled?.() === false) return null; + this.assertNotCooling(url); + await this.waitGap(signal); + this.browserLoads++; + let browser: ArchiveTodayBrowser | null = null; + try { + browser = await this.deps.openBrowser(); + return await browser.load(url, signal); + } finally { + await browser?.close().catch(() => {}); + this.lastDoneAt = this.deps.now(); + } + } + + private challengeRefusal(url: string, html: string, triedBrowser: boolean): ArchiveRefusal { + return new ArchiveRefusal( + "archive.today", + "challenge", + `archive.today answered ${url} with ${challengeDetail(html)} instead of the copy` + + (triedBrowser ? ", in the headless browser too" : "") + + `; nothing was read. ${CONNECT_ARCHIVE_SESSION_HINT}`, + ); + } + + // THE COPIES OF A PAGE, oldest first: its timemap + // (`/timemap/<original>`, one request). A 404 is "none". Within + // `from`/`to` (capture-time prefixes), at most `limit`. + listCaptures( + originalUrl: string, + o: { from?: string; to?: string; limit?: number; signal?: AbortSignal } = {}, + ): Promise<ArchiveCaptureRow[]> { + return this.serial(async () => { + const url = `https://${this.host}/timemap/${originalUrl}`; + const res = await this.send(url, { accept: "application/link-format,text/plain;q=0.9,*/*;q=0.1", maxBytes: 8 * 1024 * 1024, signal: o.signal }); + let text: string; + if (res.status === 404 || res.status === 410) return []; + const body = res.body?.toString("utf8") ?? ""; + if (isArchiveTodayChallenge(body)) { + const b = await this.viaBrowser(url, o.signal); + if (!b || isArchiveTodayChallenge(b.html)) throw this.challengeRefusal(url, b?.html ?? body, !!b); + text = b.text; + } else if (res.status >= 200 && res.status < 300) { + if (res.tooLarge) throw new ArchiveTodayRequestError(`archive.today's timemap of ${originalUrl} is over 8 MB; not read`, res.status); + text = body; + } else { + throw new ArchiveTodayRequestError(`archive.today answered HTTP ${res.status} for ${url}`, res.status); + } + const rows = parseArchiveTodayTimemap(text, originalUrl) + .map((r) => ({ ...r, mementoUrl: this.canonical(r.mementoUrl) })) + .filter((r) => withinCaptureRange(r.captureTs, o.from, o.to)); + return o.limit ? rows.slice(0, o.limit) : rows; + }); + } + + // The copy nearest `at` (4–14 digits) — one timemap request — or null. + async closestCapture(url: string, at: string, o: { signal?: AbortSignal } = {}): Promise<ArchiveCaptureRow | null> { + return nearestCapture(await this.listCaptures(url, { signal: o.signal }), at); + } + + // ONE COPY: its bytes as served (what a page import stores), and the copy + // unwrapped as a page (`page`, what the extractors read). A memento URL in + // any of its forms; redirects followed inside archive.today only (a + // `/<ts>/<url>`, `/newest/` or `/oldest/` answer is a redirect to the copy), + // at most ARCHIVE_TODAY_MAX_REDIRECTS. The copy's time and page come from + // the answer's Memento headers, else its header bar, else the URL. + // Refused (ArchiveRefusal): no such copy ("not-archived"); a check that + // stands ("challenge"); not HTML ("mimetype"); over `maxBytes` + // ("too-large"); off archive.today or round in circles; no time or page + // to name it by ("unreadable"); a 429 ("rate-limited"). + getCapture( + memento: string | ArchiveMementoRef, + o: { maxBytes?: number; signal?: AbortSignal } = {}, + ): Promise<ArchiveRawCapture> { + return this.serial(async () => { + const maxBytes = o.maxBytes ?? ARCHIVE_TODAY_PAGE_MAX_BYTES; + const ref = typeof memento === "string" ? parseArchiveTodayUrl(memento, this.host) : memento; + if (!ref) { + throw new ArchiveRefusal("archive.today", "not-archived", `${String(memento)} is not an archive.today copy's URL`); + } + let at = this.canonical(ref.mementoUrl); + const seen = new Set<string>(); + for (let hop = 0; hop <= ARCHIVE_TODAY_MAX_REDIRECTS; hop++) { + seen.add(at); + const res = await this.send(at, { accept: PAGE_ACCEPT, maxBytes, signal: o.signal }); + if (res.status >= 300 && res.status < 400) { + const next = res.location; + let host = ""; + try { + host = next ? new URL(next).hostname : ""; + } catch { + host = ""; + } + if (!next || !isArchiveTodayHost(host)) { + throw new ArchiveRefusal( + "archive.today", + "offsite-redirect", + `archive.today answered ${at} with a redirect off archive.today (${next ?? "no URL"}); only its own are followed`, + ); + } + at = this.canonical(next); + if (seen.has(at)) throw new ArchiveRefusal("archive.today", "redirect-loop", `archive.today redirects ${ref.mementoUrl} in a loop (${at})`); + continue; + } + const text = res.body?.toString("utf8") ?? ""; + if (res.body && isArchiveTodayChallenge(text)) { + const b = await this.viaBrowser(at, o.signal); + if (!b || isArchiveTodayChallenge(b.html)) throw this.challengeRefusal(at, b?.html ?? text, !!b); + return this.copyOf(Buffer.from(b.html, "utf8"), "text/html; charset=utf-8", b.url && isArchiveTodayHost(safeHost(b.url)) ? this.canonical(b.url) : at, null, ref, true); + } + if (res.status === 404 || res.status === 410) { + throw new ArchiveRefusal("archive.today", "not-archived", `archive.today holds no copy at ${at}`); + } + if (res.status < 200 || res.status >= 300) { + throw new ArchiveTodayRequestError(`archive.today answered HTTP ${res.status} for ${at}`, res.status); + } + const contentType = res.headers.get("content-type") ?? "text/html"; + if (!isPageMimetype(contentType) || bareMimetype(contentType) !== "text/html") { + throw new ArchiveRefusal( + "archive.today", + "mimetype", + `archive.today's answer for ${at} is ${bareMimetype(contentType) || "of no stated type"}, not a copied page (${PAGE_MIMETYPES[0]})`, + ); + } + if (res.tooLarge || !res.body) { + throw new ArchiveRefusal("archive.today", "too-large", `archive.today's copy at ${at} is over ${Math.round(maxBytes / 1024)} KB; not read`); + } + return this.copyOf(res.body, contentType, at, res.headers, ref, false); + } + throw new ArchiveRefusal("archive.today", "redirect-loop", `archive.today redirected ${ref.mementoUrl} more than ${ARCHIVE_TODAY_MAX_REDIRECTS} times`); + }); + } + + private copyOf( + body: Buffer, + contentType: string, + finalUrl: string, + headers: Headers | null, + ref: ArchiveMementoRef, + viaBrowser: boolean, + ): ArchiveRawCapture { + const html = body.toString("utf8"); + const fromHeaders = headers ? copyFactsFromHeaders(headers) : {}; + const fromHtml = copyFactsFromHtml(html); + const finalRef = parseArchiveTodayUrl(finalUrl, this.host); + const captureTs = fromHeaders.captureTs ?? fromHtml.captureTs ?? (finalRef?.captureTs?.length === 14 ? finalRef.captureTs : undefined) ?? (ref.captureTs?.length === 14 ? ref.captureTs : undefined); + const originalUrl = fromHeaders.originalUrl ?? fromHtml.originalUrl ?? finalRef?.originalUrl ?? ref.originalUrl; + if (!captureTs || !originalUrl) { + throw new ArchiveRefusal( + "archive.today", + "unreadable", + `archive.today's answer for ${finalUrl} names no ${!captureTs ? "capture time" : "page"} (no Memento headers, no header bar)`, + ); + } + // A copy is named by its short id when the answer gives one. + const mementoUrl = finalRef?.id ? finalRef.mementoUrl : (headers ? mementoOfLink(headers, this) : null) ?? finalUrl; + const page = unwrapArchiveTodayHtml(html, mementoUrl).html; + return { + source: "archive.today", + body, + mimetype: bareMimetype(contentType) || "text/html", + contentType, + finalTs: captureTs, + originalUrl, + mementoUrl, + bytes: body.byteLength, + sha256: createHash("sha256").update(body).digest("hex"), + unwrapped: true, + page, + ...(viaBrowser ? { viaBrowser: true } : {}), + }; + } +} + +function safeHost(url: string): string { + try { + return new URL(url).hostname; + } catch { + return ""; + } +} + +// The Link header's rel="memento" self link (a copy answered at its timestamp +// URL names its short-id URL there), on the canonical host. +function mementoOfLink(headers: Headers, client: ArchiveTodayClient): string | null { + const link = headers.get("link"); + if (!link) return null; + const m = /<([^>]+)>\s*;[^,]*\brel\s*=\s*"?[^",]*\bmemento\b/i.exec(link); + if (!m) return null; + const ref = parseArchiveTodayUrl(m[1], client.host); + return ref?.id ? ref.mementoUrl : null; +} + +async function readAnswer(res: Response, url: string, maxBytes: number): Promise<Answer> { + const base = { status: res.status, headers: res.headers, url }; + if (res.status >= 300 && res.status < 400) { + await res.body?.cancel().catch(() => {}); + const loc = res.headers.get("location"); + let location: string | null = null; + if (loc) { + try { + location = new URL(loc, url).toString(); + } catch { + location = null; + } + } + return { ...base, location, body: null, bytes: 0, tooLarge: false }; + } + const declared = Number(res.headers.get("content-length")); + if (Number.isFinite(declared) && declared > maxBytes && res.status >= 200 && res.status < 300) { + await res.body?.cancel().catch(() => {}); + return { ...base, location: null, body: null, bytes: declared, tooLarge: true }; + } + const reader = res.body?.getReader(); + const chunks: Buffer[] = []; + let bytes = 0; + if (reader) { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + bytes += value.byteLength; + if (bytes > maxBytes) { + await reader.cancel().catch(() => {}); + if (res.status >= 200 && res.status < 300) return { ...base, location: null, body: null, bytes, tooLarge: true }; + break; + } + chunks.push(Buffer.from(value)); + } + } + return { ...base, location: null, body: Buffer.concat(chunks), bytes, tooLarge: false }; +} + +// TEST-ONLY: E2E_ARCHIVE_TODAY_ORIGIN_FILE names a file holding ONE loopback +// origin; while it exists, the process's archive.today client sends every +// request for any archive.today host there — the fake archive.today a spec +// starts (common/testing/web/fakeArchiveToday.mjs) — and opens no browser. +// Anything but a loopback origin is ignored. +const LOOPBACK_ORIGIN = /^http:\/\/(?:127\.0\.0\.1|localhost)(?::\d{1,5})?$/; + +export function archiveTodayTestOrigin(env: Readonly<Record<string, string | undefined>> = process.env): string | null { + const file = env.E2E_ARCHIVE_TODAY_ORIGIN_FILE; + if (!file) return null; + let origin = ""; + try { + origin = readFileSync(file, "utf8").trim().replace(/\/$/, ""); + } catch { + return null; + } + return LOOPBACK_ORIGIN.test(origin) ? origin : null; +} + +export function processArchiveTodayFetch(url: string, init: RequestInit): Promise<Response> { + const origin = archiveTodayTestOrigin(); + return fetch(origin ? url.replace(/^https?:\/\/(?:www\.)?archive\.(?:ph|today|is|li|vn|fo|md)/, origin) : url, init); +} diff --git a/common/lib/archives/archiveTodaySession.ts b/common/lib/archives/archiveTodaySession.ts @@ -0,0 +1,205 @@ +// THE ARCHIVE SESSION (release 37 lane F): one persistent Chromium profile for +// archive.today, opened HEADLESS by the client when archive.today answers a +// plain request with a check, and HEADED by Connect archive session. +// +// The forum browser's model (social/forumSession.ts), for one service: a check +// a person passes once in a real window sets a clearance cookie the profile +// keeps, so later reads through the headless profile go through. A window +// opens only on the operator's explicit action (the channel page's Archived +// pages panel, or Settings), never from a job; the headless read waits a check +// out (its own script may clear it) and never clicks, types or solves +// anything. A check that still stands is refused with a sentence. +// +// Layout: transcripts/.archive-session/archive.today/profile/ (the profile), +// transcripts/.archive-session/archive.today/session.json (the last Connect). + +import path from "node:path"; +import { mkdir, stat } from "node:fs/promises"; +import type { Paths } from "../paths"; +import { readJsonFile, writeJsonAtomic } from "../jsonFile-server"; +import { importPlaywright, type BrowserContextLike, type ChromiumLike, type PageLike } from "../../social/playwrightRuntime"; +import { openForumProfile } from "../../social/forumSession"; +import { buildXBrowserLaunchOptions, describeXBrowser, findXBrowser, writeXBrowserRecord } from "../../social/xBrowser"; +import { isArchiveTodayChallenge } from "./archiveToday"; +import type { ArchiveTodayBrowser, ArchiveTodayBrowserLoad } from "./archiveTodayClient"; + +export const ARCHIVE_SESSION_SERVICE = "archive.today"; + +export function archiveSessionDir(paths: Pick<Paths, "transcriptsDir">): string { + return path.join(paths.transcriptsDir, ".archive-session", ARCHIVE_SESSION_SERVICE); +} + +export function archiveProfileDir(paths: Pick<Paths, "transcriptsDir">): string { + return path.join(archiveSessionDir(paths), "profile"); +} + +export type ArchiveSessionRecord = { + service: string; + host: string; + connectedAt: string; + // The window's last look before it closed: was a page showing that is not a + // check, and how many cookies archive.today had set. + cleared: boolean; + cookies: number; + browser?: string; +}; + +export type ArchiveSessionStatus = { + service: string; + hasProfile: boolean; + lastConnect?: ArchiveSessionRecord; +}; + +export async function readArchiveSessionStatus(paths: Pick<Paths, "transcriptsDir">): Promise<ArchiveSessionStatus> { + const dir = archiveSessionDir(paths); + const hasProfile = await stat(path.join(dir, "profile")).then(() => true, () => false); + const read = await readJsonFile(path.join(dir, "session.json")); + const rec = read.ok ? (read.value as ArchiveSessionRecord | null) : null; + return { + service: ARCHIVE_SESSION_SERVICE, + hasProfile, + ...(rec && typeof rec.connectedAt === "string" ? { lastConnect: rec } : {}), + }; +} + +const firstLine = (err: unknown) => ((err as Error)?.message ?? String(err)).split("\n")[0]; +const OUTER_HTML = "document.documentElement ? document.documentElement.outerHTML : ''"; +const INNER_TEXT = "document.body ? document.body.innerText : ''"; + +export const ARCHIVE_CHALLENGE_WAIT_MS = 45_000; + +// Go to `url` and read what the page shows, waiting a check out (up to +// `timeoutMs`; its own script may clear it and reload). Nothing is clicked. +export async function loadArchivePage( + page: PageLike, + url: string, + o: { signal?: AbortSignal; timeoutMs?: number; pollMs?: number; now?: () => number; onLog?: (l: string) => void } = {}, +): Promise<ArchiveTodayBrowserLoad> { + const now = o.now ?? Date.now; + let status: number | undefined; + try { + const res = (await page.goto(url, { waitUntil: "domcontentloaded", timeout: 60_000 })) as { status?: () => number } | null; + status = typeof res?.status === "function" ? res.status() : undefined; + } catch (err) { + if (!/interrupted|ERR_ABORTED|frame was detached/i.test(firstLine(err))) throw new Error(`Could not load ${url}: ${firstLine(err)}`); + } + const read = async () => { + try { + return { html: String(await page.evaluate(OUTER_HTML)), text: String(await page.evaluate(INNER_TEXT)) }; + } catch { + return null; + } + }; + let got = (await read()) ?? { html: "", text: "" }; + if (isArchiveTodayChallenge(got.html)) { + o.onLog?.(`archive.today showed a check in the headless browser; waiting up to ${Math.round((o.timeoutMs ?? ARCHIVE_CHALLENGE_WAIT_MS) / 1000)} s for it to clear by itself.`); + const started = now(); + while (now() - started < (o.timeoutMs ?? ARCHIVE_CHALLENGE_WAIT_MS)) { + if (o.signal?.aborted) break; + await page.waitForTimeout(o.pollMs ?? 2_000); + const next = await read(); + if (!next) continue; + got = next; + if (!isArchiveTodayChallenge(got.html)) break; + } + } + let href = url; + try { + const h = String(await page.evaluate("location.href")); + if (h && h !== "about:blank") href = h; + } catch { + // keep the asked URL + } + return { ...got, url: href, ...(status !== undefined ? { status } : {}) }; +} + +// The client's `openBrowser`: the archive profile, headless, one page; closed +// by the client after the one read. +export function archiveSessionBrowser( + paths: Pick<Paths, "transcriptsDir">, + o: { onLog?: (l: string) => void; chromium?: ChromiumLike; timeoutMs?: number } = {}, +): () => Promise<ArchiveTodayBrowser> { + return async () => { + const context: BrowserContextLike = await openForumProfile(archiveProfileDir(paths), { onLog: o.onLog, chromium: o.chromium }); + const page = context.pages()[0] ?? (await context.newPage()); + return { + load: (url, signal) => loadArchivePage(page, url, { signal, onLog: o.onLog, timeoutMs: o.timeoutMs }), + close: () => context.close(), + }; + }; +} + +// CONNECT: a HEADED window on the archive profile at `url` (archive.today's +// front page by default), on the display of the machine running the editor, +// for the operator to pass the check once and close it. Resolves when the +// window closes, with its last look. +export async function connectArchiveSession( + paths: Pick<Paths, "transcriptsDir">, + url: string, + o: { onLog?: (l: string) => void; timeoutMs?: number; env?: Record<string, string | undefined> } = {}, +): Promise<ArchiveSessionRecord> { + const log = o.onLog ?? (() => {}); + const host = new URL(url).hostname.toLowerCase(); + const profileDir = archiveProfileDir(paths); + await mkdir(profileDir, { recursive: true }); + const browser = findXBrowser({ env: o.env }); + const label = describeXBrowser(browser); + const { chromium } = await importPlaywright(); + log(`Opening ${label} at ${host}. Pass the check if one shows, wait for the page, then close the window.`); + let context: BrowserContextLike; + try { + context = await chromium.launchPersistentContext(profileDir, buildXBrowserLaunchOptions({ browser, headless: false, sandbox: true })); + } catch (err) { + log(`The sandboxed launch failed (${firstLine(err)}); opening without the sandbox.`); + context = await chromium.launchPersistentContext(profileDir, buildXBrowserLaunchOptions({ browser, headless: false, sandbox: false })); + } + await writeXBrowserRecord(profileDir, browser).catch(() => {}); + let cleared = false; + let cookies = 0; + const look = async () => { + try { + const page = context.pages()[0]; + if (page) cleared = !isArchiveTodayChallenge(String(await page.evaluate(OUTER_HTML))); + cookies = ((await context.cookies()) as { domain?: string }[]).filter((c) => + /archive\.(?:ph|today|is|li|vn|fo|md)$/i.test((c.domain ?? "").replace(/^\./, "")), + ).length; + } catch { + // closing, or mid-navigation + } + }; + try { + const page = context.pages()[0] ?? (await context.newPage()); + await page.goto(url, { waitUntil: "domcontentloaded", timeout: 60_000 }).catch((err: unknown) => { + log(`The first load did not finish (${firstLine(err)}); the window stays open.`); + }); + await new Promise<void>((resolve) => { + let settled = false; + const timer = setInterval(() => void look(), 2_000); + const finish = () => { + if (settled) return; + settled = true; + clearInterval(timer); + resolve(); + }; + context.on("close", finish); + if (o.timeoutMs) setTimeout(finish, o.timeoutMs); + }); + } finally { + await context.close().catch(() => {}); + } + const record: ArchiveSessionRecord = { + service: ARCHIVE_SESSION_SERVICE, + host, + connectedAt: new Date().toISOString(), + cleared, + cookies, + browser: label, + }; + await writeJsonAtomic(path.join(archiveSessionDir(paths), "session.json"), record, { mkdir: true }); + log( + cleared + ? `A page that is not a check showed before the window closed; ${cookies} cookie(s) for archive.today kept in the profile.` + : `The window closed with a check still showing; ${cookies} cookie(s) for archive.today in the profile.`, + ); + return record; +} diff --git a/common/lib/archives/ask.ts b/common/lib/archives/ask.ts @@ -0,0 +1,73 @@ +// WHAT A PAGE IMPORT IS ASKED FOR, across archive sources (release 37 lane F): +// a copy's URL on any source, or a page's own URL with a date and (optionally) +// the source to look in. Client-safe (no node imports). +// +// {url: <Wayback capture>} that capture (lib/waybackPages/urls.ts) +// {url: <page>, at} the Wayback capture nearest `at` +// {url: <archive.today copy>} that copy (archive.ph/<id>, /<ts>/<page>, /newest/<page>) +// {url: <page>, at, source: "archive.today"} the archive.today copy nearest `at` (its timemap) + +import { parsePageCaptureAsk, isCaptureAt, NOT_A_CAPTURE_URL, type PageCaptureAsk } from "../waybackPages/urls"; +import { isArchiveTodayUrl, parseArchiveTodayUrl } from "./mementos"; +import { isArchiveSourceId, type ArchiveMementoRef, type ArchiveSourceId } from "./types"; + +export type ArchiveCaptureAsk = + | (PageCaptureAsk & { source: "wayback" }) + // One archive.today copy by its URL. `originalUrl` when the URL names the + // page (/<ts>/<page>, /newest/<page>); a short id names none. + | { kind: "memento"; source: "archive.today"; ref: ArchiveMementoRef; originalUrl?: string } + // The archive.today copy of `originalUrl` nearest `at`. + | { kind: "nearest"; source: "archive.today"; at: string; originalUrl: string }; + +export const NOT_A_COPY_URL = + `${NOT_A_CAPTURE_URL}; or an archive.today copy's URL (https://archive.ph/<id>), ` + + 'or the page\'s own URL, a date and "source": "archive.today"'; + +export function parseArchiveCaptureAsk( + url: string, + at?: string, + source?: string, +): { ok: true; ask: ArchiveCaptureAsk } | { ok: false; error: string } { + const given = url.trim(); + const when = (at ?? "").trim(); + const want = (source ?? "").trim(); + if (want && !isArchiveSourceId(want)) { + return { ok: false, error: `"source" must be "wayback" or "archive.today", not "${want}"` }; + } + const asked = (want || undefined) as ArchiveSourceId | undefined; + if (given && isArchiveTodayUrl(given)) { + if (asked && asked !== "archive.today") { + return { ok: false, error: `${given} is an archive.today copy, not the ${asked === "wayback" ? "Wayback Machine's" : asked}` }; + } + const ref = parseArchiveTodayUrl(given); + if (!ref) { + return { ok: false, error: `${given} is an archive.today listing or link, not one copy: ${NOT_A_COPY_URL}` }; + } + if (when) { + return { ok: false, error: `"at" goes with a page's own URL; ${given} already names its copy` }; + } + return { + ok: true, + ask: { kind: "memento", source: "archive.today", ref, ...(ref.originalUrl ? { originalUrl: ref.originalUrl } : {}) }, + }; + } + if (asked === "archive.today") { + let u: URL; + try { + u = new URL(given); + } catch { + return { ok: false, error: `"${given}" is not a URL: ${NOT_A_COPY_URL}` }; + } + if (u.protocol !== "http:" && u.protocol !== "https:") return { ok: false, error: `"${given}" is not an http(s) URL` }; + const wb = parsePageCaptureAsk(given); + if (wb.ok) return { ok: false, error: `${given} is a Wayback Machine capture, not an archive.today copy` }; + if (!when) { + return { ok: false, error: `give "at" (YYYYMMDD) with a page's own URL to import its archive.today copy nearest that date` }; + } + if (!isCaptureAt(when)) return { ok: false, error: `"at" must be a date as YYYYMMDD (or YYYYMMDDhhmmss), not "${when}"` }; + return { ok: true, ask: { kind: "nearest", source: "archive.today", at: when, originalUrl: given } }; + } + const wb = parsePageCaptureAsk(given, at); + if (!wb.ok) return wb; + return { ok: true, ask: { ...wb.ask, source: "wayback" } }; +} diff --git a/common/lib/archives/index.ts b/common/lib/archives/index.ts @@ -0,0 +1,168 @@ +// THE ARCHIVE SOURCES (release 37 lane F): the registry every caller asks — the +// page import, the lookup across sources, the channel page — and the process's +// clients. One entry per source, in the order a lookup lists them. ADDING A +// SOURCE is one module (its client + its `ArchiveSource`) and one entry here: +// see plans/release-37/archive-sources.md, "Adding an archive source". +// +// Server-only (the clients). What a URL says without a request is +// lib/archives/mementos.ts, client-safe. + +import { getSettings } from "../settings"; +import { getPaths } from "../paths"; +import { ArchiveOrgRequestError } from "../archiveOrgClient"; +import { isWaybackExcluded, WAYBACK_EXCLUDED_PHRASE, WaybackCaptureRefusal } from "../waybackClient"; +import { archiveSourceLabel, parseArchiveTodayUrl } from "./mementos"; +import { waybackSource } from "./wayback"; +import { + ARCHIVE_TODAY_QUEUE, + ArchiveTodayClient, + ArchiveTodayRequestError, + archiveTodayTestOrigin, + processArchiveTodayFetch, +} from "./archiveTodayClient"; +import { archiveSessionBrowser } from "./archiveTodaySession"; +import { ArchiveRefusal, type ArchiveCaptureRow, type ArchiveRefusalCode, type ArchiveSource, type ArchiveSourceId } from "./types"; + +export * from "./types"; + +const archivesSettings = () => { + try { + return getSettings().archives; + } catch { + return undefined; + } +}; + +// THE process's archive.today client: one chain, one gap, one cool-down, the +// host and pace read from settings per request. Under the e2e fake +// (E2E_ARCHIVE_TODAY_ORIGIN_FILE) no browser is ever opened. +export const archiveTodayClient = new ArchiveTodayClient( + { + fetch: processArchiveTodayFetch, + host: () => archivesSettings()?.archiveTodayHost ?? "archive.ph", + openBrowser: () => archiveSessionBrowser(getPaths(), { onLog: (l) => console.log(`[archive-session] ${l}`) })(), + browserEnabled: () => archivesSettings()?.archiveTodayBrowser !== false && archiveTodayTestOrigin() === null, + }, + { + minGapMs: () => (archivesSettings()?.archiveTodayGapSeconds ?? 8) * 1000, + cooldownMs: () => (archivesSettings()?.archiveTodayCooldownMinutes ?? 30) * 60_000, + }, +); + +export function archiveTodaySource(client: ArchiveTodayClient = archiveTodayClient): ArchiveSource { + return { + id: "archive.today", + label: "archive.today", + queueKey: ARCHIVE_TODAY_QUEUE, + matchesUrl: (url) => parseArchiveTodayUrl(url) !== null, + parseMementoUrl: (url) => parseArchiveTodayUrl(url, client.host), + listCaptures: (url, o) => client.listCaptures(url, o), + closestCapture: (url, at, o) => client.closestCapture(url, at, o), + getCapture: (memento, o) => client.getCapture(memento, o), + }; +} + +export const ARCHIVE_SOURCES: readonly ArchiveSource[] = [waybackSource(), archiveTodaySource()]; + +export function archiveSource(id: string | undefined, sources: readonly ArchiveSource[] = ARCHIVE_SOURCES): ArchiveSource | null { + return sources.find((s) => s.id === (id ?? "wayback")) ?? null; +} + +// The source a COPY's URL is on, or null (a listing, an original page). +export function sourceForUrl(url: string, sources: readonly ArchiveSource[] = ARCHIVE_SOURCES): ArchiveSource | null { + return sources.find((s) => s.matchesUrl(url)) ?? null; +} + +// An error as an archive refusal (its code, source and sentence), or null +// when it is not one: ArchiveRefusal, WaybackCaptureRefusal, and the Wayback +// Machine's exclusion (a CDX 403). +export function archiveRefusalOf(e: unknown): { source: ArchiveSourceId; code: ArchiveRefusalCode; message: string } | null { + if (e instanceof ArchiveRefusal) return { source: e.source, code: e.code, message: e.message }; + if (isWaybackExcluded(e)) return { source: "wayback", code: "excluded", message: (e as Error).message }; + if (e instanceof WaybackCaptureRefusal) return { source: "wayback", code: e.code, message: e.message }; + return null; +} + +export type ArchiveLookupEntry = { + source: ArchiveSourceId; + label: string; + ok: boolean; + captures: ArchiveCaptureRow[]; + // The refusal's code ("excluded", "challenge", "rate-limited", …), when + // the source refused. + refusal?: ArchiveRefusalCode; + error?: string; +}; + +export type ArchiveLookup = { + url: string; + found: number; + sources: ArchiveLookupEntry[]; +}; + +// THE COPIES OF A PAGE across sources (`archive-lookup`): each source asked +// in turn (each through its own paced client), its copies oldest first, at +// most `limit` per source. A source that refuses or fails is its own entry's +// sentence; the others still answer. Read only. +export async function archiveLookup( + url: string, + o: { + source?: ArchiveSourceId; + sources?: readonly ArchiveSource[]; + limit?: number; + from?: string; + to?: string; + signal?: AbortSignal; + } = {}, +): Promise<ArchiveLookup> { + const all = o.sources ?? ARCHIVE_SOURCES; + const chosen = o.source ? all.filter((s) => s.id === o.source) : all; + const entries: ArchiveLookupEntry[] = []; + for (const s of chosen) { + try { + const captures = await s.listCaptures(url, { + ...(o.limit ? { limit: o.limit } : {}), + ...(o.from ? { from: o.from } : {}), + ...(o.to ? { to: o.to } : {}), + ...(o.signal ? { signal: o.signal } : {}), + }); + entries.push({ source: s.id, label: s.label, ok: true, captures }); + } catch (e) { + if (o.signal?.aborted) throw e; + const refusal = archiveRefusalOf(e); + if (refusal) { + entries.push({ source: s.id, label: s.label, ok: false, captures: [], refusal: refusal.code, error: refusal.message }); + } else if (e instanceof ArchiveOrgRequestError || e instanceof ArchiveTodayRequestError) { + entries.push({ source: s.id, label: s.label, ok: false, captures: [], error: e.message }); + } else { + throw e; + } + } + } + return { url, found: entries.reduce((n, e) => n + e.captures.length, 0), sources: entries }; +} + +// THE COPY NEAREST A TIME, across sources (lane E's find-copy page mode): each +// source asked in turn (the Wayback Machine first), the first that holds a +// copy answers. A source that EXCLUDES the page (a Wayback 403) or holds none +// passes to the next; any other refusal or error is thrown, so the caller's +// stop rules still apply. +export async function nearestAcrossSources( + url: string, + at: string, + o: { sources?: readonly ArchiveSource[]; signal?: AbortSignal } = {}, +): Promise<ArchiveCaptureRow | null> { + for (const s of o.sources ?? ARCHIVE_SOURCES) { + try { + const near = await s.closestCapture(url, at, o.signal ? { signal: o.signal } : {}); + if (near) return near; + } catch (e) { + if (o.signal?.aborted) throw e; + if (archiveRefusalOf(e)?.code === "excluded") continue; + throw e; + } + } + return null; +} + +export { archiveSourceLabel, WAYBACK_EXCLUDED_PHRASE }; diff --git a/common/lib/archives/mementos.test.ts b/common/lib/archives/mementos.test.ts @@ -0,0 +1,143 @@ +// Release 37 lane F: what a memento URL says, with no request. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/archives/mementos.test.ts + +import test from "node:test"; +import assert from "node:assert/strict"; +import { + archiveTodayHostOf, + archiveTodayTs, + httpDateOfTimestamp, + mementoSourceOf, + pageArchiveLink, + parseArchiveTodayUrl, + timestampOfDate, + unwrapArchiveTodayOutlink, +} from "./mementos"; +import { parseArchiveCaptureAsk } from "./ask"; + +test("archive.today copies in every form, on the canonical host; listings and links out are not copies", () => { + assert.deepEqual(parseArchiveTodayUrl("https://archive.ph/Ab3dE"), { source: "archive.today", mementoUrl: "https://archive.ph/Ab3dE", id: "Ab3dE" }); + // Any of its names, read as the canonical host; a copy's sub-page is the copy. + assert.equal(parseArchiveTodayUrl("http://archive.is/Ab3dE/image")?.mementoUrl, "https://archive.ph/Ab3dE"); + assert.equal(parseArchiveTodayUrl("https://archive.today/Ab3dE", "archive.li")?.mementoUrl, "https://archive.li/Ab3dE"); + assert.deepEqual(parseArchiveTodayUrl("https://archive.ph/2019.05.12-083000/https://journal.example/a.html"), { + source: "archive.today", + mementoUrl: "https://archive.ph/20190512083000/https://journal.example/a.html", + originalUrl: "https://journal.example/a.html", + captureTs: "20190512083000", + }); + assert.equal(parseArchiveTodayUrl("https://archive.ph/20190512/journal.example/a.html?x=1")?.originalUrl, "http://journal.example/a.html?x=1"); + assert.deepEqual(parseArchiveTodayUrl("https://archive.vn/newest/https://journal.example/a.html"), { + source: "archive.today", + mementoUrl: "https://archive.ph/newest/https://journal.example/a.html", + originalUrl: "https://journal.example/a.html", + pick: "newest", + }); + for (const notACopy of [ + "https://archive.ph/", + "https://archive.ph/journal.example", + "https://archive.ph/https://journal.example/*", + "https://archive.ph/o/Ab3dE/https://journal.example/b.html", + "https://archive.ph/timemap/https://journal.example/", + "https://archive.ph/search/?q=journal", + "https://archive.ph/submit/", + "https://web.archive.org/web/2019/https://journal.example/", + "https://journal.example/Ab3dE", + ]) { + assert.equal(parseArchiveTodayUrl(notACopy), null, notACopy); + } +}); + +test("timestamps: dotted and digit forms, HTTP dates both ways; the canonical host is one of its names", () => { + assert.equal(archiveTodayTs("2019.05.12-083000"), "20190512083000"); + assert.equal(timestampOfDate("Sun, 12 May 2019 08:30:00 GMT"), "20190512083000"); + assert.equal(timestampOfDate("2019-05-12T08:30:00Z"), "20190512083000"); + assert.equal(timestampOfDate("not a date"), null); + assert.equal(httpDateOfTimestamp("20190512083000"), "Sun, 12 May 2019 08:30:00 GMT"); + assert.equal(archiveTodayHostOf("ARCHIVE.IS"), "archive.is"); + assert.equal(archiveTodayHostOf("evil.example"), "archive.ph"); + assert.equal(archiveTodayHostOf(undefined), "archive.ph"); +}); + +test("a link out of a copy is the URL it points at", () => { + assert.equal(unwrapArchiveTodayOutlink("https://archive.ph/o/Ab3dE/https://other.example/account"), "https://other.example/account"); + assert.equal(unwrapArchiveTodayOutlink("/o/Ab3dE/https://other.example/x?y=1"), "https://other.example/x?y=1"); + assert.equal(unwrapArchiveTodayOutlink("https://other.example/x"), "https://other.example/x"); +}); + +test("which source a URL is a copy on", () => { + assert.equal(mementoSourceOf("https://web.archive.org/web/20140305120000/https://blog.example/"), "wayback"); + assert.equal(mementoSourceOf("https://archive.ph/Ab3dE"), "archive.today"); + assert.equal(mementoSourceOf("https://blog.example/"), null); + assert.equal(mementoSourceOf("https://web.archive.org/web/*/blog.example/*"), null); +}); + +test("a record's copy is cited by its source's URL and name; a record with no source is the Wayback Machine's", () => { + assert.deepEqual( + pageArchiveLink({ captureTs: "20140305120000", originalUrl: "https://blog.example/", waybackUrl: "https://web.archive.org/web/20140305120000/https://blog.example/" }), + { source: "wayback", label: "Wayback Machine", url: "https://web.archive.org/web/20140305120000/https://blog.example/" }, + ); + assert.deepEqual( + pageArchiveLink({ source: "archive.today", archiveUrl: "https://archive.ph/Ab3dE", waybackUrl: "https://archive.ph/Ab3dE", captureTs: "20190512083000", originalUrl: "https://journal.example/a.html" }), + { source: "archive.today", label: "archive.today", url: "https://archive.ph/Ab3dE" }, + ); +}); + +test("an import's ask across sources: a copy's URL names its source; a page's URL takes `at` and a source", () => { + const ok = (url: string, at?: string, source?: string) => { + const r = parseArchiveCaptureAsk(url, at, source); + assert.ok(r.ok, r.ok ? "" : r.error); + return r.ask; + }; + const err = (url: string, at?: string, source?: string) => { + const r = parseArchiveCaptureAsk(url, at, source); + assert.equal(r.ok, false); + return r.ok ? "" : r.error; + }; + assert.deepEqual(ok("https://web.archive.org/web/20140305120000/https://blog.example/"), { + kind: "capture", + captureTs: "20140305120000", + originalUrl: "https://blog.example/", + source: "wayback", + }); + assert.deepEqual(ok("https://blog.example/", "2014"), { kind: "nearest", at: "2014", originalUrl: "https://blog.example/", source: "wayback" }); + assert.deepEqual(ok("https://archive.is/Ab3dE"), { + kind: "memento", + source: "archive.today", + ref: { source: "archive.today", mementoUrl: "https://archive.ph/Ab3dE", id: "Ab3dE" }, + }); + assert.equal(ok("https://archive.ph/newest/https://journal.example/a.html").originalUrl, "https://journal.example/a.html"); + assert.deepEqual(ok("https://journal.example/a.html", "20190601", "archive.today"), { + kind: "nearest", + source: "archive.today", + at: "20190601", + originalUrl: "https://journal.example/a.html", + }); + assert.match(err("https://archive.ph/https://journal.example/*"), /archive\.today listing or link, not one copy/); + assert.match(err("https://archive.ph/Ab3dE", "2019"), /"at" goes with a page's own URL/); + assert.match(err("https://archive.ph/Ab3dE", undefined, "wayback"), /is an archive\.today copy/); + assert.match(err("https://journal.example/a.html", undefined, "archive.today"), /give "at"/); + assert.match(err("https://web.archive.org/web/2014/https://blog.example/", "2014", "archive.today"), /is a Wayback Machine capture/); + assert.match(err("https://journal.example/a.html", "2019", "ghostarchive"), /"source" must be/); + // The Wayback Machine's own sentences, unchanged. + assert.match(err("https://blog.example/"), /not a Wayback Machine capture/); +}); + +test("the view's copy link names archive.today for its records (lane D's pageCopyLinks)", async () => { + const { pageCopyLinks, pageCaptureView } = await import("../waybackPages/view"); + const page = { + originalUrl: "https://journal.example/a.html", + captureTs: "20190512083000", + waybackUrl: "https://archive.ph/Ab3dE", + rawUrl: "https://archive.ph/Ab3dE", + source: "archive.today", + archiveUrl: "https://archive.ph/Ab3dE", + }; + assert.deepEqual(pageCopyLinks(page).copy, { label: "archive.today copy, 2019-05-12", url: "https://archive.ph/Ab3dE" }); + const { source: _s, archiveUrl: _a, ...wb } = page; + assert.match(pageCopyLinks({ ...wb, waybackUrl: "https://web.archive.org/web/20190512083000/https://journal.example/a.html" }).copy.label, /^Wayback Machine copy, /); + const view = pageCaptureView({ id: "20190512083000-aaaaaaaaaaaa", text: "x", page: { ...page, kind: "generic", extractor: "generic", extractorVersion: 1 } }); + assert.equal(view?.source, "archive.today"); + assert.equal(view?.waybackUrl, "https://archive.ph/Ab3dE"); +}); diff --git a/common/lib/archives/mementos.ts b/common/lib/archives/mementos.ts @@ -0,0 +1,183 @@ +// WHAT A MEMENTO URL SAYS (release 37 lane F), for every archive source, with +// no request: which source a URL is a copy on, the page and time it names, and +// how a record links its copy. Client-safe (no node imports): the channel form +// and the channel page read it too. +// +// archive.today (one service under several names: archive.ph, archive.today, +// archive.is, archive.li, archive.vn, archive.fo, archive.md) names a copy as +// https://archive.ph/<id> a copy, by its short id (AbCdE) +// https://archive.ph/<ts>/<original> the copy of <original> nearest <ts> +// (<ts>: YYYYMMDDhhmmss, or YYYY.MM.DD-hhmmss) +// https://archive.ph/newest/<original> its newest copy +// https://archive.ph/oldest/<original> its oldest copy +// and lists them at /timemap/<original> (the Memento protocol's link format). +// `/o/<id>/<url>` is a link OUT of a copy (to <url>), and a bare +// `/<original>` or `/search/` a listing: neither is a copy. + +import { parseWaybackUrl, waybackPageUrl } from "../wayback"; +import type { ArchiveMementoRef, ArchiveSourceId } from "./types"; + +export const ARCHIVE_TODAY_HOSTS = [ + "archive.ph", + "archive.today", + "archive.is", + "archive.li", + "archive.vn", + "archive.fo", + "archive.md", +] as const; + +export const DEFAULT_ARCHIVE_TODAY_HOST = "archive.ph"; + +export const ARCHIVE_SOURCE_LABELS: Record<ArchiveSourceId, string> = { + wayback: "Wayback Machine", + "archive.today": "archive.today", +}; + +export function archiveSourceLabel(id: string | undefined): string { + return ARCHIVE_SOURCE_LABELS[(id ?? "wayback") as ArchiveSourceId] ?? id ?? "Wayback Machine"; +} + +export function isArchiveTodayHost(host: string): boolean { + const h = host.toLowerCase().replace(/^www\./, ""); + return (ARCHIVE_TODAY_HOSTS as readonly string[]).includes(h); +} + +// The canonical host a setting names, or the default: one of the known names, +// nothing else (a typo never sends requests somewhere new). +export function archiveTodayHostOf(setting: unknown): string { + const h = typeof setting === "string" ? setting.trim().toLowerCase().replace(/^www\./, "") : ""; + return isArchiveTodayHost(h) ? h : DEFAULT_ARCHIVE_TODAY_HOST; +} + +const SHORT_ID_RE = /^[A-Za-z0-9]{4,6}$/; +// YYYYMMDDhhmmss (or a whole-unit prefix), or archive.today's dotted +// YYYY.MM.DD-hhmmss (or YYYY.MM.DD). +const TS_SEG_RE = /^(?:\d{4}(?:\d{2}){0,5}|\d{4}\.\d{2}\.\d{2}(?:-\d{6})?)$/; +const RESERVED = new Set(["o", "timemap", "timegate", "search", "submit", "wip", "faq", "newest", "oldest", "about", "donate"]); + +// "2019.01.02-030405" → "20190102030405"; a digit timestamp as it is. +export function archiveTodayTs(seg: string): string { + return seg.replace(/[.-]/g, ""); +} + +// An HTTP date (Memento-Datetime: "Tue, 01 Jan 2019 12:34:56 GMT") or an +// ISO-8601 instant as a 14-digit UTC timestamp, or null. +export function timestampOfDate(value: string | null | undefined): string | null { + if (!value) return null; + const ms = Date.parse(value.trim()); + if (!Number.isFinite(ms)) return null; + return new Date(ms).toISOString().replace(/[-:T]/g, "").slice(0, 14); +} + +// A 14-digit timestamp as an HTTP date (what a timegate's Accept-Datetime takes). +export function httpDateOfTimestamp(ts: string): string { + const p = ts.padEnd(14, "0"); + const ms = Date.UTC(+p.slice(0, 4), +p.slice(4, 6) - 1 || 0, +p.slice(6, 8) || 1, +p.slice(8, 10), +p.slice(10, 12), +p.slice(12, 14)); + return new Date(ms).toUTCString(); +} + +function originalOf(rest: string, search: string): string | null { + let r = rest; + if (/^https?%3a/i.test(r)) { + try { + r = decodeURIComponent(r); + } catch { + return null; + } + } + r = r.replace(/^(https?):\/(?!\/)/i, "$1://"); + if (!/^https?:\/\//i.test(r)) r = `http://${r}`; + const out = `${r}${search}`; + try { + const u = new URL(out); + if (!u.hostname.includes(".")) return null; + if (isArchiveTodayHost(u.hostname)) return null; + } catch { + return null; + } + return out; +} + +// An archive.today COPY's parts (on the canonical `host`), or null for +// anything else: another host, a listing, a search, a link out of a copy. +export function parseArchiveTodayUrl(url: string | null | undefined, host: string = DEFAULT_ARCHIVE_TODAY_HOST): ArchiveMementoRef | null { + if (!url) return null; + let u: URL; + try { + u = new URL(url.trim()); + } catch { + return null; + } + if (u.protocol !== "http:" && u.protocol !== "https:") return null; + if (!isArchiveTodayHost(u.hostname)) return null; + const canon = archiveTodayHostOf(host); + const path = u.pathname.replace(/^\/+/, ""); + const segs = path.split("/"); + const first = segs[0] ?? ""; + if (!first) return null; + if (first === "newest" || first === "oldest") { + const original = originalOf(segs.slice(1).join("/"), u.search); + if (!original) return null; + return { source: "archive.today", mementoUrl: `https://${canon}/${first}/${original}`, originalUrl: original, pick: first }; + } + if (TS_SEG_RE.test(first) && segs.length > 1) { + const original = originalOf(segs.slice(1).join("/"), u.search); + if (!original) return null; + const ts = archiveTodayTs(first); + return { source: "archive.today", mementoUrl: `https://${canon}/${ts}/${original}`, originalUrl: original, captureTs: ts }; + } + if (RESERVED.has(first.toLowerCase())) return null; + // `/<id>`, `/<id>/`, and the copy's own sub-pages (`/<id>/image`) name the copy. + if (SHORT_ID_RE.test(first) && (segs.length === 1 || segs.slice(1).every((s) => s === "" || /^[a-z]+$/.test(s)))) { + return { source: "archive.today", mementoUrl: `https://${canon}/${first}`, id: first }; + } + return null; +} + +// Any URL on an archive.today host (a copy, a listing, a search). +export function isArchiveTodayUrl(url: string): boolean { + try { + return isArchiveTodayHost(new URL(url.trim()).hostname); + } catch { + return false; + } +} + +// `/o/<id>/<url>` (a link out of an archive.today copy) as <url>; any other +// URL as given. +export function unwrapArchiveTodayOutlink(href: string): string { + const m = /^(?:https?:)?\/\/(?:www\.)?(?:archive\.(?:ph|today|is|li|vn|fo|md))\/o\/[A-Za-z0-9]+\/(.+)$/i.exec(href.trim()) + ?? /^\/o\/[A-Za-z0-9]+\/(https?:\/\/.+)$/i.exec(href.trim()); + if (!m) return href; + return m[1].replace(/^(https?):\/(?!\/)/i, "$1://"); +} + +// Which source a URL is a COPY on, or null (a listing, an original page). +export function mementoSourceOf(url: string): ArchiveSourceId | null { + if (parseWaybackUrl(url)) return "wayback"; + if (parseArchiveTodayUrl(url)) return "archive.today"; + return null; +} + +// THE LINK A RECORD'S COPY IS CITED BY (lane D: shots, the moment page, +// citation labels, the MCP): `page.archiveUrl` for a record from a source that +// is not the Wayback Machine, else its Wayback replay URL — and the source's +// name for the label. +export function pageArchiveLink(page: { + source?: string; + archiveUrl?: string; + waybackUrl?: string; + captureTs: string; + originalUrl: string; +}): { source: ArchiveSourceId; label: string; url: string } { + const source = (page.source ?? "wayback") as ArchiveSourceId; + if (source !== "wayback" && page.archiveUrl) { + return { source, label: archiveSourceLabel(source), url: page.archiveUrl }; + } + return { + source: "wayback", + label: ARCHIVE_SOURCE_LABELS.wayback, + url: page.waybackUrl || waybackPageUrl({ captureTs: page.captureTs, originalUrl: page.originalUrl }), + }; +} diff --git a/common/lib/archives/settings.ts b/common/lib/archives/settings.ts @@ -0,0 +1,54 @@ +// settings.archives — the archive sources a page import reads (release 37 +// lane F). Pure: the type, its defaults, the sanitizer settingsSchema.ts runs +// it through and the per-field docs SETTINGS.md renders. + +import type { FieldDocs } from "../fieldDocs"; +import { archiveTodayHostOf, DEFAULT_ARCHIVE_TODAY_HOST } from "./mementos"; + +export type ArchivesSettings = { + archiveTodayHost: string; + archiveTodayGapSeconds: number; + archiveTodayCooldownMinutes: number; + archiveTodayBrowser: boolean; +}; + +export const DEFAULT_ARCHIVES_SETTINGS: ArchivesSettings = { + archiveTodayHost: DEFAULT_ARCHIVE_TODAY_HOST, + archiveTodayGapSeconds: 8, + archiveTodayCooldownMinutes: 30, + archiveTodayBrowser: true, +}; + +export const ARCHIVES_SETTINGS_FIELD_DOCS: FieldDocs<ArchivesSettings> = { + archiveTodayHost: + "The archive.today name every request goes to (archive.ph, archive.today, archive.is, archive.li, archive.vn, " + + "archive.fo or archive.md — one service). A copy's URL on any of them is read from this one. Anything else " + + "falls back to archive.ph.", + archiveTodayGapSeconds: + "The least time between two archive.today requests, seconds, from the end of one to the start of the next, " + + "with up to a quarter more at random. One request at a time, always. Clamped to [4, 120]; default 8.", + archiveTodayCooldownMinutes: + "After archive.today answers HTTP 429 (too many requests) the run stops, and no request goes to it for this " + + "long (or its Retry-After, when longer). Clamped to [5, 1440]; default 30.", + archiveTodayBrowser: + "When archive.today answers with a check (a CAPTCHA, a browser check) instead of a copy, read the copy once " + + "more through the headless browser on the archive session's profile (Connect archive session keeps a cleared " + + "check there). Nothing is ever solved by code: a check the browser cannot pass is refused with a sentence. " + + "False = refuse at the check.", +}; + +const clamp = (v: unknown, d: number, min: number, max: number): number => { + const n = typeof v === "number" && Number.isFinite(v) ? v : d; + return Math.min(max, Math.max(min, n)); +}; + +export function sanitizeArchives(value: unknown): ArchivesSettings { + const r = (value && typeof value === "object" && !Array.isArray(value) ? value : {}) as Record<string, unknown>; + const d = DEFAULT_ARCHIVES_SETTINGS; + return { + archiveTodayHost: archiveTodayHostOf(r.archiveTodayHost), + archiveTodayGapSeconds: clamp(r.archiveTodayGapSeconds, d.archiveTodayGapSeconds, 4, 120), + archiveTodayCooldownMinutes: Math.round(clamp(r.archiveTodayCooldownMinutes, d.archiveTodayCooldownMinutes, 5, 1440)), + archiveTodayBrowser: r.archiveTodayBrowser !== false, + }; +} diff --git a/common/lib/archives/types.ts b/common/lib/archives/types.ts @@ -0,0 +1,140 @@ +// ARCHIVE SOURCES (release 37 lane F, plans/release-37/archive-sources.md): a +// service that holds copies of web pages — the Wayback Machine, archive.today, +// and whichever comes next — read the same way. A source answers four +// questions: is this URL one of my copies (a "memento"), which copies do I +// hold of a page, which one is nearest a time, and what are a copy's bytes. +// Each source is ONE module (lib/archives/<source>.ts) registered in +// lib/archives/index.ts; the page import, the lookup and the citation code ask +// the registry, never a source by name. +// +// Types and the refusal only; client-safe (no node imports). + +// The sources this build knows. A record's `page.source` is one of these +// (absent = "wayback", the records made before sources existed). +export const ARCHIVE_SOURCE_IDS = ["wayback", "archive.today"] as const; +export type ArchiveSourceId = (typeof ARCHIVE_SOURCE_IDS)[number]; + +export function isArchiveSourceId(v: unknown): v is ArchiveSourceId { + return typeof v === "string" && (ARCHIVE_SOURCE_IDS as readonly string[]).includes(v); +} + +// What a memento URL says before anything is fetched. archive.today's short +// form (`archive.ph/AbCdE`) names neither the page nor the time: those are +// learned from the copy itself. +export type ArchiveMementoRef = { + source: ArchiveSourceId; + // The copy's URL, on the source's canonical host. + mementoUrl: string; + // The page it is a copy of, when the URL names it. + originalUrl?: string; + // The capture time (4–14 digits, a Wayback timestamp's form), when the URL + // names it. A short one is "the copy nearest this". + captureTs?: string; + // The bytes as captured, when the source has such a form (Wayback's `id_`). + rawUrl?: string; + // archive.today: the short id (`AbCdE`). + id?: string; + // archive.today: `newest` / `oldest` — the URL names a page, and the source + // picks the copy. + pick?: "newest" | "oldest"; +}; + +// One copy a source lists (a lookup's row). +export type ArchiveCaptureRow = { + source: ArchiveSourceId; + // YYYYMMDDhhmmss + captureTs: string; + originalUrl: string; + // The copy as a page a reader opens. + mementoUrl: string; + // The status the capture recorded, when the source says ("200", "302"). + status?: string; + mimetype?: string; +}; + +// One copy's bytes (getCapture). `body` is what the source served — what the +// page import stores — and `page` the same copy as a page the extractors read +// (`unwrapped`): Wayback's `id_` body as it is, archive.today's snapshot with +// its own header taken off and its rewritten links put back. +export type ArchiveRawCapture = { + source: ArchiveSourceId; + body: Buffer; + // The bare mimetype ("text/html") and the Content-Type as served. + mimetype: string; + contentType: string; + // The copy the answer is (after any redirect). + finalTs: string; + originalUrl: string; + mementoUrl: string; + bytes: number; + sha256: string; + unwrapped: true; + page: string; + // archive.today: the copy was read through the headless browser (its check + // stood in the way of a plain request). + viaBrowser?: boolean; +}; + +export type ArchiveRefusalCode = + // The source answered, and holds nothing of this page for anyone: a Wayback + // CDX 403 ("excluded from the Wayback Machine (cause unknown)"). + | "excluded" + // The source put a check (a CAPTCHA, a "one more step" page) in front of + // the copy. Never solved by code: Connect archive session, then again. + | "challenge" + // The source said "too many requests" (HTTP 429): the run stops, and the + // client leaves the source alone for a while. + | "rate-limited" + // No such copy. + | "not-archived" + // A body that is not a page, or over the cap. + | "mimetype" + | "too-large" + // Redirects that leave the source or go round. + | "offsite-redirect" + | "redirect-loop" + // An answer that names no capture time or page. + | "unreadable"; + +// A copy (or a listing) a source will not hand back, with the sentence a +// caller shows. Thrown by the archive.today client and by the registry's +// lookups; Wayback's own refusals (WaybackCaptureRefusal, WaybackExcludedError) +// are read as these by `archiveRefusalOf` (lib/archives/index.ts). +export class ArchiveRefusal extends Error { + readonly code: ArchiveRefusalCode; + readonly source: ArchiveSourceId; + // rate-limited: when the client will ask again (epoch ms). + readonly retryAt?: number; + constructor(source: ArchiveSourceId, code: ArchiveRefusalCode, message: string, o: { retryAt?: number } = {}) { + super(message); + this.name = "ArchiveRefusal"; + this.source = source; + this.code = code; + if (o.retryAt !== undefined) this.retryAt = o.retryAt; + } +} + +// THE SOURCE. Every request goes through the source's own paced client; a job +// that reads a source runs on its `queueKey`. +export type ArchiveSource = { + id: ArchiveSourceId; + // "Wayback Machine", "archive.today". + label: string; + // The job queue its requests run on ("platform:archive.org", + // "platform:archive.today"). + queueKey: string; + // Is this a memento URL of mine (a copy, not a listing)? + matchesUrl(url: string): boolean; + parseMementoUrl(url: string): ArchiveMementoRef | null; + // The copies held of `originalUrl`, oldest first; `from`/`to` are + // capture-time prefixes (inclusive), `limit` at most this many. Paced. + listCaptures( + originalUrl: string, + o?: { from?: string; to?: string; limit?: number; signal?: AbortSignal }, + ): Promise<ArchiveCaptureRow[]>; + // The copy nearest `at` (4–14 digits), or null when there is none. + closestCapture(url: string, at: string, o?: { signal?: AbortSignal }): Promise<ArchiveCaptureRow | null>; + // One copy's bytes, at most `maxBytes`. Throws ArchiveRefusal (or the + // source's own typed refusal) for what it will not hand back. + getCapture(memento: string | ArchiveMementoRef, o?: { maxBytes?: number; signal?: AbortSignal }): Promise<ArchiveRawCapture>; +}; diff --git a/common/lib/archives/wayback.test.ts b/common/lib/archives/wayback.test.ts @@ -0,0 +1,136 @@ +// Release 37 lane F: the Wayback Machine as an archive source answers exactly +// what its client answers (the same requests, rows and bytes); a CDX 403 is +// the typed "excluded" refusal on every path; the lookup across sources gives +// each source its own entry. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/archives/wayback.test.ts + +import test from "node:test"; +import assert from "node:assert/strict"; +import { startFakeWayback, PAGE_ARTICLE_TS, PAGE_ARTICLE_URL, PAGE_ARTICLE_LATER_TS } from "../../testing/web/fakeWayback.mjs"; +import { startFakeArchiveToday, AT_ARTICLE_URL, AT_ARTICLE_TS } from "../../testing/web/fakeArchiveToday.mjs"; +import { ArchiveOrgRequestError } from "../archiveOrgClient"; +import { isWaybackExcluded, WaybackCaptureRefusal, WaybackClient, WaybackExcludedError, waybackCdxUrl } from "../waybackClient"; +import { parseWaybackMemento, waybackSource } from "./wayback"; +import { archiveLookup, archiveRefusalOf, archiveSource, archiveTodaySource, nearestAcrossSources, sourceForUrl } from "./index"; +import { ArchiveTodayClient } from "./archiveTodayClient"; + +const fast = { minGapMs: 0, baseBackoffMs: 1, maxBackoffMs: 2 }; + +test("the adapter's rows, nearest and bytes are the client's, request for request", async () => { + const wb = await startFakeWayback(); + try { + const direct = new WaybackClient({ fetch: wb.fetch }, fast); + const viaSource = waybackSource(new WaybackClient({ fetch: wb.fetch }, fast)); + const rows = await direct.captures(PAGE_ARTICLE_URL); + const before = wb.requests.length; + const listed = await viaSource.listCaptures(PAGE_ARTICLE_URL); + assert.deepEqual( + listed, + rows.map((r) => ({ source: "wayback", captureTs: r.timestamp, originalUrl: r.original, mementoUrl: r.replayUrl, status: r.status, ...(r.mimetype ? { mimetype: r.mimetype } : {}) })), + ); + assert.equal(wb.requests.at(-1)?.path, wb.requests[before - 1]?.path, "the same CDX request"); + const near = await direct.closestCapture(PAGE_ARTICLE_URL, "20150601"); + assert.equal((await viaSource.closestCapture(PAGE_ARTICLE_URL, "20150601"))?.captureTs, near?.timestamp); + assert.equal(near?.timestamp, PAGE_ARTICLE_LATER_TS); + const raw = await direct.getCapture(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL, { raw: true }); + const copy = await viaSource.getCapture(`https://web.archive.org/web/${PAGE_ARTICLE_TS}/${PAGE_ARTICLE_URL}`); + assert.equal(copy.sha256, raw.sha256); + assert.equal(copy.finalTs, raw.finalTs); + assert.equal(copy.mementoUrl, `https://web.archive.org/web/${PAGE_ARTICLE_TS}/${PAGE_ARTICLE_URL}`); + assert.equal(copy.page, raw.body.toString("utf8")); + assert.equal(copy.unwrapped, true); + // Capture-time bounds go to CDX as its own from/to. + await viaSource.listCaptures(PAGE_ARTICLE_URL, { from: "2015", to: "2016" }); + assert.match(String(wb.requests.at(-1)?.path), /from=2015&to=2016/); + assert.match(waybackCdxUrl("https://a.example/", { from: "2014" }), /from=2014/); + } finally { + await wb.close(); + } +}); + +test("memento URLs: a Wayback capture's parts; the registry knows which source a copy is on", () => { + assert.deepEqual(parseWaybackMemento(`https://web.archive.org/web/${PAGE_ARTICLE_TS}id_/${PAGE_ARTICLE_URL}`), { + source: "wayback", + mementoUrl: `https://web.archive.org/web/${PAGE_ARTICLE_TS}/${PAGE_ARTICLE_URL}`, + originalUrl: PAGE_ARTICLE_URL, + captureTs: PAGE_ARTICLE_TS, + rawUrl: `https://web.archive.org/web/${PAGE_ARTICLE_TS}id_/${PAGE_ARTICLE_URL}`, + }); + assert.equal(sourceForUrl(`https://web.archive.org/web/${PAGE_ARTICLE_TS}/${PAGE_ARTICLE_URL}`)?.id, "wayback"); + assert.equal(sourceForUrl("https://archive.md/Ab3dE")?.id, "archive.today"); + assert.equal(sourceForUrl(PAGE_ARTICLE_URL), null); + assert.equal(archiveSource(undefined)?.label, "Wayback Machine"); + assert.equal(archiveSource("archive.today")?.queueKey, "platform:archive.today"); + assert.equal(archiveSource("wayback")?.queueKey, "platform:archive.org"); +}); + +test("a CDX 403 while the archive answers other URLs: EXCLUDED, typed, on the listing, the nearest and the capture", async () => { + const gone = "https://x.example/someone"; + const wb = await startFakeWayback({ excluded: [gone] }); + try { + const client = new WaybackClient({ fetch: wb.fetch }, fast); + await assert.rejects(client.captures(gone), (e: unknown) => { + assert.ok(e instanceof WaybackExcludedError); + assert.ok(e instanceof ArchiveOrgRequestError, "still an ArchiveOrgRequestError for every older catch"); + assert.equal((e as ArchiveOrgRequestError).status, 403); + assert.match((e as Error).message, /excluded from the Wayback Machine \(cause unknown\)/); + return true; + }); + await assert.rejects(client.closestCapture(gone, "2014"), (e: unknown) => isWaybackExcluded(e)); + await assert.rejects(client.getCapture("20140101000000", gone, { raw: true }), (e: unknown) => { + assert.ok(e instanceof WaybackCaptureRefusal); + assert.equal((e as WaybackCaptureRefusal).code, "excluded"); + return true; + }); + // Another URL, same archive: answered as usual. + assert.ok((await client.captures(PAGE_ARTICLE_URL)).length > 0); + assert.equal(archiveRefusalOf(new WaybackExcludedError(gone))?.code, "excluded"); + } finally { + await wb.close(); + } +}); + +test("the lookup across sources: each source its own entry — an exclusion one, the other's copies still listed", async () => { + const wb = await startFakeWayback({ excluded: [AT_ARTICLE_URL] }); + const at = await startFakeArchiveToday(); + try { + const sources = [ + waybackSource(new WaybackClient({ fetch: wb.fetch }, fast)), + archiveTodaySource(new ArchiveTodayClient({ fetch: at.fetch, sleep: async () => {} }, { minGapMs: 0 })), + ]; + const r = await archiveLookup(AT_ARTICLE_URL, { sources }); + assert.equal(r.found, 2); + assert.deepEqual( + r.sources.map((s) => [s.source, s.ok, s.refusal ?? null, s.captures.length]), + [ + ["wayback", false, "excluded", 0], + ["archive.today", true, null, 2], + ], + ); + assert.match(String(r.sources[0].error), /excluded from the Wayback Machine \(cause unknown\)/); + assert.equal(r.sources[1].captures[0].captureTs, AT_ARTICLE_TS); + const one = await archiveLookup(AT_ARTICLE_URL, { sources, source: "archive.today", limit: 1 }); + assert.deepEqual(one.sources.map((s) => [s.source, s.captures.length]), [["archive.today", 1]]); + } finally { + await wb.close(); + await at.close(); + } +}); + +test("the copy nearest a time across sources: an exclusion or none passes to the next source", async () => { + const wb = await startFakeWayback({ excluded: [AT_ARTICLE_URL] }); + const at = await startFakeArchiveToday(); + try { + const sources = [ + waybackSource(new WaybackClient({ fetch: wb.fetch }, fast)), + archiveTodaySource(new ArchiveTodayClient({ fetch: at.fetch, sleep: async () => {} }, { minGapMs: 0 })), + ]; + assert.equal((await nearestAcrossSources(AT_ARTICLE_URL, "2019", { sources }))?.source, "archive.today"); + assert.equal((await nearestAcrossSources(PAGE_ARTICLE_URL, "2014", { sources }))?.source, "wayback"); + assert.equal(await nearestAcrossSources("https://nowhere.example/", "2014", { sources }), null); + } finally { + await wb.close(); + await at.close(); + } +}); diff --git a/common/lib/archives/wayback.ts b/common/lib/archives/wayback.ts @@ -0,0 +1,83 @@ +// THE WAYBACK MACHINE AS AN ARCHIVE SOURCE (release 37 lane F): an adapter +// over the existing client (lib/waybackClient.ts) — the same requests, the +// same pacing (archive.org's: one at a time, 2 s apart, 429/503 waited out), +// the same refusals. Nothing here changes what the client does. + +import { parseWaybackUrl, waybackPageUrl, waybackRawUrl } from "../wayback"; +import { waybackClient as processWaybackClient, type WaybackCapture, type WaybackClient } from "../waybackClient"; +import { queueKeyForUrl } from "../platform"; +import { decodeCaptureBody } from "../waybackPages/extract"; +import { ArchiveRefusal, type ArchiveCaptureRow, type ArchiveMementoRef, type ArchiveSource } from "./types"; + +export const WAYBACK_QUEUE = queueKeyForUrl("https://web.archive.org/"); + +export function parseWaybackMemento(url: string): ArchiveMementoRef | null { + const ref = parseWaybackUrl(url); + if (!ref) return null; + return { + source: "wayback", + mementoUrl: waybackPageUrl(ref), + originalUrl: ref.originalUrl, + captureTs: ref.captureTs, + rawUrl: waybackRawUrl(ref), + }; +} + +export function waybackRow(c: WaybackCapture): ArchiveCaptureRow { + return { + source: "wayback", + captureTs: c.timestamp, + originalUrl: c.original, + mementoUrl: c.replayUrl, + ...(c.status ? { status: c.status } : {}), + ...(c.mimetype ? { mimetype: c.mimetype } : {}), + }; +} + +export function waybackSource(client: Pick<WaybackClient, "captures" | "closestCapture" | "getCapture"> = processWaybackClient): ArchiveSource { + return { + id: "wayback", + label: "Wayback Machine", + queueKey: WAYBACK_QUEUE, + matchesUrl: (url) => parseWaybackUrl(url) !== null, + parseMementoUrl: parseWaybackMemento, + async listCaptures(originalUrl, o = {}) { + const rows = await client.captures(originalUrl, { + ...(o.limit ? { limit: o.limit } : {}), + ...(o.from ? { from: o.from } : {}), + ...(o.to ? { to: o.to } : {}), + ...(o.signal ? { signal: o.signal } : {}), + }); + return rows.map(waybackRow); + }, + async closestCapture(url, at, o = {}) { + const c = await client.closestCapture(url, at, o.signal ? { signal: o.signal } : {}); + return c ? waybackRow(c) : null; + }, + async getCapture(memento, o = {}) { + const ref = typeof memento === "string" ? parseWaybackMemento(memento) : memento; + if (!ref?.captureTs || !ref.originalUrl) { + throw new ArchiveRefusal("wayback", "not-archived", `${typeof memento === "string" ? memento : memento.mementoUrl} is not a Wayback Machine capture's URL`); + } + const cap = await client.getCapture(ref.captureTs, ref.originalUrl, { + raw: true, + ...(o.maxBytes ? { maxBytes: o.maxBytes } : {}), + ...(o.signal ? { signal: o.signal } : {}), + }); + const final = { captureTs: cap.finalTs, originalUrl: cap.originalUrl }; + return { + source: "wayback", + body: cap.body, + mimetype: cap.mimetype, + contentType: cap.contentType, + finalTs: cap.finalTs, + originalUrl: cap.originalUrl, + mementoUrl: waybackPageUrl(final), + bytes: cap.bytes, + sha256: cap.sha256, + unwrapped: true, + page: decodeCaptureBody(cap.body, cap.contentType), + }; + }, + }; +} diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts @@ -230,7 +230,7 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = { mirror: "For a channel that MIRRORS another creator's streams: the creator's channels it copies (`of`, their slugs). The mirror scan (`pnpm ops mirror-scan`) pairs each of this channel's videos with the creator's by date and title and writes `transcripts/mirrors/<slug>.json`: which videos the creator still has public, removed or never uploaded, and which of the creator's removed videos this channel holds. Private: never published. An object without a usable `of` is dropped.", wayback: - 'A WAYBACK PAGES channel (platform `"webpage"`, `sourceKind` `"social"`): which Wayback Machine captures of pages that are not videos are in scope. `{targets: [{url, match, from?, to?, mime?, include?, exclude?}], collapse?: "digest", auto?: true}` — `match` is `"exact"` (one page), `"prefix"` (every URL under a path), `"host"` (one host) or `"domain"` (a host and its subdomains); `from`/`to` bound the capture time (a Wayback timestamp prefix, 4–14 digits, inclusive); `mime` the mimetypes kept (default `text/html`); `include`/`exclude` regex sources over a capture\'s original URL. Each capture imported (`pnpm ops import-page`, the channel page\'s **Import a capture**) becomes a page record in the channel\'s posts, its raw body kept under `pages/` (OPERATING.md, "Import from the Wayback Machine"). A target without a URL or a valid `match` is dropped; an object with no valid target is dropped. `auto: true` lets the download lane import the captures a later scan (`pnpm ops wayback-scan`, the **Captures** tab) adds, one job each at archive.org\'s pace; absent, nothing is imported unasked.', + 'A WAYBACK PAGES channel (platform `"webpage"`, `sourceKind` `"social"`): which Wayback Machine captures of pages that are not videos are in scope. `{targets: [{url, match, from?, to?, mime?, include?, exclude?}], collapse?: "digest", auto?: true}` — `match` is `"exact"` (one page), `"prefix"` (every URL under a path), `"host"` (one host) or `"domain"` (a host and its subdomains); `from`/`to` bound the capture time (a Wayback timestamp prefix, 4–14 digits, inclusive); `mime` the mimetypes kept (default `text/html`); `include`/`exclude` regex sources over a capture\'s original URL. Each capture imported (`pnpm ops import-page`, the channel page\'s **Import a capture**) becomes a page record in the channel\'s posts, its raw body kept under `pages/` (OPERATING.md, "Import from the Wayback Machine"). A target without a URL or a valid `match` is dropped; an object with no valid target is dropped. `auto: true` lets the download lane import the captures a later scan (`pnpm ops wayback-scan`, the **Captures** tab) adds, one job each at archive.org\'s pace; absent, nothing is imported unasked. Release 37 lane F: a target\'s `sources` (`["wayback", "archive.today"]`; absent = the Wayback Machine alone) says which archives hold its copies, and an archive.today copy imported into the channel is a page record like a capture (OPERATING.md, "Archived pages: the Wayback Machine and archive.today"); the form calls the kind "Archived pages".', xSearch: 'An X SEARCH channel (platform `"twitter"`, `sourceKind` `"social"`, `url` the search page): a saved X search across accounts, its records the matching posts from ANY author. `{query, since?, until?, windowMonths?, lang?, exclude?}` — `query` as X\'s search box takes it (words, `"phrases"`, `OR`, `-term`, `from:`, `to:`, `@mention`, `url:`, `filter:`, `lang:` pass through; `since:`, `until:` and `max_id:` are refused — the walk adds them); `since`/`until` the days walked between (YYYY-MM-DD; `since` inclusive, `until` exclusive; absent `until` = tomorrow, and each later fetch searches what is new); `windowMonths` each search window\'s span (1–12, default 3); `lang` a language code added as `lang:<code>`; `exclude` the handles **Never archive** hid from the leads view (lower case). A fetch walks the windows newest first through gallery-dl\'s search, resumable, at the older walk\'s pace and with its login (OPERATING.md, "X search"). Never on a site. An object without a valid query is dropped.', }; diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -235,6 +235,7 @@ const DECLARED: EnvVarDecl[] = [ { 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, 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_ARCHIVE_TODAY_ORIGIN_FILE", audience: "test", default: "unset (the real archive.today)", readBy: "common/lib/archives/archiveTodayClient.ts, common/lib/archives/index.ts", doc: "A file holding one loopback origin; while it exists, the editor's archive.today client sends every request for any archive.today name (archive.ph, archive.today, archive.is, …) there — the fake archive.today a spec starts (`common/testing/web/fakeArchiveToday.mjs`) — and never opens the archive session's browser. The editor's e2e server names a file in each slot's test data (`archive-today-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/settingsDocs.ts b/common/lib/settingsDocs.ts @@ -12,6 +12,7 @@ import { ARCHIVE_ORG_SETTINGS_FIELD_DOCS, + ARCHIVES_SETTINGS_FIELD_DOCS, ARCHIVE_STORAGE_SETTINGS_FIELD_DOCS, ATTRIBUTION_SETTINGS_FIELD_DOCS, BACKFILL_SETTINGS_FIELD_DOCS, @@ -263,6 +264,13 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings, defaults: fromObject(d.archiveOrg), }, ], + archives: [ + { + path: "archives", + docs: ARCHIVES_SETTINGS_FIELD_DOCS, + defaults: fromObject(d.archives), + }, + ], publish: [ { path: "publish", diff --git a/common/lib/settingsSchema.test.ts b/common/lib/settingsSchema.test.ts @@ -32,6 +32,7 @@ import type { StorageSettings } from "./storageLocations"; import type { ArchiveOrgFetchSettings } from "./archiveOrgTorrent"; import type { SeederSettings } from "./seederSettings"; import type { TtsSettings } from "./ttsSettings"; +import type { ArchivesSettings } from "./archives/settings"; import type { GenerationSettings } from "./generationSettings"; import type { AttributionSettings, @@ -105,6 +106,7 @@ type PreSchemaSiteSettings = { attribution: AttributionSettings; // How archive.org files are fetched: BitTorrent with seeding, else direct. archiveOrg: ArchiveOrgFetchSettings; + archives: ArchivesSettings; // The publish lane (release 18). publish: PublishSettings; // The recurring reports' lane (umtool R5). @@ -121,7 +123,7 @@ type PreSchemaSiteSettings = { type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false; const shapeUnchanged: Same<SiteSettings, PreSchemaSiteSettings> = true; -test("SiteSettings keeps its 40 fields, in file order", () => { +test("SiteSettings keeps its 41 fields, in file order", () => { assert.equal(shapeUnchanged, true); assert.deepEqual(Object.keys(siteSettingsSchema.shape), [ "adminTitle", @@ -159,6 +161,7 @@ test("SiteSettings keeps its 40 fields, in file order", () => { "backfill", "attribution", "archiveOrg", + "archives", "publish", "reportSchedule", "seeder", diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -80,6 +80,7 @@ import { import { sanitizeSeeder, type SeederSettings } from "./seederSettings"; export { SEEDER_SETTINGS_FIELD_DOCS, type SeederSettings } from "./seederSettings"; import { sanitizeTts, type TtsSettings } from "./ttsSettings"; +import { sanitizeArchives, type ArchivesSettings } from "./archives/settings"; import { sanitizeGeneration, type GenerationSettings } from "./generationSettings"; export { GENERATION_CAPS_FIELD_DOCS, @@ -97,6 +98,7 @@ export { type GenerationSettings, } from "./generationSettings"; export { ORPHEUS_TTS_SETTINGS_FIELD_DOCS, TTS_SETTINGS_FIELD_DOCS, type TtsSettings } from "./ttsSettings"; +export { ARCHIVES_SETTINGS_FIELD_DOCS, type ArchivesSettings } from "./archives/settings"; import { DEFAULT_COOKIE_MODE, isCookieMode, @@ -1879,6 +1881,9 @@ export const siteSettingsSchema = z.object({ archiveOrg: settingsField((v): ArchiveOrgFetchSettings => sanitizeArchiveOrg(v)).describe( "How archive.org files are fetched (controller/archiveOrgDownload.ts). Over BitTorrent with aria2c when the item's torrent carries the file — archive.org is the torrent's web seed, so the swarm takes load off archive.org — then seeded for a while; otherwise, or when the torrent stalls, a direct download from archive.org. Either way the file is verified against archive.org's sha1/md5. No yt-dlp.", ), + archives: settingsField((v): ArchivesSettings => sanitizeArchives(v)).describe( + "The archive sources a page import reads besides the Wayback Machine (release 37 lane F, lib/archives/): archive.today's one canonical host, its pace (one request at a time, a long gap, a rest after a 429) and whether a check it answers with is read once more through the archive session's headless browser. The Wayback Machine keeps archive.org's own client and pace. See ArchivesSettings.", + ), publish: settingsField((v): PublishSettings => sanitizePublish(v)).describe( "The publish LANE (release 18): a runner that, when the index is stale, updates it and then builds — and, where a site's own `publish.auto` (site.json) says so, deploys — what changed, one stage at a time on the `publish` queue. OFF by default; the manual stages (Publish now, Build, Deploy) work either way. See PublishSettings and common/publish/publishRunner.ts.", ), diff --git a/common/lib/waybackClient.ts b/common/lib/waybackClient.ts @@ -43,13 +43,16 @@ export function waybackReplayUrl(timestamp: string, original: string): string { export function waybackCdxUrl( url: string, - o: { limit?: number; okOnly?: boolean; closest?: string } = {}, + o: { limit?: number; okOnly?: boolean; closest?: string; from?: string; to?: string } = {}, ): string { const q = new URLSearchParams(); q.set("url", url); q.set("output", "json"); if (o.okOnly) q.set("filter", "statuscode:200"); if (o.limit) q.set("limit", String(o.limit)); + // Release 37 lane F: capture-time bounds (timestamp prefixes, inclusive). + if (o.from) q.set("from", o.from); + if (o.to) q.set("to", o.to); // Release 37: the captures nearest a time first (the page import's // `{url, at}` form). if (o.closest) { @@ -180,7 +183,15 @@ export type WaybackRawCapture = { sha256: string; }; -export type WaybackCaptureRefusalCode = "mimetype" | "too-large" | "offsite-redirect" | "redirect-loop" | "not-archived"; +export type WaybackCaptureRefusalCode = + | "mimetype" + | "too-large" + | "offsite-redirect" + | "redirect-loop" + | "not-archived" + // Release 37 lane F: the archive answered 403 for the capture (see + // WaybackExcludedError). + | "excluded"; // A capture getCapture will not hand back, with the sentence a caller shows. export class WaybackCaptureRefusal extends Error { @@ -194,6 +205,40 @@ export class WaybackCaptureRefusal extends Error { } } +// AN EXCLUDED URL (release 37 lane F): the Wayback Machine answers HTTP 403 — +// at its CDX API, or for a capture — for a URL it will not show anyone (a site +// owner's request, a legal one, a policy: it does not say which), while it +// answers every other URL as usual. That is a fact about the URL, not an +// outage, and every surface says it in these words. The error stays an +// ArchiveOrgRequestError (status 403), so every catch written before it reads +// it as it always did. +export const WAYBACK_EXCLUDED_PHRASE = "excluded from the Wayback Machine (cause unknown)"; + +export class WaybackExcludedError extends ArchiveOrgRequestError { + readonly excluded = true as const; + readonly url: string; + constructor(url: string) { + super(`${url} is ${WAYBACK_EXCLUDED_PHRASE}: the Wayback Machine answered HTTP 403 for it`, 403, false); + this.name = "WaybackExcludedError"; + this.url = url; + } +} + +// Whether `e` is the Wayback Machine refusing a URL as excluded (a CDX 403, or +// getCapture's "excluded"). +export function isWaybackExcluded(e: unknown): boolean { + return e instanceof WaybackExcludedError || (e instanceof WaybackCaptureRefusal && e.code === "excluded"); +} + +// A CDX request's error as the exclusion it is (a 403), else as it was: what a +// caller that builds its own CDX request (lane B's scan pages) wraps its +// request in. +export function waybackExcludedOf(e: unknown, url: string): unknown { + return e instanceof ArchiveOrgRequestError && !(e instanceof WaybackExcludedError) && e.status === 403 + ? new WaybackExcludedError(url) + : e; +} + export class WaybackClient { private readonly http: ArchiveOrgClient; @@ -261,11 +306,12 @@ export class WaybackClient { // Null when the Wayback Machine holds no capture of `url` that recorded a // 200. async closestCapture(url: string, at: string, o: { signal?: AbortSignal } = {}): Promise<WaybackCapture | null> { - const body = await this.http.getText( - waybackCdxUrl(url, { okOnly: true, limit: 5, closest: at }), - "application/json", - o.signal, - ); + let body: string; + try { + body = await this.http.getText(waybackCdxUrl(url, { okOnly: true, limit: 5, closest: at }), "application/json", o.signal); + } catch (e) { + throw waybackExcludedOf(e, url); + } let rows: WaybackCapture[]; try { rows = parseCdxJson(body); @@ -314,6 +360,9 @@ export class WaybackClient { if (e instanceof ArchiveOrgRequestError && (e.status === 404 || e.status === 410)) { throw new WaybackCaptureRefusal("not-archived", `the Wayback Machine holds no capture of ${url} at ${ts}`); } + if (e instanceof ArchiveOrgRequestError && e.status === 403) { + throw new WaybackCaptureRefusal("excluded", `${url} is ${WAYBACK_EXCLUDED_PHRASE}: it answered HTTP 403 for the capture at ${ts}`); + } throw e; } if (res.location !== null || (res.status >= 300 && res.status < 400)) { @@ -421,9 +470,14 @@ export class WaybackClient { // refusing (`rateLimited`) or answered an error. async captures( url: string, - o: { limit?: number; okOnly?: boolean; signal?: AbortSignal } = {}, + o: { limit?: number; okOnly?: boolean; from?: string; to?: string; signal?: AbortSignal } = {}, ): Promise<WaybackCapture[]> { - const body = await this.http.getText(waybackCdxUrl(url, o), "application/json", o.signal); + let body: string; + try { + body = await this.http.getText(waybackCdxUrl(url, o), "application/json", o.signal); + } catch (e) { + throw waybackExcludedOf(e, url); + } try { return parseCdxJson(body); } catch (e) { @@ -437,7 +491,18 @@ export class WaybackClient { // Throws ArchiveOrgRequestError when the API kept refusing or answered an // error. async cdxPage(cdxUrl: string, o: { signal?: AbortSignal } = {}): Promise<string> { - return this.http.getText(cdxUrl, "application/json", o.signal); + try { + return await this.http.getText(cdxUrl, "application/json", o.signal); + } catch (e) { + // Release 37 lane F: a 403 for the scanned URL is its exclusion. + let url = cdxUrl; + try { + url = new URL(cdxUrl).searchParams.get("url") ?? cdxUrl; + } catch { + // keep the request URL + } + throw waybackExcludedOf(e, url); + } } } diff --git a/common/lib/waybackPages/config.ts b/common/lib/waybackPages/config.ts @@ -27,8 +27,22 @@ export type WaybackTarget = { // `include` (if set) and not `exclude`. include?: string; exclude?: string; + // Release 37 lane F: the archive sources that hold this target's copies + // ("wayback", "archive.today"; lib/archives/). Absent = ["wayback"]. + sources?: WaybackTargetSource[]; }; +// The archive sources a target may name (lib/archives/types.ts +// ARCHIVE_SOURCE_IDS; repeated here because this file is a leaf). +export const WAYBACK_TARGET_SOURCES = ["wayback", "archive.today"] as const; +export type WaybackTargetSource = (typeof WAYBACK_TARGET_SOURCES)[number]; + +// The sources a target's copies are looked for on: its own, else the +// Wayback Machine alone. +export function targetSources(target: Pick<WaybackTarget, "sources">): WaybackTargetSource[] { + return target.sources?.length ? [...target.sources] : ["wayback"]; +} + export type WaybackPagesConfig = { targets: WaybackTarget[]; // How a scan folds repeated captures: "digest" = one row per distinct body. @@ -67,6 +81,11 @@ export function coerceWaybackTarget(v: unknown): WaybackTarget | undefined { if (include) out.include = include; const exclude = trimmed(r.exclude); if (exclude) out.exclude = exclude; + if (Array.isArray(r.sources)) { + const sources = [...new Set(r.sources.filter((x): x is WaybackTargetSource => (WAYBACK_TARGET_SOURCES as readonly unknown[]).includes(x)))]; + // ["wayback"] alone is the default: not written. + if (sources.length > 0 && !(sources.length === 1 && sources[0] === "wayback")) out.sources = sources; + } return out; } @@ -103,9 +122,20 @@ const WAYBACK_HOST_RE = /^(?:web|wayback)\.archive\.org$/i; // exactly. A URL that is not on the Wayback Machine is taken as the target // itself: a trailing `*` makes it a prefix, a leading `*.` a domain. // Null for anything that names no target. +// Release 37 lane F: an archive.today copy that names its page +// (archive.ph/<ts>/<page>, /newest/<page>, /oldest/<page>) is that page, +// exactly, on archive.today; a short id (archive.ph/<id>) names no page. +const ARCHIVE_TODAY_COPY_RE = + /^https?:\/\/(?:www\.)?archive\.(?:ph|today|is|li|vn|fo|md)\/(?:newest|oldest|\d{4,14}|\d{4}\.\d{2}\.\d{2}(?:-\d{6})?)\/(.+)$/i; + export function waybackTargetFromUrl(input: string): WaybackTarget | null { const raw = input.trim(); if (!raw) return null; + const at = ARCHIVE_TODAY_COPY_RE.exec(raw); + if (at) { + const inner = waybackTargetFromUrl(at[1].replace(/^(https?):\/(?!\/)/i, "$1://")); + return inner ? { url: inner.url, match: "exact", sources: ["archive.today"] } : null; + } let rest = raw; let from: string | undefined; let to: string | undefined; diff --git a/common/lib/waybackPages/parse.ts b/common/lib/waybackPages/parse.ts @@ -58,6 +58,12 @@ export function parsePagePostInfo(raw: unknown): PagePostInfo | null { out.extractorFallback = { from, fromVersion: f.fromVersion, error: typeof f.error === "string" ? f.error : "" }; } } + // Release 37 lane F: the archive source (a word; absent = the Wayback + // Machine) and its copy's URL. + const source = str(r.source); + if (source && KIND_RE.test(source.replace(/\./g, "-")) && source !== "wayback") out.source = source; + const archiveUrl = str(r.archiveUrl); + if (archiveUrl && /^https?:\/\//i.test(archiveUrl)) out.archiveUrl = archiveUrl; if (Array.isArray(r.tags)) { const tags = r.tags.filter((t): t is string => typeof t === "string" && t.trim() !== ""); if (tags.length > 0) out.tags = tags; diff --git a/common/lib/waybackPages/store-server.ts b/common/lib/waybackPages/store-server.ts @@ -44,6 +44,12 @@ export type StoredCapture = { requestedUrl?: string; // The record ids this capture made, at the last extraction. records?: string[]; + // Release 37 lane F: the archive source the copy is from (absent = the + // Wayback Machine), and the copy's URL there (archive.today's + // `https://archive.ph/<id>`). The body is the copy AS SERVED — for + // archive.today its rewritten snapshot, unwrapped each time it is read. + source?: string; + mementoUrl?: string; }; export function channelPagesDir(channelRoot: string): string { @@ -95,6 +101,10 @@ function parseStoredCapture(raw: unknown): StoredCapture | null { out.extractorFallback = { from: fb.from, fromVersion: fb.fromVersion, error: typeof fb.error === "string" ? fb.error : "" }; } if (Array.isArray(r.records)) out.records = r.records.filter((x): x is string => typeof x === "string"); + const source = s("source"); + if (source && source !== "wayback") out.source = source; + const mementoUrl = s("mementoUrl"); + if (mementoUrl) out.mementoUrl = mementoUrl; return out; } @@ -169,3 +179,24 @@ export async function countStoredCaptures(channelRoot: string): Promise<number> return 0; } } + +// The stored capture of a copy by its URL at its source (release 37 lane F: +// an archive.today short-id URL names neither page nor time, so "already +// stored" is asked by the copy's URL before anything is fetched), or null. +export async function findStoredCaptureByMemento(channelRoot: string, mementoUrl: string): Promise<StoredCaptureEntry | null> { + const want = mementoKey(mementoUrl); + for (const e of await listStoredCaptures(channelRoot)) { + if (e.capture.mementoUrl && mementoKey(e.capture.mementoUrl) === want) return e; + } + return null; +} + +// A copy's URL compared host-blind (archive.today's names are one service). +function mementoKey(url: string): string { + try { + const u = new URL(url); + return `${u.pathname}${u.search}`.replace(/\/+$/, ""); + } catch { + return url; + } +} diff --git a/common/lib/waybackPages/toPost.ts b/common/lib/waybackPages/toPost.ts @@ -35,6 +35,11 @@ export type DraftToPostContext = { capture: PageCaptureFacts; extractor: { name: string; version: number }; fallback?: { from: string; fromVersion: number; error: string }; + // Release 37 lane F: the capture is a copy on another archive source (not + // the Wayback Machine): its id and the copy's URL there. The record's + // `page.source` / `page.archiveUrl` say so, and its waybackUrl / rawUrl + // are that URL (types.ts). + source?: { id: string; mementoUrl: string }; }; function hostOf(url: string): string { @@ -60,15 +65,20 @@ export function draftToPost(draft: PageRecordDraft, ctx: DraftToPostContext): Po : undefined; const createdAt = published ?? (captureTsIso(capture.captureTs) || new Date(0).toISOString()); const ref = { captureTs: capture.captureTs, originalUrl: capture.originalUrl }; + const other = ctx.source && ctx.source.id !== "wayback" ? ctx.source : null; const page: PagePostInfo = { originalUrl: capture.originalUrl, captureTs: capture.captureTs, - waybackUrl: waybackPageUrl(ref), - rawUrl: waybackRawUrl(ref), + waybackUrl: other ? other.mementoUrl : waybackPageUrl(ref), + rawUrl: other ? other.mementoUrl : waybackRawUrl(ref), kind: draft.kind, extractor: ctx.extractor.name, extractorVersion: ctx.extractor.version, }; + if (other) { + page.source = other.id; + page.archiveUrl = other.mementoUrl; + } const title = draft.title ?? capture.title; if (title) page.title = title; if (capture.mimetype) page.mimetype = capture.mimetype; diff --git a/common/lib/waybackPages/types.ts b/common/lib/waybackPages/types.ts @@ -54,6 +54,16 @@ export type PagePostInfo = WaybackProvenance & { extractorFallback?: { from: string; fromVersion: number; error: string }; // Tags the page gives the item (Tumblr tags). tags?: string[]; + // Release 37 lane F (lib/archives/): the archive source the capture is + // from — "archive.today", … — absent for the Wayback Machine (every record + // made before sources existed). For a source that is not the Wayback + // Machine, `archiveUrl` is the copy's URL (archive.today's + // `https://archive.ph/<id>`), and `waybackUrl` / `rawUrl` hold that same + // URL (they are required, and a reader that knows no source still links + // the copy): cite by `pageArchiveLink(page)` (lib/archives/mementos.ts), + // which names the source. + source?: string; + archiveUrl?: string; }; // What an extractor hands back per record, before it becomes a Post. The diff --git a/common/lib/waybackPages/urls.ts b/common/lib/waybackPages/urls.ts @@ -4,6 +4,7 @@ // it. Client-safe: no node imports. import { isWaybackHost, parseWaybackUrl } from "../wayback"; +import { isArchiveTodayHost, parseArchiveTodayUrl } from "../archives/mementos"; // The bodies a page import keeps. Anything else is refused by its mimetype. export const PAGE_MIMETYPES = ["text/html", "text/plain", "application/json"] as const; @@ -154,6 +155,12 @@ export function isWaybackPagesUrl(url: string): boolean { } catch { return false; } + // Release 37 lane F: an archive.today copy is an archived page too (a + // short id names no page; one that names a video is import-video's). + if (isArchiveTodayHost(u.hostname)) { + const ref = parseArchiveTodayUrl(url); + return ref !== null && (!ref.originalUrl || videoPageOf(ref.originalUrl) === null); + } if (!isWaybackHost(u.hostname)) return false; const m = /^\/(?:web\/)?\d{0,14}\*?(?:[a-z]{2}_)?\/(.+)$/s.exec(u.pathname + u.search); if (!m) return false; diff --git a/common/lib/waybackPages/view.ts b/common/lib/waybackPages/view.ts @@ -18,6 +18,7 @@ import type { Post } from "../posts"; import type { PagePostInfo } from "./types"; import { waybackCaptureDate, waybackCitationLinks, type WaybackLink } from "../wayback"; import { PAGE_ORIGINAL_GONE_LABEL } from "./liveness"; +import { pageArchiveLink } from "../archives/mementos"; export const PAGE_KIND_LABELS: Record<string, string> = { generic: "Web page", @@ -62,6 +63,9 @@ export type PageCaptureView = { links: { original: WaybackLink; copy: WaybackLink }; // The original is known gone: the Wayback copy is the only copy. originalGone?: boolean; + // Release 37 lane F: the archive source when it is not the Wayback Machine + // ("archive.today"); `waybackUrl` is then that copy's URL. + source?: string; title?: string; noContent?: boolean; // The extractor-fallback sentence. @@ -77,14 +81,19 @@ export type PageCaptureView = { // it, so a record from another archive is one change here. // `originalGone`: the original is known gone (release 37 S5's check recorded // it `deleted`) — the original is then named as such (PAGE_ORIGINAL_GONE_LABEL). +// Release 37 lane F: a record from another archive source (`page.source`, +// "archive.today") names that source and links its copy (`page.archiveUrl`): +// "archive.today copy, <date>". export function pageCopyLinks( - page: Pick<PagePostInfo, "originalUrl" | "captureTs" | "waybackUrl" | "rawUrl">, + page: Pick<PagePostInfo, "originalUrl" | "captureTs" | "waybackUrl" | "rawUrl"> & Partial<Pick<PagePostInfo, "source" | "archiveUrl">>, o: { originalGone?: boolean } = {}, ): { original: WaybackLink; copy: WaybackLink; } { - const links = waybackCitationLinks(page); + const base = waybackCitationLinks(page); + const other = page.source && page.source !== "wayback" ? pageArchiveLink(page) : null; + const links = other ? { ...base, copy: { label: `${other.label} copy, ${waybackCaptureDate(page.captureTs)}`, url: other.url } } : base; return o.originalGone ? { ...links, original: { ...links.original, label: PAGE_ORIGINAL_GONE_LABEL } } : links; } @@ -157,8 +166,9 @@ export function pageCaptureView( captureTs: page.captureTs, captureDate: waybackCaptureDate(page.captureTs), originalUrl: page.originalUrl, - waybackUrl: page.waybackUrl, + waybackUrl: page.archiveUrl ?? page.waybackUrl, links: pageCopyLinks(page, { originalGone }), + ...(page.source && page.source !== "wayback" ? { source: page.source } : {}), ...(originalGone ? { originalGone: true } : {}), ...(page.title ? { title: page.title } : {}), ...(page.noContent ? { noContent: true } : {}), diff --git a/common/publish/findCopyPages.ts b/common/publish/findCopyPages.ts @@ -34,6 +34,7 @@ // 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 { nearestAcrossSources } from "../lib/archives/index"; import path from "node:path"; import type { Paths } from "../lib/paths"; import type { Citation, PageCitation, PostCitation } from "../lib/citations/schema"; @@ -234,7 +235,18 @@ export function defaultFindPageCopiesDeps(paths: Paths, o: { check?: CheckOrigin 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 } : {}), + // Release 37 lane F: across archive sources (the Wayback Machine, then + // archive.today); a row's copy URL is its replayUrl, so the import reads + // whichever source holds it. A Wayback client given here keeps the + // Wayback-only lookup (tests). + nearest: o.client + ? (url, at, signal) => client.closestCapture(url, at, signal ? { signal } : {}) + : async (url, at, signal) => { + const row = await nearestAcrossSources(url, at, signal ? { signal } : {}); + return row + ? { timestamp: row.captureTs, original: row.originalUrl, status: row.status ?? "200", replayUrl: row.mementoUrl, ...(row.mimetype ? { mimetype: row.mimetype } : {}) } + : null; + }, importCapture: (io) => importPage({ paths, slug: io.slug, url: io.url, client, ...(io.signal ? { signal: io.signal } : {}), ...(io.onLog ? { onLog: io.onLog } : {}) }), now: () => new Date(), }; @@ -325,9 +337,11 @@ export async function findPageCopies(opts: { 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`; + item.detail = `the original is gone (${checked.reason}), and no archive source holds a copy of it that recorded a page`; } else { - const waybackUrl = waybackPageUrl({ captureTs: near.timestamp, originalUrl: near.original }); + // The copy's own URL (a Wayback replay URL, or an archive.today + // copy's from the source registry — release 37 lane F). + const waybackUrl = near.replayUrl || waybackPageUrl({ captureTs: near.timestamp, originalUrl: near.original }); item.capture = { timestamp: near.timestamp, original: near.original, waybackUrl }; if (dryRun) { item.outcome = "would-import"; diff --git a/common/testing/web/fakeArchiveToday.d.mts b/common/testing/web/fakeArchiveToday.d.mts @@ -0,0 +1,33 @@ +export type FakeArchiveTodayCopy = { id: string; original: string; timestamp: string; page: () => string }; + +export const COPIES: FakeArchiveTodayCopy[]; +export const AT_ARTICLE_URL: string; +export const AT_ARTICLE_ID: string; +export const AT_ARTICLE_TS: string; +export const AT_ARTICLE_LATER_ID: string; +export const AT_ARTICLE_LATER_TS: string; +export const AT_CHECKED_URL: string; +export const AT_CHECKED_ID: string; +export const AT_CHECKED_TS: string; +export const CHALLENGE_HTML: string; + +export function httpDateOf(ts: string): string; +export function wrapLikeArchiveToday( + html: string, + o: { id: string; original: string; timestamp: string; host?: string }, +): string; +export function fixtureCopy(name: string, o: { id: string; original: string; timestamp: string }): FakeArchiveTodayCopy; + +export type FakeArchiveToday = { + base: string; + requests: { path: string; at: number; ua: string }[]; + fetch(url: string | URL, init?: RequestInit): Promise<Response>; + close(): Promise<void>; +}; + +export function startFakeArchiveToday(opts?: { + copies?: FakeArchiveTodayCopy[]; + challenge?: string[] | "all"; + challengeStatus?: number; + busyTimes?: number; +}): Promise<FakeArchiveToday>; diff --git a/common/testing/web/fakeArchiveToday.mjs b/common/testing/web/fakeArchiveToday.mjs @@ -0,0 +1,240 @@ +// A fake archive.today on loopback (release 37 lane F): timemaps, copies +// wrapped the way archive.today serves them, its redirects, a check page and +// "too many requests". No test reaches the real archive.today. +// +// const at = await startFakeArchiveToday(); +// at.fetch a fetch that sends https://archive.ph/… (any of its names) here +// at.base the loopback origin +// at.requests every request path, in order, with its time (`at`) +// await at.close() +// +// Routes (every name — archive.ph, archive.today, archive.is, … — is one): +// GET /timemap/<original> link format: rel="original", then one rel="memento" +// (first/last marked) per copy of <original>, oldest +// first; 404 when it holds none +// GET /<id> the copy, wrapped (wrapLikeArchiveToday), with +// Memento-Datetime and Link (rel="original", +// rel="memento") headers; 404 for an unknown id +// GET /<ts>/<original> 302 to the copy of <original> nearest <ts> +// GET /newest/<original> 302 to its newest copy; /oldest/ to its oldest +// opts.challenge: ids (or "all") answered with a CAPTCHA page instead of the +// copy (opts.challengeStatus, default 200 — archive.today also uses 429/503) +// opts.busyTimes: the first N requests answer a plain 429 (Retry-After: 2) +// opts.copies: the copies held (default COPIES) + +import http from "node:http"; +import { readFileSync } from "node:fs"; + +// ─── Wrapping a page the way archive.today serves its copy ─── +// +// archive.today's snapshot (as known 2026-10-20; synthetic): its own header +// bar (`#HEADER`: the "saved from" URL box, the capture's <time>) above +// `#CONTENT`, which holds the page; scripts gone; every link out of the copy +// rewritten to `https://<host>/o/<id>/<absolute url>`; every image served +// from its own cache (`https://<host>/<id>/<hash>.<ext>`) with the original +// kept as `old-src`. The page's title and <meta>s stay in the <head>. + +const abs = (href, base) => { + try { + return new URL(href, base).toString(); + } catch { + return href; + } +}; + +const hash = (s) => { + let h = 2166136261; + for (const ch of s) h = Math.imul(h ^ ch.codePointAt(0), 16777619) >>> 0; + return h.toString(16).padStart(8, "0"); +}; + +const isoOf = (ts) => `${ts.slice(0, 4)}-${ts.slice(4, 6)}-${ts.slice(6, 8)}T${ts.slice(8, 10)}:${ts.slice(10, 12)}:${ts.slice(12, 14)}Z`; +export const httpDateOf = (ts) => new Date(isoOf(ts)).toUTCString(); + +export function wrapLikeArchiveToday(html, { id, original, timestamp, host = "archive.ph" }) { + const headEnd = html.search(/<\/head\s*>/i); + const head = headEnd >= 0 ? html.slice(0, headEnd) : ""; + const title = /<title\b[^>]*>([\s\S]*?)<\/title\s*>/i.exec(head)?.[1] ?? ""; + const metas = (head.match(/<meta\b[^>]*>/gi) ?? []).filter((m) => !/charset/i.test(m)).join("\n"); + const bodyMatch = /<body\b[^>]*>([\s\S]*?)<\/body\s*>/i.exec(html); + let body = bodyMatch ? bodyMatch[1] : html; + body = body.replace(/<script\b[\s\S]*?<\/script\s*>/gi, ""); + body = body.replace(/(<a\b[^>]*?\shref\s*=\s*)(["'])(.*?)\2/gi, (m, pre, q, href) => { + if (href.startsWith("#") || /^(?:javascript|mailto):/i.test(href)) return m; + return `${pre}${q}https://${host}/o/${id}/${abs(href.replace(/&amp;/g, "&"), original).replace(/&/g, "&amp;")}${q}`; + }); + body = body.replace(/(<img\b[^>]*?)\ssrc\s*=\s*(["'])(.*?)\2/gi, (m, pre, q, src) => { + const orig = abs(src, original); + const ext = (/\.(jpe?g|png|gif|webp)(?:[?#]|$)/i.exec(orig)?.[1] ?? "jpg").toLowerCase(); + return `${pre} old-src=${q}${orig}${q} src=${q}https://${host}/${id}/${hash(orig)}.${ext}${q}`; + }); + return `<!DOCTYPE html> +<html prefix="og: http://ogp.me/ns# article: http://ogp.me/ns/article#" itemscope="" itemtype="http://schema.org/Article" style="background-color:#eee"> +<head> +<meta http-equiv="Content-Type" content="text/html;charset=utf-8"> +<meta name="robots" content="index,noarchive"> +<link rel="canonical" href="https://${host}/${id}"> +<meta property="og:url" content="https://${host}/${id}"> +<title>${title}</title> +${metas} +</head> +<body style="margin:0"> +<center><div id="HEADER" style="background-color:#eee;padding:8px"> +<table style="width:1028px"><tr> +<td><a href="https://${host}/" style="display:block"><img alt="archive.today" src="https://${host}/apple-touch-icon.png" style="width:48px"></a></td> +<td> +<form action="https://${host}/search/" method="get" style="display:inline"> +<input type="text" name="q" value="${original.replace(/&/g, "&amp;").replace(/"/g, "&quot;")}" style="width:600px"> +</form> +<div>webpage capture</div> +<div>Saved from <a href="https://${host}/o/${id}/${original}">${new URL(original).hostname}</a> · <time itemprop="pubdate" datetime="${isoOf(timestamp)}">${httpDateOf(timestamp)}</time></div> +<div><a href="https://${host}/${id}/image">screenshot</a> · <a href="https://${host}/newest/${original}">all snapshots from host</a></div> +</td></tr></table> +</div></center> +<div id="CONTENT" style="position:relative"> +<div class="html" style="text-align:left"> +${body} +</div> +</div> +<div id="FOOTER" style="text-align:center;color:#888">archive.today</div> +</body> +</html>`; +} + +// ─── The copies it holds ─── + +export const AT_ARTICLE_URL = "https://journal.example/2019/05/deleted-notes.html"; +export const AT_ARTICLE_ID = "Ab3dE"; +export const AT_ARTICLE_TS = "20190512083000"; +export const AT_ARTICLE_LATER_ID = "Fg7hJ"; +export const AT_ARTICLE_LATER_TS = "20200101101500"; +// A copy held only behind a check (opts.challenge default: none). +export const AT_CHECKED_URL = "https://checked.example/page.html"; +export const AT_CHECKED_ID = "Kl9mN"; +export const AT_CHECKED_TS = "20210303030303"; + +const articleHtml = (version) => `<!doctype html> +<html lang="en"><head><meta charset="utf-8"> +<title>Notes I Later Deleted | Journal</title> +<meta property="og:title" content="Notes I Later Deleted"> +<meta property="article:published_time" content="2019-05-11T20:00:00Z"> +<meta name="author" content="Sam Example"> +<script>var tracker = 1;</script> +</head><body> +<nav><a href="/">Home</a> <a href="/archive">Archive</a></nav> +<article> +<header><h1>Notes I Later Deleted</h1><time datetime="2019-05-11T20:00:00Z">May 11, 2019</time></header> +<p>These are the notes from the meeting, written down the same night so that nothing would be lost to memory.</p> +<p>The minutes themselves are on <a href="/2019/05/minutes.html">the minutes page</a>, and the group's own account is at <a href="https://other.example/account">other.example</a>.</p> +<img src="/img/whiteboard.png" alt="The whiteboard after the meeting"> +${version > 1 ? "<p>Edit: a second meeting is planned.</p>" : ""} +</article> +<footer>Journal, 2019</footer> +</body></html>`; + +export const COPIES = [ + { id: AT_ARTICLE_ID, original: AT_ARTICLE_URL, timestamp: AT_ARTICLE_TS, page: () => articleHtml(1) }, + { id: AT_ARTICLE_LATER_ID, original: AT_ARTICLE_URL, timestamp: AT_ARTICLE_LATER_TS, page: () => articleHtml(2) }, + { + id: AT_CHECKED_ID, + original: AT_CHECKED_URL, + timestamp: AT_CHECKED_TS, + page: () => "<html><head><title>Checked</title></head><body><main><p>A page held behind a check, every word invented for a test.</p></main></body></html>", + }, +]; + +// Lane C's synthetic fixtures (a 2016 status page, a 2012 Tumblr post) as +// copies, for the "same records either way" checks. +const FIXTURES = new URL("../../lib/waybackPages/extractors/__fixtures__/", import.meta.url); +export function fixtureCopy(name, { id, original, timestamp }) { + return { id, original, timestamp, page: () => readFileSync(/* turbopackIgnore: true */ new URL(name, FIXTURES), "utf8") }; +} + +export const CHALLENGE_HTML = `<!DOCTYPE html><html><head><title>archive.ph</title> +<script src="https://www.google.com/recaptcha/api.js" async defer></script></head> +<body><form method="post" action="/"><p>Please complete the security check to access archive.ph</p> +<div class="g-recaptcha" data-sitekey="synthetic-site-key"></div><input type="submit" value="Submit"></form></body></html>`; + +// ─── The server ─── + +const linkTs = (c) => httpDateOf(c.timestamp); + +export async function startFakeArchiveToday(opts = {}) { + const copies = opts.copies ?? COPIES; + const challenge = opts.challenge ?? []; + const challengeStatus = opts.challengeStatus ?? 200; + let busy = opts.busyTimes ?? 0; + const requests = []; + const host = "archive.ph"; + const checked = (id) => challenge === "all" || (Array.isArray(challenge) && challenge.includes(id)); + const of = (original) => copies.filter((c) => c.original === original).sort((a, b) => a.timestamp.localeCompare(b.timestamp)); + const server = http.createServer((req, res) => { + const u = new URL(req.url ?? "/", "http://fake"); + const pathAndQuery = decodeURI(u.pathname) + u.search; + requests.push({ path: pathAndQuery, at: Date.now(), ua: String(req.headers["user-agent"] ?? "") }); + const send = (status, type, body, headers = {}) => { + res.writeHead(status, { "content-type": type, ...headers }); + res.end(body); + }; + if (busy > 0) { + busy--; + return send(429, "text/html", "<html><body><h1>429 Too Many Requests</h1></body></html>", { "retry-after": "2" }); + } + if (challenge === "all") return send(challengeStatus, "text/html; charset=utf-8", CHALLENGE_HTML); + const rest = pathAndQuery.replace(/^\/+/, ""); + const tm = /^timemap\/(.+)$/.exec(rest); + if (tm) { + const list = of(tm[1]); + if (list.length === 0) return send(404, "text/plain", "not found"); + const lines = [ + `<${tm[1]}>; rel="original"`, + `<https://${host}/timegate/${tm[1]}>; rel="timegate"`, + `<https://${host}/timemap/${tm[1]}>; rel="self"; type="application/link-format"; from="${linkTs(list[0])}"; until="${linkTs(list[list.length - 1])}"`, + ...list.map((c, i) => { + const rel = list.length === 1 ? "first last memento" : i === 0 ? "first memento" : i === list.length - 1 ? "last memento" : "memento"; + return `<https://${host}/${c.id}>; rel="${rel}"; datetime="${linkTs(c)}"`; + }), + ]; + return send(200, "application/link-format", lines.join(",\n") + "\n"); + } + const pick = /^(newest|oldest)\/(.+)$/.exec(rest); + if (pick) { + const list = of(pick[2]); + if (list.length === 0) return send(404, "text/plain", "not found"); + const c = pick[1] === "newest" ? list[list.length - 1] : list[0]; + return send(302, "text/html", "", { location: `https://${host}/${c.id}` }); + } + const near = /^(\d{4,14}|\d{4}\.\d{2}\.\d{2}(?:-\d{6})?)\/(.+)$/.exec(rest); + if (near) { + const list = of(near[2]); + if (list.length === 0) return send(404, "text/plain", "not found"); + // Nearest in time, as archive.today answers. + const ms = (ts) => { + const p = ts.padEnd(14, "0"); + return Date.UTC(+p.slice(0, 4), Math.max(0, +p.slice(4, 6) - 1), Math.max(1, +p.slice(6, 8)), +p.slice(8, 10), +p.slice(10, 12), +p.slice(12, 14)); + }; + const want = ms(near[1].replace(/[.-]/g, "")); + const c = [...list].sort((a, b) => Math.abs(ms(a.timestamp) - want) - Math.abs(ms(b.timestamp) - want))[0]; + return send(302, "text/html", "", { location: `https://${host}/${c.id}` }); + } + const one = /^([A-Za-z0-9]{4,6})$/.exec(rest); + if (one) { + const c = copies.find((x) => x.id === one[1]); + if (!c) return send(404, "text/html", "<html><body>No such page</body></html>"); + if (checked(c.id)) return send(challengeStatus, "text/html; charset=utf-8", CHALLENGE_HTML); + return send(200, "text/html; charset=utf-8", wrapLikeArchiveToday(c.page(), { id: c.id, original: c.original, timestamp: c.timestamp, host }), { + "memento-datetime": linkTs(c), + link: `<${c.original}>; rel="original", <https://${host}/timemap/${c.original}>; rel="timemap"; type="application/link-format", <https://${host}/${c.id}>; rel="memento"; datetime="${linkTs(c)}"`, + }); + } + return send(404, "text/plain", "not found"); + }); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + const base = `http://127.0.0.1:${server.address().port}`; + return { + base, + requests, + fetch: (url, init) => fetch(String(url).replace(/^https?:\/\/(?:www\.)?archive\.(?:ph|today|is|li|vn|fo|md)/, base), init), + close: () => new Promise((r) => server.close(() => r())), + }; +} diff --git a/common/testing/web/fakeWayback.d.mts b/common/testing/web/fakeWayback.d.mts @@ -58,6 +58,8 @@ export function startFakeWayback(opts?: { streamBusyTimes?: number; // (release 37) the page captures served raw (default PAGE_CAPTURES + PAGE_CAPTURES_SPLIT). pageCaptures?: FakePageCapture[]; + // (release 37 lane F) originals CDX and their captures answer 403 for. + excluded?: string[]; // (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 diff --git a/common/testing/web/fakeWayback.mjs b/common/testing/web/fakeWayback.mjs @@ -35,6 +35,8 @@ // A capture's `digest` is its own when it names one, else DIGEST<timestamp>. // opts.scanRefuseFrom: the Nth scan request (1-based) and every one after answer 503. // opts.streamBusyTimes: the first N stream requests answer 429 (Retry-After: 1). +// opts.excluded: (release 37 lane F) originals the archive answers 403 for — CDX and +// their captures — while every other URL answers as usual. import http from "node:http"; @@ -314,6 +316,7 @@ export async function startFakeWayback(opts = {}) { const requests = []; let busy = opts.busyTimes ?? 0; let down = opts.downTimes ?? 0; + const excluded = opts.excluded ?? []; let scanRequests = 0; // Release 37 (lane E): Save Page Now's state. const spn = { @@ -337,6 +340,15 @@ export async function startFakeWayback(opts = {}) { res.writeHead(status, { "content-type": type, ...headers }); res.end(body); }; + // ─── Release 37 (lane F): an EXCLUDED URL — CDX and its captures answer + // 403, as the Wayback Machine does for a URL it will not show anyone + // (opts.excluded: the originals). Every other URL answers as usual. + if (excluded.length > 0) { + const asked = u.pathname === "/cdx/search/cdx" ? (u.searchParams.get("url") ?? "") : /^\/web\/\d{1,14}(?:[a-z]{2}_)?\/(.+)$/.exec(u.pathname + u.search)?.[1] ?? ""; + if (asked && excluded.includes(asked)) { + return send(403, "text/html", "<p>Sorry. This URL has been excluded from the Wayback Machine.</p>"); + } + } // 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); diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,8 @@ # Changelog ## [Unreleased] +- **archive.today copies are page records too, like Wayback captures.** The channel kind is now **Archived pages** on the New channel form (paste an archive.today copy's URL, `archive.ph/newest/<page>`, and the channel's target is that page on archive.today), and each target says where its copies are looked for: the Wayback Machine, archive.today, or both. The channel page's **Import a capture** takes an archive.today copy's URL (`archive.ph/<id>`, or any of its other names), or the page's own URL, a date and **on archive.today** for the copy nearest that date; the copy is kept as archive.today served it and read without its header bar, links back to the pages they pointed at, so a tweet, a Tumblr post or an article gives the same records it would from the Wayback Machine — each saying it came from archive.today and linking that copy, its images archive.today's own copies. archive.today is asked one request at a time, eight seconds apart; when it says "too many requests" the import stops with a sentence and nothing more is asked of it for half an hour. When it answers with a CAPTCHA instead of the copy, the import is refused and never reads the CAPTCHA as a page: **Connect archive session** (on the channel page, and in Settings → Archive sources) opens a window on the editor's machine to pass the check once, and the next import reads through it; nothing is ever solved for you. **Look up a page** lists every copy each archive holds of a page, with an Import button on each. From a terminal: `pnpm ops import-page` takes `"source": "archive.today"`, `pnpm ops archive-lookup` lists the copies, and `pnpm archilyzer archive lookup <url>` runs without the editor. Needs a restart of the editor. +- **A page the Wayback Machine will not show says so.** When the Wayback Machine answers "forbidden" for one page while it answers others, that page is excluded from it, and Wayback lookups, page imports and archive lookups now say "excluded from the Wayback Machine (cause unknown)" instead of reporting an error. - **Save an X search across accounts, and see who keeps saying it.** Paste an X search page's URL (as copied from X's search box) into the New channel form, or choose **X search** as the platform and type a query: it makes an X search channel whose records are the matching posts from any account. The query is X's own — OR, "quotes", -term, from:, to:, @name, url:, filter:, lang: — and its dates are the channel's **Since** and **Until** (a pasted URL's since:/until: are moved there; typed into the query they are refused with a sentence). Fetch posts searches backwards a window at a time (3 months, or your **Window**), newest first, at the older walk's pace and with its X login; a run cut short resumes where it stopped, later fetches search only the new days, and a new query starts afresh. The channel page's **Leads** lists the accounts by how many matching posts they made, with their first and last day and a sample: **Archive this account** creates `<handle>-x` on no site and starts its fetch, **Never archive** hides the account (Restore brings it back), and an account an X channel already archives says so. An X search channel is never put on a site. From a terminal: `pnpm ops create-channel` with the search URL, `pnpm ops fetch-posts`, `pnpm ops get channel <slug> --leads` and `pnpm ops x-search-lead`; the MCP has `x_search_leads`. Nothing calls a model. Needs a restart of the editor. - **A forum thread's fetch resumes where it stopped instead of reading the thread again.** A forum channel now keeps two places: how far it has caught up with the newest posts, and where its walk back through the older pages stands. **Fetch posts** reads from the last page down to the newest post it already holds, then jumps straight to the older pages it has yet to read — a run capped at a few pages ("Latest N pages") no longer loses the older place, and a page whose posts are all held is stepped past without counting against the cap. Pages that shifted because posts were deleted are still read without a gap. **Full re-walk** (it replaces "Re-fetch full history" on a forum channel) asks first, with the page count and how long it takes at the channel's pace, then reads every page from the last to page 1: edited posts are updated, and posts no page shows any more are counted in the log and kept. The panel's status line says where both stand — "pages read 2338–2600 of 2600 · history to page 1 remaining: 2337 pages (~9.7 h)". The older place is checked against the pages the archive holds at every run, so a channel whose place was overwritten by the old single resume point heals on its next fetch. A page that reads empty — as one can just after a browser check clears — is loaded once more before the fetch stops on it. **Retry after a block** (the Forum session section) makes Fetch posts wait out a browser check that will not clear or a refused page — 30 minutes, then try again, up to 12 tries, say — and never retries a captcha or a login; `pnpm ops fetch-posts` takes `"retryOnBlock": {"minutes": 30, "max": 12}` (or `true` for the saved setting). Needs a restart of the editor. - **Is a Wayback page's original still up? The channel page says, and can ask the Wayback Machine to save one now.** A Wayback pages channel's page has **Originals**: **Check originals** asks each record's original address at its own site — never the Wayback Machine — once per address, a few seconds apart, and the page lists every original that is gone (404 or 410, or X's, Tumblr's, Google Docs' or YouTube's "does not exist" page) with "the only copy" linking its Wayback copy; a suspended account or a document no longer shared reads as unavailable, and anything else (a wall, an outage, a redirect to another site) as an error, never as gone. Gone records read as deleted wherever a deleted post does. **Save Page Now** — "Ask the Wayback Machine to capture this now" — takes any address, or a record whose original is still up (**Capture now**): archive.org captures the page, the job waits for it, and the new capture is imported into the channel. It needs your archive.org S3 keys (`ARCHIVE_ORG_S3_ACCESS` and `ARCHIVE_ORG_S3_SECRET` in the editor's environment, or in the mode-600 file `archiveOrg.s3KeyFile` names); without them the button is off and says why, and the keys are never logged. From a terminal: `pnpm ops check-post-availability`, `pnpm ops save-page-now` (`dryRun` first). Needs a restart of the editor. diff --git a/editor/app/api/ops/archive-lookup/route.ts b/editor/app/api/ops/archive-lookup/route.ts @@ -0,0 +1,34 @@ +import { NextResponse } from "next/server"; +import { archiveLookupAction } from "../../../channels/[slug]/waybackPagesActions"; +import { OpsInputError, ops, opsFail, optPositiveInt, optString, reqString } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { url, source?, limit? } -> { ok: true, url, found, sources: [{ source, +// label, ok, captures: [{ source, captureTs, originalUrl, mementoUrl, +// status?, mimetype? }], refusal?, error? }] } +// +// THE COPIES OF A PAGE across archive sources (release 37 lane F, +// common/lib/archives/): the Wayback Machine (its CDX API, archive.org's pace) +// and archive.today (its timemap, one request at a time with a long gap), in +// that order, or only `source` ("wayback" | "archive.today"). At most `limit` +// per source (default 50, at most 500), oldest first. A source that refuses is +// its own entry's sentence — `refusal: "excluded"` (the Wayback Machine +// answered 403 for the URL: "excluded from the Wayback Machine (cause +// unknown)"), "challenge" (archive.today put a check in front: Connect archive +// session), "rate-limited" (a 429: the client rests) — and the others still +// answer. Read only; nothing is stored. `wayback-lookup` stays as it is. +const MAX_LIMIT = 500; + +export async function POST(request: Request) { + return ops(request, ["url", "source", "limit"], async (body) => { + const url = reqString(body, "url"); + if (!/^https?:\/\/[^\s]+$/.test(url)) throw new OpsInputError(`"url" must be an http(s) URL`); + const source = optString(body, "source")?.trim() || undefined; + const limit = optPositiveInt(body, "limit") ?? 50; + if (limit > MAX_LIMIT) throw new OpsInputError(`"limit" is at most ${MAX_LIMIT}`); + const r = await archiveLookupAction(url, source, limit); + if (!r.ok) return opsFail(r.error, 400); + return NextResponse.json({ ok: true, ...r.lookup }); + }); +} diff --git a/editor/app/api/ops/import-page/route.ts b/editor/app/api/ops/import-page/route.ts @@ -19,16 +19,24 @@ export const dynamic = "force-dynamic"; // Every refusal is the controller's sentence: 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 X is private. +// +// Release 37 lane F: `url` may be an archive.today copy (https://archive.ph/<id>, +// /<ts>/<page>, /newest/<page>), or the page's own URL with `at` and +// `source: "archive.today"` for its copy nearest that date — an import-page +// job on the `platform:archive.today` queue, at archive.today's pace. A +// refusal at the source is in the log's result as `refusal` ("excluded", +// "challenge", "rate-limited", …). export async function POST(request: Request) { - return ops(request, ["slug", "url", "at", "dryRun"], async (body) => { + return ops(request, ["slug", "url", "at", "source", "dryRun"], async (body) => { const slug = reqSlug(body, "slug"); const url = reqString(body, "url"); const at = optString(body, "at")?.trim() || undefined; + const source = optString(body, "source")?.trim() || undefined; if (optBool(body, "dryRun") === true) { - const r = await importPageDryRunAction(slug, url, at); + const r = await importPageDryRunAction(slug, url, at, source); if (!r.ok) return NextResponse.json({ ok: false, error: r.error }, { status: 400 }); return NextResponse.json(r); } - return jobResponse(await importPageAction(slug, url, at, "ops")); + return jobResponse(await importPageAction(slug, url, at, "ops", source)); }); } diff --git a/editor/app/api/ops/wayback-lookup/route.ts b/editor/app/api/ops/wayback-lookup/route.ts @@ -1,5 +1,6 @@ import { NextResponse } from "next/server"; import { ArchiveOrgRequestError } from "yt-dlp-transcript-common/lib/archiveOrgClient"; +import { isWaybackExcluded } from "yt-dlp-transcript-common/lib/waybackClient"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { recordWebpageUrl, waybackLookup } from "yt-dlp-transcript-common/publish/findCopy"; import { OpsInputError, ops, opsFail, optBool, optPositiveInt, optString, reqSlug, reqVideoId } from "../_lib"; @@ -17,6 +18,9 @@ export const dynamic = "force-dynamic"; // archive.org's manners (one at a time, a 2 s gap, the project's User-Agent, // 429s waited out a few times, then a 502). Read only; nothing is fetched. // `find-copy` is what fetches a gone recording's windows from a capture. +// Release 37 lane F: a URL the Wayback Machine answers 403 for is EXCLUDED +// ("excluded from the Wayback Machine (cause unknown)"): a 403 with +// `refusal: "excluded"`. `archive-lookup` asks every archive source. const MAX_LIMIT = 500; export async function POST(request: Request) { @@ -43,6 +47,9 @@ export async function POST(request: Request) { const r = await waybackLookup(url, { okOnly: optBool(body, "okOnly") === true, limit }); return NextResponse.json({ ok: true, url, found: r.captures.length, captures: r.captures }); } catch (e) { + // Release 37 lane F: a 403 for this URL while the archive answers is an + // exclusion — a fact about the URL, not an outage. + if (isWaybackExcluded(e)) return opsFail((e as Error).message, 403, { refusal: "excluded" }); if (e instanceof ArchiveOrgRequestError) return opsFail(e.message, 502); throw e; } diff --git a/editor/app/channels/[slug]/components/WaybackPageRecords.tsx b/editor/app/channels/[slug]/components/WaybackPageRecords.tsx @@ -69,7 +69,7 @@ export function WaybackPageRecords({ slug, rows }: { slug: string; rows: Wayback <img data-page-shot={r.id} src={r.shot} - alt={`Screenshot of the Wayback Machine copy, ${r.view.captureDate}`} + alt={`Screenshot of the ${r.view.links.copy.label}`} className="max-h-[32rem] max-w-full self-start rounded border border-border object-contain object-top" /> )} @@ -82,6 +82,7 @@ export function WaybackPageRecords({ slug, rows }: { slug: string; rows: Wayback <a href={r.view.waybackUrl} target="_blank" rel="noreferrer" className="font-mono text-xs underline underline-offset-2"> {r.view.captureDate} </a> + {r.view.source && <span className="ml-2 text-xs text-muted-foreground">{r.view.links.copy.label.replace(/ copy, .*$/, "")}</span>} </td> </tr> ))} diff --git a/editor/app/channels/[slug]/components/WaybackPagesPanel.tsx b/editor/app/channels/[slug]/components/WaybackPagesPanel.tsx @@ -9,8 +9,12 @@ import { useState } from "react"; import Link from "next/link"; import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; import { cancelJobAction } from "../../../jobs/actions"; -import { importPageAction, reextractPagesAction } from "../waybackPagesActions"; +import { archiveLookupAction, importPageAction, reextractPagesAction } from "../waybackPagesActions"; import { WaybackPageRecords, type WaybackPageRecordRow } from "./WaybackPageRecords"; +import { ConnectArchiveSession } from "../../../settings/components/ArchiveSessionSection"; +import type { ArchiveSessionStatus } from "yt-dlp-transcript-common/lib/archives/archiveTodaySession"; +import type { ArchiveLookup } from "yt-dlp-transcript-common/lib/archives/index"; +import { archiveSourceLabel, isArchiveTodayUrl } from "yt-dlp-transcript-common/lib/archives/mementos"; // A record's row: its capture's view and its shot (WaybackPageRecords.tsx). export type WaybackPagesRecordRow = WaybackPageRecordRow; @@ -18,8 +22,10 @@ export type WaybackPagesRecordRow = WaybackPageRecordRow; export type WaybackPagesState = { recordCount: number; captureCount: number; - targets: { url: string; match: string; from?: string; to?: string }[]; + targets: { url: string; match: string; from?: string; to?: string; sources?: string[] }[]; recent: WaybackPagesRecordRow[]; + // Release 37 lane F: archive.today's check, passed once in Connect. + archiveSession?: ArchiveSessionStatus; }; const MATCH_LABEL: Record<string, string> = { @@ -38,6 +44,9 @@ function atFromDate(v: string): string { export function WaybackPagesPanel({ slug, state }: { slug: string; state: WaybackPagesState }) { const [url, setUrl] = useState(""); const [date, setDate] = useState(""); + // Release 37 lane F: where the capture nearest a date is looked for (a + // copy's URL names its own source). + const [source, setSource] = useState("wayback"); const [importJob, setImportJob] = useState<string | null>(null); const [reextractJob, setReextractJob] = useState<string | null>(null); const input = "rounded border border-border bg-card px-2 py-1 text-sm font-mono"; @@ -62,6 +71,9 @@ export function WaybackPagesPanel({ slug, state }: { slug: string; state: Waybac {t.from || t.to ? ( <span className="text-muted-foreground"> · captured {t.from ?? "…"}–{t.to ?? "…"}</span> ) : null} + {t.sources?.length ? ( + <span className="text-muted-foreground"> · on {t.sources.map((x) => archiveSourceLabel(x)).join(" and ")}</span> + ) : null} </li> ))} </ul> @@ -74,10 +86,10 @@ export function WaybackPagesPanel({ slug, state }: { slug: string; state: Waybac value={url} onChange={(e) => setUrl(e.target.value)} aria-label="capture URL" - placeholder="https://web.archive.org/web/20140305120000/https://…" + placeholder="https://web.archive.org/web/20140305120000/https://… or https://archive.ph/…" className={`${input} w-[36rem] max-w-full`} /> - <label className="flex items-center gap-2 text-sm"> + <label className="flex flex-wrap items-center gap-2 text-sm"> <span>Nearest to</span> <input type="date" @@ -86,10 +98,29 @@ export function WaybackPagesPanel({ slug, state }: { slug: string; state: Waybac aria-label="capture date" className="rounded border border-border bg-card px-2 py-1 text-sm" /> + <span>on</span> + <select + value={source} + onChange={(e) => setSource(e.target.value)} + aria-label="capture source" + disabled={isArchiveTodayUrl(url)} + className="rounded border border-border bg-card px-2 py-1 text-sm" + > + <option value="wayback">the Wayback Machine</option> + <option value="archive.today">archive.today</option> + </select> <span className="text-xs text-muted-foreground">with the page&apos;s own URL</span> </label> <StreamActionLog - trigger={() => importPageAction(slug, url.trim(), date ? atFromDate(date) : undefined)} + trigger={() => + importPageAction( + slug, + url.trim(), + date ? atFromDate(date) : undefined, + undefined, + date && source !== "wayback" && !isArchiveTodayUrl(url) ? source : undefined, + ) + } cancelAction={cancelJobAction} buttonLabel="Import capture" runningLabel="Importing…" @@ -103,6 +134,13 @@ export function WaybackPagesPanel({ slug, state }: { slug: string; state: Waybac </Link> )} </section> + <ArchiveLookupSection slug={slug} /> + {state.archiveSession && ( + <section aria-label="archive session" className="flex flex-col gap-2 rounded-lg border border-border p-3"> + <h4 className="text-sm font-semibold">archive.today check</h4> + <ConnectArchiveSession initial={state.archiveSession} /> + </section> + )} <section aria-label="re-extract" className="flex flex-col gap-2 rounded-lg border border-border p-3"> <h4 className="text-sm font-semibold">Re-extract</h4> <span className="text-xs text-muted-foreground"> @@ -126,3 +164,93 @@ export function WaybackPagesPanel({ slug, state }: { slug: string; state: Waybac </div> ); } + +// LOOK UP A PAGE across archive sources (release 37 lane F, `archive-lookup`): +// the copies each source holds, read only; each row imports that one copy. +function ArchiveLookupSection({ slug }: { slug: string }) { + const [page, setPage] = useState(""); + const [lookup, setLookup] = useState<ArchiveLookup | null>(null); + const [error, setError] = useState<string | null>(null); + const [busy, setBusy] = useState(false); + const [jobs, setJobs] = useState<Record<string, string>>({}); + const [refusals, setRefusals] = useState<Record<string, string>>({}); + const input = "rounded border border-border bg-card px-2 py-1 text-sm font-mono"; + return ( + <section aria-label="look up a page" className="flex flex-col gap-2 rounded-lg border border-border p-3"> + <h4 className="text-sm font-semibold">Look up a page</h4> + <div className="flex flex-wrap items-center gap-2"> + <input + value={page} + onChange={(e) => setPage(e.target.value)} + aria-label="page URL" + placeholder="https://… (the page's own URL)" + className={`${input} w-[30rem] max-w-full`} + /> + <button + type="button" + disabled={busy || !page.trim()} + onClick={async () => { + setBusy(true); + setError(null); + try { + const r = await archiveLookupAction(page.trim()); + if (r.ok) setLookup(r.lookup); + else setError(r.error); + } finally { + setBusy(false); + } + }} + className="rounded-md border border-border px-2 py-1 text-xs hover:bg-muted disabled:opacity-50" + > + {busy ? "Looking…" : "Look up"} + </button> + </div> + {error && ( + <span role="alert" aria-label="lookup error" className="text-xs text-destructive"> + {error} + </span> + )} + {lookup && + lookup.sources.map((s) => ( + <div key={s.source} data-archive-source={s.source} className="flex flex-col gap-1"> + <span role="status" aria-label={`${s.label} copies`} className="text-sm"> + {s.label}: {s.ok ? `${s.captures.length} cop${s.captures.length === 1 ? "y" : "ies"}` : s.error} + </span> + {s.captures.length > 0 && ( + <ul className="flex flex-col gap-1 text-xs"> + {s.captures.map((c) => ( + <li key={c.mementoUrl} className="flex flex-wrap items-center gap-2 font-mono"> + <a href={c.mementoUrl} target="_blank" rel="noreferrer" className="underline underline-offset-2"> + {c.captureTs} + </a> + <span className="text-muted-foreground">{c.status ?? ""}</span> + {jobs[c.mementoUrl] ? ( + <Link href={`/jobs/${jobs[c.mementoUrl]}`} className="underline underline-offset-2"> + import job + </Link> + ) : ( + <button + type="button" + aria-label={`import ${s.source} ${c.captureTs}`} + onClick={async () => { + const r = await importPageAction(slug, c.mementoUrl); + if (r.ok) { + setJobs((j) => ({ ...j, [c.mementoUrl]: r.jobId })); + void r.stream.cancel(); + } else setRefusals((x) => ({ ...x, [c.mementoUrl]: r.error })); + }} + className="rounded border border-border px-1.5 py-0.5 hover:bg-muted" + > + Import + </button> + )} + {refusals[c.mementoUrl] && <span className="text-destructive">{refusals[c.mementoUrl]}</span>} + </li> + ))} + </ul> + )} + </div> + ))} + </section> + ); +} diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx @@ -38,6 +38,7 @@ import { describeXSearchWalk } from "yt-dlp-transcript-common/lib/xSearch/walk"; import { readXSearchLeads } from "yt-dlp-transcript-common/controller/xSearchLeads"; import { XSearchLeadsPanel } from "./components/XSearchLeadsPanel"; import { countStoredCaptures } from "yt-dlp-transcript-common/lib/waybackPages/store-server"; +import { readArchiveSessionStatus } from "yt-dlp-transcript-common/lib/archives/archiveTodaySession"; import { pageCaptureView } from "yt-dlp-transcript-common/lib/waybackPages/view"; import { postsMediaDir, readPostCapture } from "yt-dlp-transcript-common/social/postCapture"; import { listPostFetchersFor } from "./socialActions"; @@ -218,7 +219,13 @@ export default async function ChannelDetailPage({ // A WAYBACK PAGES channel (release 37): its captures, its scope, Import a // capture — no fetcher, nothing to fetch. const pageRecords = isWaybackPagesChannel(config) ? (await readAllPosts(channelRoot)).filter((p) => p.page) : []; - const wayback = isWaybackPagesChannel(config) ? await waybackPagesRows(channelRoot, slug, pageRecords, postAvailability) : null; + const wayback = isWaybackPagesChannel(config) + ? { + ...(await waybackPagesRows(channelRoot, slug, pageRecords, postAvailability)), + // Release 37 lane F: archive.today's check, passed once in Connect. + archiveSession: await readArchiveSessionStatus(paths), + } + : null; // An X SEARCH channel (release 38): its query, its walk and its leads. const xSearch = isXSearchChannel(config) && config.xSearch ? config.xSearch : null; const leads = xSearch ? await readXSearchLeads(paths, slug) : null; @@ -234,6 +241,7 @@ export default async function ChannelDetailPage({ captureCount: wayback.captureCount, targets: config.wayback?.targets ?? [], recent: wayback.recent, + archiveSession: wayback.archiveSession, }} /> {/* Release 37 S5: is each original still up; Save Page Now. */} diff --git a/editor/app/channels/[slug]/waybackPagesActions.ts b/editor/app/channels/[slug]/waybackPagesActions.ts @@ -11,26 +11,57 @@ import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; import { importPage, queueImportPage, type ImportPageResult } from "yt-dlp-transcript-common/controller/importPage"; import { queueReextractPages } from "yt-dlp-transcript-common/controller/reextractPages"; +import { archiveLookup, type ArchiveLookup } from "yt-dlp-transcript-common/lib/archives/index"; +import { isArchiveSourceId, type ArchiveSourceId } from "yt-dlp-transcript-common/lib/archives/types"; +// Release 37 lane F: `source` ("archive.today") with a page's own URL and +// `at`; a copy's URL (Wayback or archive.today) names its source itself. export async function importPageAction( slug: string, url: string, at?: string, requestedBy?: string, + source?: string, ): Promise<StreamActionResult> { return queueImportPage({ paths: getPaths(), slug, url: url.trim(), ...(at?.trim() ? { at: at.trim() } : {}), + ...(source?.trim() ? { source: source.trim() } : {}), ...(requestedBy ? { requestedBy } : {}), onDone: () => safeRevalidate([`/channels/${slug}`]), }); } // What an import WOULD fetch, answered now (no job, no request). -export async function importPageDryRunAction(slug: string, url: string, at?: string): Promise<ImportPageResult> { - return importPage({ paths: getPaths(), slug, url: url.trim(), ...(at?.trim() ? { at: at.trim() } : {}), dryRun: true }); +export async function importPageDryRunAction(slug: string, url: string, at?: string, source?: string): Promise<ImportPageResult> { + return importPage({ + paths: getPaths(), + slug, + url: url.trim(), + ...(at?.trim() ? { at: at.trim() } : {}), + ...(source?.trim() ? { source: source.trim() } : {}), + dryRun: true, + }); +} + +// THE COPIES OF A PAGE across archive sources (release 37 lane F, +// `archive-lookup`): read only, each source through its own paced client; a +// source that refuses (excluded, a check, a 429) is its own entry's sentence. +export async function archiveLookupAction( + url: string, + source?: string, + limit?: number, +): Promise<{ ok: true; lookup: ArchiveLookup } | { ok: false; error: string }> { + const given = url.trim(); + if (!/^https?:\/\/[^\s]+$/.test(given)) return { ok: false, error: "give a page's own http(s) URL" }; + if (source && !isArchiveSourceId(source)) return { ok: false, error: `"source" must be "wayback" or "archive.today", not "${source}"` }; + const lookup = await archiveLookup(given, { + ...(source ? { source: source as ArchiveSourceId } : {}), + limit: Math.min(Math.max(1, limit ?? 50), 500), + }); + return { ok: true, lookup }; } export async function reextractPagesAction(slug: string, dryRun?: boolean): Promise<StreamActionResult> { diff --git a/editor/app/channels/components/ChannelForm.tsx b/editor/app/channels/components/ChannelForm.tsx @@ -422,7 +422,7 @@ export function ChannelForm({ <option value="x-search">X search (posts from any account)</option> <option value="bluesky">Bluesky (posts)</option> <option value="xenforo">Forum thread — XenForo (posts)</option> - <option value="webpage">Wayback pages (captures of pages)</option> + <option value="webpage">Archived pages (Wayback Machine, archive.today)</option> </SeededSelect> <span className="text-xs text-muted-foreground"> Used as the default job queue, so all channels on the same @@ -546,7 +546,7 @@ export function ChannelForm({ <option value="x-search">X search (posts from any account)</option> <option value="bluesky">Bluesky (posts)</option> <option value="xenforo">Forum thread — XenForo (posts)</option> - <option value="webpage">Wayback pages (captures of pages)</option> + <option value="webpage">Archived pages (Wayback Machine, archive.today)</option> </ControlledSelect> <span className="text-xs text-muted-foreground"> Used as the default job queue, so all channels on the same diff --git a/editor/app/channels/components/WaybackTargetsField.tsx b/editor/app/channels/components/WaybackTargetsField.tsx @@ -11,9 +11,34 @@ import { type WaybackTarget, } from "yt-dlp-transcript-common/lib/waybackPages/config"; +// `sources` (release 37 lane F): "wayback", "archive.today" or "both" — +// where the target's copies are looked for. // `keep`: what the rows do not edit (mime, include, exclude), carried through a // save so the scan's filters survive an edit of the form (release 37 S2). -type Row = { url: string; match: string; from: string; to: string; keep?: Pick<WaybackTarget, "mime" | "include" | "exclude"> }; +type Row = { + url: string; + match: string; + from: string; + to: string; + sources?: string; + keep?: Pick<WaybackTarget, "mime" | "include" | "exclude">; +}; + +const SOURCE_LABELS: Record<string, string> = { + wayback: "Wayback Machine", + "archive.today": "archive.today", + both: "Both", +}; + +const sourcesOf = (t: WaybackTarget): string => { + const s = t.sources ?? []; + if (s.includes("wayback") && s.includes("archive.today")) return "both"; + if (s.includes("archive.today")) return "archive.today"; + return "wayback"; +}; + +const sourcesList = (v: string | undefined): string[] | undefined => + v === "both" ? ["wayback", "archive.today"] : v === "archive.today" ? ["archive.today"] : undefined; const LABELS: Record<string, string> = { exact: "Exact page", @@ -28,7 +53,7 @@ const toRow = (t: WaybackTarget): Row => { ...(t.include ? { include: t.include } : {}), ...(t.exclude ? { exclude: t.exclude } : {}), }; - return { url: t.url, match: t.match, from: t.from ?? "", to: t.to ?? "", ...(Object.keys(keep).length ? { keep } : {}) }; + return { url: t.url, match: t.match, from: t.from ?? "", to: t.to ?? "", sources: sourcesOf(t), ...(Object.keys(keep).length ? { keep } : {}) }; }; export function WaybackTargetsField({ @@ -64,6 +89,7 @@ export function WaybackTargetsField({ match: r.match, ...(r.from.trim() ? { from: r.from.trim() } : {}), ...(r.to.trim() ? { to: r.to.trim() } : {}), + ...(sourcesList(r.sources) ? { sources: sourcesList(r.sources) } : {}), ...(r.keep ?? {}), })), ); @@ -107,6 +133,18 @@ export function WaybackTargetsField({ placeholder="to (2016)" className={`${input} w-28 font-mono`} /> + <select + value={r.sources ?? "wayback"} + onChange={(e) => edit(i, { sources: e.target.value })} + aria-label={`target ${i + 1} sources`} + className={input} + > + {Object.entries(SOURCE_LABELS).map(([v, label]) => ( + <option key={v} value={v}> + {label} + </option> + ))} + </select> <button type="button" onClick={() => { @@ -137,7 +175,7 @@ export function WaybackTargetsField({ Import new captures automatically (the download lane, at archive.org&apos;s pace) </label> <span className="text-xs text-muted-foreground"> - Which captures are in scope. Dates are Wayback timestamps or their start (2014, 201403, 20140305). + Which captures are in scope, and on which archive. Dates are capture timestamps or their start (2014, 201403, 20140305). </span> </fieldset> ); diff --git a/editor/app/channels/components/parseChannelForm.test.ts b/editor/app/channels/components/parseChannelForm.test.ts @@ -210,8 +210,11 @@ test("the ops patch round-trips a pages channel's targets (an array or its JSON) // Release 37 S2: a save of the form keeps `wayback.auto` and each target's // mime/include/exclude (the form rewrites `config.wayback` whole); the // `waybackAuto` checkbox and the ops patch turn it on and off. -test("a form save keeps wayback.auto and the targets' filters; the checkbox and the ops patch set and clear auto", () => { - const targets = [{ url: "blog.example", match: "host" as const, mime: ["text/html", "text/plain"], include: "/post/", exclude: "/post/9/" }]; +test("a form save keeps wayback.auto and the targets' filters and sources; the checkbox and the ops patch set and clear auto", () => { + // Release 37 lane F: and each target's archive sources. + const targets = [ + { url: "blog.example", match: "host" as const, mime: ["text/html", "text/plain"], include: "/post/", exclude: "/post/9/", sources: ["wayback" as const, "archive.today" as const] }, + ]; const fd = channelConfigToFormData({ handling: "transcribe", name: "Old blog", diff --git a/editor/app/settings/archiveSessionActions.ts b/editor/app/settings/archiveSessionActions.ts @@ -0,0 +1,57 @@ +"use server"; + +// THE ARCHIVE SESSION (release 37 lane F, common/lib/archives/archiveTodaySession.ts): +// archive.today's check, passed once by the operator in a HEADED window on the +// archive profile, so the headless reads behind a check go through. Only this +// explicit action opens a window; an import that meets a check it cannot pass +// stops and says to come here. Nothing is ever solved by code. +// +// And settings.archives (host, pace, the browser fallback), saved as a patch. + +import { revalidatePath } from "next/cache"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { getSettings } from "yt-dlp-transcript-common/lib/settings"; +import { + connectArchiveSession, + readArchiveSessionStatus, + type ArchiveSessionRecord, + type ArchiveSessionStatus, +} from "yt-dlp-transcript-common/lib/archives/archiveTodaySession"; +import { isArchiveTodayUrl } from "yt-dlp-transcript-common/lib/archives/mementos"; +import { sanitizeArchives, type ArchivesSettings } from "yt-dlp-transcript-common/lib/archives/settings"; +import { saveSettings } from "./saveSettings"; + +export async function archiveSessionStatusAction(): Promise<ArchiveSessionStatus> { + return readArchiveSessionStatus(getPaths()); +} + +// Open the window at `url` (an archive.today copy the check stood in front +// of), else at archive.today's front page on the canonical host. +export async function connectArchiveSessionAction( + url?: string, +): Promise<{ ok: true; record: ArchiveSessionRecord } | { ok: false; error: string }> { + const host = getSettings().archives.archiveTodayHost; + const at = url?.trim() && isArchiveTodayUrl(url.trim()) ? url.trim() : `https://${host}/`; + try { + const record = await connectArchiveSession(getPaths(), at, { + onLog: (line) => console.log(`[archive-session] ${line}`), + }); + revalidatePath("/settings"); + return { ok: true, record }; + } catch (e) { + return { ok: false, error: (e as Error).message }; + } +} + +export async function saveArchivesSettingsAction( + patch: Partial<ArchivesSettings>, +): Promise<{ ok: true; archives: ArchivesSettings } | { ok: false; error: string }> { + try { + const archives = sanitizeArchives({ ...getSettings().archives, ...patch }); + await saveSettings({ archives }); + revalidatePath("/settings"); + return { ok: true, archives }; + } catch (e) { + return { ok: false, error: (e as Error).message }; + } +} diff --git a/editor/app/settings/components/ArchiveSessionSection.tsx b/editor/app/settings/components/ArchiveSessionSection.tsx @@ -0,0 +1,138 @@ +"use client"; + +// ARCHIVE SOURCES on the settings page (release 37 lane F): archive.today's +// host, pace and browser fallback (settings.archives), and the archive +// session — Connect opens a window on the editor's machine for the operator to +// pass archive.today's check once; the headless reads reuse it. The same +// Connect control sits on an Archived pages channel's panel. + +import { useState, useTransition } from "react"; +import { ARCHIVE_TODAY_HOSTS } from "yt-dlp-transcript-common/lib/archives/mementos"; +import type { ArchivesSettings } from "yt-dlp-transcript-common/lib/archives/settings"; +import type { ArchiveSessionStatus } from "yt-dlp-transcript-common/lib/archives/archiveTodaySession"; +import { connectArchiveSessionAction, saveArchivesSettingsAction } from "../archiveSessionActions"; + +function sessionLine(status: ArchiveSessionStatus): string { + const last = status.lastConnect; + if (!last) return status.hasProfile ? "Profile kept; never connected by hand" : "Not connected"; + const when = last.connectedAt.slice(0, 16).replace("T", " "); + return `Connected ${when} UTC — ${last.cleared ? "the page showed" : "a check was still showing"}, ${last.cookies} cookie${last.cookies === 1 ? "" : "s"}`; +} + +// The status line and Connect, alone (the channel panel's). +export function ConnectArchiveSession({ initial, url }: { initial: ArchiveSessionStatus; url?: string }) { + const [status, setStatus] = useState(initial); + const [error, setError] = useState<string | null>(null); + const [pending, start] = useTransition(); + return ( + <div className="flex flex-wrap items-center gap-2 text-sm"> + <span role="status" aria-label="archive session" className="text-muted-foreground"> + archive.today session: {sessionLine(status)} + </span> + <button + type="button" + disabled={pending} + onClick={() => + start(async () => { + setError(null); + const r = await connectArchiveSessionAction(url); + if (r.ok) setStatus({ ...status, hasProfile: true, lastConnect: r.record }); + else setError(r.error); + }) + } + className="rounded-md border border-border px-2 py-1 text-xs hover:bg-muted disabled:opacity-50" + > + {pending ? "Window open… close it when done" : "Connect archive session"} + </button> + {error && ( + <span role="alert" aria-label="archive session error" className="text-xs text-destructive"> + {error} + </span> + )} + </div> + ); +} + +export function ArchiveSourcesSection({ initial, session }: { initial: ArchivesSettings; session: ArchiveSessionStatus }) { + const [form, setForm] = useState(initial); + const [note, setNote] = useState<string | null>(null); + const [pending, start] = useTransition(); + const input = "rounded border border-border bg-card px-2 py-1 text-sm"; + return ( + <div aria-label="archive sources" className="flex flex-col gap-3"> + <h2 className="text-lg font-semibold">Archive sources</h2> + <ConnectArchiveSession initial={session} /> + <div className="flex flex-wrap items-end gap-3 text-sm"> + <label className="flex flex-col gap-1"> + <span>archive.today host</span> + <select + aria-label="archive.today host" + value={form.archiveTodayHost} + onChange={(e) => setForm({ ...form, archiveTodayHost: e.target.value })} + className={input} + > + {ARCHIVE_TODAY_HOSTS.map((h) => ( + <option key={h} value={h}> + {h} + </option> + ))} + </select> + </label> + <label className="flex flex-col gap-1"> + <span>Gap between requests (s)</span> + <input + type="number" + min={4} + max={120} + aria-label="archive.today gap seconds" + value={form.archiveTodayGapSeconds} + onChange={(e) => setForm({ ...form, archiveTodayGapSeconds: Number(e.target.value) })} + className={`${input} w-24`} + /> + </label> + <label className="flex flex-col gap-1"> + <span>Rest after a 429 (min)</span> + <input + type="number" + min={5} + max={1440} + aria-label="archive.today cooldown minutes" + value={form.archiveTodayCooldownMinutes} + onChange={(e) => setForm({ ...form, archiveTodayCooldownMinutes: Number(e.target.value) })} + className={`${input} w-24`} + /> + </label> + <label className="flex items-center gap-2"> + <input + type="checkbox" + aria-label="read a check through the browser" + checked={form.archiveTodayBrowser} + onChange={(e) => setForm({ ...form, archiveTodayBrowser: e.target.checked })} + /> + Read past a check with the session&apos;s browser (never solves one) + </label> + <button + type="button" + disabled={pending} + onClick={() => + start(async () => { + const r = await saveArchivesSettingsAction(form); + if (r.ok) { + setForm(r.archives); + setNote("Saved."); + } else setNote(r.error); + }) + } + className="rounded-md border border-border px-2 py-1 text-xs hover:bg-muted disabled:opacity-50" + > + Save archive sources + </button> + {note && ( + <span role="status" aria-label="archive sources saved" className="text-xs text-muted-foreground"> + {note} + </span> + )} + </div> + </div> + ); +} diff --git a/editor/app/settings/page.tsx b/editor/app/settings/page.tsx @@ -8,6 +8,8 @@ import { xCookieSourceView } from "yt-dlp-transcript-common/social/xCookieSource import { xPostsVisibility } from "yt-dlp-transcript-common/lib/postsVisibility"; import { SettingsForm } from "./components/SettingsForm"; import { XSessionSection } from "./components/XSessionSection"; +import { ArchiveSourcesSection } from "./components/ArchiveSessionSection"; +import { readArchiveSessionStatus } from "yt-dlp-transcript-common/lib/archives/archiveTodaySession"; export const dynamic = "force-dynamic"; @@ -101,6 +103,11 @@ export default async function SettingsPage() { /> </section> + {/* Release 37 lane F: archive.today's host, pace and session. */} + <section className="flex flex-col gap-3 border-t border-border pt-6"> + <ArchiveSourcesSection initial={settings.archives} session={await readArchiveSessionStatus(paths)} /> + </section> + <section className="flex flex-col gap-3 border-t border-border pt-6"> <details> <summary className="cursor-pointer text-lg font-semibold"> diff --git a/editor/e2e/archive-today-pages.spec.ts b/editor/e2e/archive-today-pages.spec.ts @@ -0,0 +1,175 @@ +// archive.today copies as page records (release 37 lane F), end to end over the +// fake archive.today (common/testing/web/fakeArchiveToday.mjs) and the fake +// Wayback Machine, named to the test server through E2E_ARCHIVE_TODAY_ORIGIN_FILE +// and E2E_WAYBACK_ORIGIN_FILE (e2e/servers.ts). Neither real service is ever +// contacted, and no archive-session browser opens under the fake. +// +// The New channel form makes an "Archived pages" channel of an archive.today +// copy's URL (its target on archive.today); Import a capture takes a copy's URL +// and, with a date, the copy nearest it on archive.today; the copy is stored +// as served with its source; Look up a page lists each source's copies — the +// Wayback Machine's exclusion said in its words; a copy behind a check is +// refused with its code, and Connect archive session is offered (never +// clicked here: it opens a window). + +import { test, expect, type APIRequestContext } from "@playwright/test"; +import { readFile, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { + startFakeArchiveToday, + AT_ARTICLE_ID, + AT_ARTICLE_LATER_ID, + AT_ARTICLE_LATER_TS, + AT_ARTICLE_TS, + AT_ARTICLE_URL, + AT_CHECKED_ID, +} from "yt-dlp-transcript-common/testing/web/fakeArchiveToday.mjs"; +import { startFakeWayback } from "yt-dlp-transcript-common/testing/web/fakeWayback.mjs"; +import { pageRecordId } from "yt-dlp-transcript-common/lib/waybackPages/types"; +import { baseUrl } from "./baseUrl"; +import { generateReport, pathExists, readJson, resetData, resolvePath, testPaths, writeSettings } from "./helpers"; +import { archiveTodayOriginFile, waybackOriginFile } from "./servers"; + +const AUTH = { authorization: "Bearer test-worker-token" }; +const SLUG = "deleted-journal"; + +async function waitForJob(request: APIRequestContext, jobId: string): Promise<{ status: string; tail: string[] }> { + let last = { status: "", tail: [] as string[] }; + await expect + .poll( + async () => { + const res = await request.get(`${baseUrl}/api/ops/job/${jobId}?tail=40`, { headers: AUTH }); + const body = (await res.json()) as { job: { status: string }; tail?: string[] }; + last = { status: body.job.status, tail: body.tail ?? [] }; + return last.status; + }, + { timeout: 90_000, intervals: [1_000] }, + ) + .toMatch(/^(done|failed|cancelled)$/); + return last; +} + +test("an Archived pages channel from an archive.today copy, its copies imported, looked up and refused at a check", async ({ page, request }) => { + test.setTimeout(240_000); + await resetData("empty"); + // archive.today's least gap (4 s): the spec's few requests stay paced. + await writeSettings({ minFreeDiskGB: 0, archives: { archiveTodayGapSeconds: 4, archiveTodayBrowser: true } }); + await generateReport(page, "new"); + + await page.goto("/channels/new"); + await page.locator('input[name="url"]').fill(`https://archive.ph/newest/${AT_ARTICLE_URL}`); + // Offline: an archive.today copy of a page is an Archived pages channel. + await expect(page.locator('select[name="platform"]')).toHaveValue("webpage"); + await expect(page.locator('select[name="platform"] option[value="webpage"]')).toHaveText(/Archived pages/); + await expect(page.getByLabel("target 1 URL")).toHaveValue(AT_ARTICLE_URL); + await expect(page.getByLabel("target 1 match")).toHaveValue("exact"); + await expect(page.getByLabel("target 1 sources")).toHaveValue("archive.today"); + // Widen it: the whole journal, on both archives. + await page.getByLabel("target 1 URL").fill("journal.example/"); + await page.getByLabel("target 1 match").selectOption("prefix"); + await page.getByLabel("target 1 sources").selectOption("both"); + await page.locator('input[name="name"]').fill("Deleted journal"); + await page.locator('input[name="slug"]').fill(SLUG); + await page.getByRole("button", { name: /create|add channel|save/i }).first().click(); + + const configFile = `${testPaths().transcriptsDir}/channels/${SLUG}/config.json`; + await expect + .poll(async () => ((await pathExists(configFile)) ? await readJson(configFile) : null), { timeout: 15_000 }) + .toMatchObject({ + sourceKind: "social", + platform: "webpage", + wayback: { targets: [{ url: "journal.example/", match: "prefix", sources: ["wayback", "archive.today"] }] }, + }); + + const at = await startFakeArchiveToday({ challenge: [AT_CHECKED_ID] }); + const wb = await startFakeWayback({ excluded: [AT_ARTICLE_URL] }); + const atFile = archiveTodayOriginFile(resolvePath(testPaths().transcriptsDir)); + const wbFile = waybackOriginFile(resolvePath(testPaths().transcriptsDir)); + await writeFile(atFile, at.base); + await writeFile(wbFile, wb.base); + try { + await page.goto(`/channels/${SLUG}`); + const pages = page.getByRole("region", { name: "Wayback pages" }); + await expect(pages.getByLabel("pages held")).toHaveText("0 records from 0 captures"); + await expect(page.getByRole("button", { name: "Connect archive session" })).toBeVisible(); + + // One copy by its short id (on another of archive.today's names). + await page.getByLabel("capture URL").fill(`https://archive.is/${AT_ARTICLE_ID}`); + await expect(page.getByLabel("capture source")).toBeDisabled(); + await page.getByRole("button", { name: "Import capture" }).click(); + await expect(page.getByRole("log", { name: `Import a capture into ${SLUG} output` })).toContainText('"ok":true', { timeout: 60_000 }); + const id = pageRecordId(AT_ARTICLE_TS, AT_ARTICLE_URL); + const channelRoot = resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}`); + const capture = JSON.parse(await readFile(path.join(channelRoot, "pages", id, "capture.json"), "utf8")) as Record<string, unknown>; + expect(capture).toMatchObject({ + originalUrl: AT_ARTICLE_URL, + captureTs: AT_ARTICLE_TS, + source: "archive.today", + mementoUrl: `https://archive.ph/${AT_ARTICLE_ID}`, + extractor: "generic", + }); + expect(at.requests.map((r) => r.path)).toEqual([`/${AT_ARTICLE_ID}`]); + + await page.reload(); + await expect(pages.getByLabel("pages held")).toHaveText("1 record from 1 capture"); + const row = page.locator(`[data-page-record="${id}"]`); + await expect(row.getByRole("link", { name: "Notes I Later Deleted" })).toHaveAttribute("href", AT_ARTICLE_URL); + await expect(row.getByRole("link", { name: "2019-05-12" })).toHaveAttribute("href", `https://archive.ph/${AT_ARTICLE_ID}`); + await expect(row).toContainText("archive.today"); + + // The copy nearest a date, on archive.today (one timemap request). + await page.getByLabel("capture URL").fill(AT_ARTICLE_URL); + await page.getByLabel("capture date").fill("2019-12-01"); + await page.getByLabel("capture source").selectOption("archive.today"); + await page.getByRole("button", { name: "Import capture" }).click(); + await expect(page.getByRole("log", { name: `Import a capture into ${SLUG} output` })).toContainText(`"captureTs":"${AT_ARTICLE_LATER_TS}"`, { + timeout: 60_000, + }); + expect(at.requests.map((r) => r.path).slice(1)).toEqual([`/timemap/${AT_ARTICLE_URL}`, `/${AT_ARTICLE_LATER_ID}`]); + await page.reload(); + await expect(pages.getByLabel("pages held")).toHaveText("2 records from 2 captures"); + + // Look up a page across sources: the Wayback Machine excludes it (its + // words), archive.today lists its two copies — each importable. + await page.getByLabel("page URL").fill(AT_ARTICLE_URL); + await page.getByRole("button", { name: "Look up" }).click(); + await expect(page.getByLabel("Wayback Machine copies")).toContainText("excluded from the Wayback Machine (cause unknown)", { timeout: 60_000 }); + await expect(page.getByLabel("archive.today copies")).toHaveText("archive.today: 2 copies"); + await expect(page.getByRole("button", { name: `import archive.today ${AT_ARTICLE_TS}` })).toBeVisible(); + + // The ops door: the same lookup; a copy behind a check refused with its code. + const look = await request.post(`${baseUrl}/api/ops/archive-lookup`, { headers: AUTH, data: { url: AT_ARTICLE_URL } }); + const lookBody = (await look.json()) as { ok: boolean; found: number; sources: { source: string; ok: boolean; refusal?: string }[] }; + expect(lookBody).toMatchObject({ ok: true, found: 2 }); + expect(lookBody.sources.map((s) => [s.source, s.ok, s.refusal ?? null])).toEqual([ + ["wayback", false, "excluded"], + ["archive.today", true, null], + ]); + const wl = await request.post(`${baseUrl}/api/ops/wayback-lookup`, { headers: AUTH, data: { url: AT_ARTICLE_URL } }); + expect(wl.status()).toBe(403); + expect(await wl.json()).toMatchObject({ ok: false, refusal: "excluded" }); + + const dry = await request.post(`${baseUrl}/api/ops/import-page`, { + headers: AUTH, + data: { slug: SLUG, url: `https://archive.ph/${AT_ARTICLE_ID}`, dryRun: true }, + }); + expect(await dry.json()).toMatchObject({ ok: true, dryRun: true, already: true, source: "archive.today" }); + + const checked = await request.post(`${baseUrl}/api/ops/import-page`, { headers: AUTH, data: { slug: SLUG, url: `https://archive.ph/${AT_CHECKED_ID}` } }); + const checkedBody = (await checked.json()) as { jobId?: string; error?: string }; + expect(checked.status(), checkedBody.error).toBe(200); + const job = await waitForJob(request, checkedBody.jobId!); + expect(job.status).toBe("failed"); + const tail = job.tail.join("\n"); + expect(tail).toContain('"refusal":"challenge"'); + expect(tail).toContain("Connect archive session"); + // Nothing of the checked copy was stored. + await page.reload(); + await expect(pages.getByLabel("pages held")).toHaveText("2 records from 2 captures"); + } finally { + await rm(atFile, { force: true }); + await rm(wbFile, { force: true }); + await at.close(); + await wb.close(); + } +}); diff --git a/editor/e2e/servers.ts b/editor/e2e/servers.ts @@ -57,6 +57,11 @@ export function waybackOriginFile(transcriptsDir: string): string { return join(transcriptsDir, ".fake-wayback-origin"); } +/** The file naming a slot's fake archive.today (common/lib/archives/archiveTodayClient.ts; archive-today-pages.spec). */ +export function archiveTodayOriginFile(transcriptsDir: string): string { + return join(transcriptsDir, ".fake-archive-today-origin"); +} + /** The saved thread pages a slot's forum fetcher reads (forumFixtureLoader.ts; forum-resume.spec). */ export function forumFixtureDir(transcriptsDir: string): string { return join(transcriptsDir, ".forum-fixture"); @@ -223,6 +228,9 @@ export function slotServers(slot: number, mode: E2EMode, env: Env = process.env) // The same for the fake Wayback Machine wayback-pages.spec starts // (lib/waybackClient.ts: the process's client sends web.archive.org there). editorEnv.E2E_WAYBACK_ORIGIN_FILE = waybackOriginFile(paths.transcriptsDir); + // The same for the fake archive.today archive-today-pages.spec starts + // (lib/archives/archiveTodayClient.ts; no archive session browser under it). + editorEnv.E2E_ARCHIVE_TODAY_ORIGIN_FILE = archiveTodayOriginFile(paths.transcriptsDir); // The forum fetcher's saved pages (forum-resume.spec): the slot's own // directory (common/social/forumFixtureLoader.ts). editorEnv.E2E_FORUM_FIXTURE_DIR = forumFixtureDir(paths.transcriptsDir); diff --git a/editor/playwright.config.ts b/editor/playwright.config.ts @@ -39,6 +39,9 @@ import { currentSlot } from "./e2e/testPaths"; // into, where the editor's Wayback client then sends // every web.archive.org request // (common/lib/waybackClient.ts; wayback-pages.spec) +// E2E_ARCHIVE_TODAY_ORIGIN_FILE the same for the fake archive.today +// (common/lib/archives/archiveTodayClient.ts; +// archive-today-pages.spec); no browser opens under it // E2E_FORUM_FIXTURE_DIR set per slot (e2e/servers.ts): the directory of // SYNTHETIC saved thread pages the forum fetcher // reads in place of a browser, with no pause diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -11187,6 +11187,63 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri then parsed; renderers found by key anywhere (`channelAboutFullMetadataRenderer` | `aboutChannelViewModel`, `c4TabbedHeaderRenderer` | `pageHeaderViewModel`, `channelMetadataRenderer`). +## Release 37 lane F: archive sources — archive.today like Wayback (verified 2026-10-20, branch `r37/archive-sources`) + +- **The layer** is `common/lib/archives/`: `types.ts` (`ArchiveSource` = `{id, label, queueKey, matchesUrl, + parseMementoUrl, listCaptures, closestCapture, getCapture}`, `ArchiveRefusal` with codes `excluded | challenge | + rate-limited | not-archived | mimetype | too-large | offsite-redirect | redirect-loop | unreadable`), `mementos.ts` + (client-safe: `parseArchiveTodayUrl`, `mementoSourceOf`, `pageArchiveLink`, `ARCHIVE_TODAY_HOSTS`), `ask.ts` + (client-safe `parseArchiveCaptureAsk(url, at?, source?)`), `wayback.ts` (the adapter over `WaybackClient`, no + behaviour change), `archiveToday.ts` (pure: timemap, copy facts, check page, unwrap, media map), + `archiveTodayClient.ts`, `archiveTodaySession.ts`, `settings.ts`, and `index.ts` (server: `ARCHIVE_SOURCES` = + [wayback, archive.today], `sourceForUrl`, `archiveSource(id)`, `archiveRefusalOf(e)`, `archiveLookup`, the + process `archiveTodayClient`). Callers ask the registry, never a source by name. +- **archive.today** is one service under seven names (archive.ph .today .is .li .vn .fo .md); every request goes to + `settings.archives.archiveTodayHost` (default archive.ph; anything else → archive.ph). Copies: `/<id>` (4–6 + alphanumerics, names no page or time), `/<ts>/<page>` (14 digits or `YYYY.MM.DD-hhmmss`), `/newest|oldest/<page>` + (both redirect to `/<id>`); `/timemap/<page>` is link format (404 = none); `/o/<id>/<url>` is a link OUT of a copy. + A copy's time and page come from `Memento-Datetime` + `Link rel="original"`, else its header bar (`#HEADER`'s + URL box and `<time datetime>`), else the URL. Shapes as known 2026-10-20 — no live copy was read (synthetic + fixtures only): the stored body is the copy AS SERVED, so a better unwrap is a `reextract-pages`. +- **The client** (`ArchiveTodayClient`): one chain, gap `archiveTodayGapSeconds` (8, clamp 4–120) + up to 25 % + jitter from the END of one request; manual redirects inside archive.today only (≤ 5); 502/503/504 retried (3); + **a 429 is never retried**: `ArchiveRefusal("rate-limited")` and nothing is sent for + `archiveTodayCooldownMinutes` (30) or Retry-After; **a check page** (`isArchiveTodayChallenge`: recaptcha / + hcaptcha / cloudflare markers with no `#HEADER`+`#CONTENT` frame, at any status) is `ArchiveRefusal("challenge")`, + after ONE read through `openBrowser` (the headless archive profile, `archiveTodaySession.ts`, which waits a check + out and never clicks) when `archiveTodayBrowser` (true) and no test origin. Queue `platform:archive.today`. + `E2E_ARCHIVE_TODAY_ORIGIN_FILE` sends every archive.today name to the fake and turns the browser off. +- **Unwrap** (`unwrapArchiveTodayHtml`): `#CONTENT`'s inner HTML (scripts dropped) as `<body>`, the copy's `<title>` + and its page `<meta>`s (none naming an archive host, no http-equiv) as `<head>`; `/o/<id>/<url>` and `old-href` → + the href; `old-src` → the img src, the cached copy kept in `images` (original → cached); a body with no frame + passes through, hrefs restored. Lane C's tweet and Tumblr fixtures wrapped like archive.today (the fake's + `wrapLikeArchiveToday`) give deep-equal drafts. `mapArchiveTodayMedia`: a record's image is the cached copy, a + Wayback `im_` form of an uncached original becomes the original. +- **Records and storage (additive):** `PagePostInfo.source?` ("archive.today"; absent = Wayback, "wayback" is + normalised away by `parsePagePostInfo`) and `archiveUrl?` (the copy's URL); for such a record `waybackUrl` and + `rawUrl` ARE that copy's URL (required fields). Cite with `pageArchiveLink(page)`. `StoredCapture.source?` / + `mementoUrl?`; `findStoredCaptureByMemento` answers "already stored" for a short id before any request (host- + blind). The record id and dir are `pageRecordId(captureTs, originalUrl)` as for Wayback — a Wayback capture and + an archive.today copy of the same page at the same second share one (a stored one is not stored again). +- **import-page** (`controller/importPage.ts`): `planImportPage` takes `source`; `importPageQueueOf(ask)` is the + job's queue; `extractInputOfCapture(capture, body)` (shared with reextract's staleness check) unwraps an + archive.today copy; `ImportPageResult` gains `source`, `mementoUrl`, `refusal`. A short id's video/X checks run + after the read. `startImportPageJob` takes `source`. +- **Excluded:** `WaybackExcludedError` (an `ArchiveOrgRequestError`, status 403, so older catches still read it) from + `captures` / `closestCapture`; `WaybackCaptureRefusal("excluded")` from `getCapture`; `isWaybackExcluded(e)`; + `waybackExcludedOf(e, url)` for a caller building its own CDX request (lane B's `cdxPage`); + `WAYBACK_EXCLUDED_PHRASE` = "excluded from the Wayback Machine (cause unknown)". `wayback-lookup` answers 403 + `{refusal: "excluded"}`. The fake Wayback's `excluded: [originals]` answers 403 for CDX and captures. +- **Config:** a target's `sources?: ("wayback" | "archive.today")[]` (`["wayback"]` alone is not written; + `targetSources(t)`). `waybackTargetFromUrl` reads `archive.ph/newest|oldest|<ts>/<page>` as that page, exact, on + archive.today; `isWaybackPagesUrl` is true for an archive.today copy that is not of a video. The form's platform + option reads "Archived pages (Wayback Machine, archive.today)"; the panel region's label stays "Wayback pages". +- **Settings:** `settings.archives` = `{archiveTodayHost, archiveTodayGapSeconds, archiveTodayCooldownMinutes, + archiveTodayBrowser}` (41 settings fields). The session: `transcripts/.archive-session/archive.today/{profile/, + session.json}`; Connect only on the operator's click (channel panel, Settings → Archive sources). +- **Ops / CLI:** `archive-lookup {url, source?, limit?}` (read only) → `{url, found, sources: [{source, label, ok, + captures, refusal?, error?}]}`; `import-page` takes `source`; `archilyzer archive lookup <url>` and `wayback pages + import --source`. ## Release 38 lane S: X search channels (verified 2026-10-20, branch `r38/x-search`) - **An X search channel is `config.xSearch` on an X posts channel** (`sourceKind: "social"`, `platform: "twitter"`, diff --git a/plans/release-37/archive-sources.md b/plans/release-37/archive-sources.md @@ -0,0 +1,132 @@ +# Release 37 lane F — `r37/archive-sources`: archive.today, and any archive service, like Wayback (as shipped) + +The plan of record is [`wayback-pages.md`](wayback-pages.md) ("Added 2026-10-20 — lane F"). Operator, 2026-10-20: +"include archive.today support like wayback, which we'll do on any other archive service we need to read". This lane +puts an **archive-source layer** under the page import: the Wayback Machine becomes one source (an adapter over its +existing client, no behaviour change) and archive.today the second — its timemap, its copies in every URL form, its +rewritten snapshot unwrapped so the same extractors read it, its own paced client, and a headless-browser session for +its check, never CAPTCHA solving. A page record says which source it came from (`page.source`, `page.archiveUrl`), +`import-page` and a new read-only `archive-lookup` work across sources, the channel kind reads "Archived pages" in the +UI, and a Wayback CDX 403 is a typed `excluded` refusal. Rulings followed: no model anywhere; every operation has a +button (Import a capture with a source, Look up a page, Connect archive session, Settings → Archive sources); polite +(one stream per source, archive.today 8 s apart and stopped by a 429); synthetic fixtures only; no real network in any +test; commits end with the one Co-Authored-By trailer. + +## Shared-shape changes (additive) + +- `PagePostInfo` (`lib/waybackPages/types.ts`): `source?: string` (absent = the Wayback Machine) and `archiveUrl?: + string` (the copy's URL on that source). For such a record `waybackUrl` and `rawUrl` hold the copy's URL too (they + are required): cite with `pageArchiveLink(page)` (`lib/archives/mementos.ts`), which names the source. + `parsePagePostInfo` keeps both (a stored `"wayback"` is normalised away). +- `StoredCapture` (`store-server.ts`): `source?`, `mementoUrl?`; `findStoredCaptureByMemento`. +- `WaybackTarget` (`config.ts`): `sources?: ("wayback" | "archive.today")[]` (`targetSources(t)`; `["wayback"]` + alone is not written). +- `WaybackCaptureRefusalCode` gains `"excluded"`; `waybackCdxUrl` / `WaybackClient.captures` take `from`/`to`. +- `DraftToPostContext.source?`, `ImportPageResult.{source, mementoUrl, refusal}`, `planImportPage`/ + `queueImportPage`/`startImportPageJob`/`importPage` take `source`. +- `settings.archives` (a 41st settings field). + +## What + +1. **The layer** `common/lib/archives/`: `ArchiveSource` (`id, label, queueKey, matchesUrl, parseMementoUrl, + listCaptures, closestCapture, getCapture`), `ArchiveRefusal` (typed codes), the registry `ARCHIVE_SOURCES` + + `sourceForUrl` + `archiveSource(id)` + `archiveRefusalOf(e)` + `archiveLookup` (`index.ts`), the Wayback adapter + (`wayback.ts`), client-safe URL reading (`mementos.ts`, `ask.ts`). +2. **archive.today**: `archiveToday.ts` (pure: timemap link format, copy facts from Memento headers else the header + bar, the check page, the unwrap, the media map) and `archiveTodayClient.ts` (one chain; gap 8 s + up to 25 % + jitter; manual redirects inside archive.today; 502/503/504 retried; a 429 stops with a sentence and rests the client + 30 min; a check is refused, after one read through the headless archive profile when allowed). One canonical host + from settings for all seven names. `archiveTodaySession.ts`: the profile, `connectArchiveSession` (headed, only on + the operator's click), `archiveSessionBrowser` (headless; waits a check out, never clicks). +3. **Import**: `import-page` takes an archive.today copy (`/<id>`, `/<ts>/<page>`, `/newest|oldest/<page>`) or + `{url, at, source: "archive.today"}` (one timemap request), on `platform:archive.today`; the copy is stored AS + SERVED with `source` + `mementoUrl` in `capture.json` and unwrapped each time it is read + (`extractInputOfCapture`, shared with `reextract-pages`' staleness check); a short id is checked against the stored + copies before any request, and for video / X after the read. The New channel form's kind reads **Archived pages** + and reads an archive.today copy's URL as a target on archive.today; each target row has a sources choice. +4. **Excluded**: `WaybackExcludedError` (an `ArchiveOrgRequestError` 403) from `captures`/`closestCapture`, + `WaybackCaptureRefusal("excluded")` from `getCapture`, `isWaybackExcluded`, `waybackExcludedOf` — surfaced by + `wayback-lookup` (403, `refusal: "excluded"`), `import-page` and `archive-lookup` as "excluded from the Wayback + Machine (cause unknown)". +5. **Ops / CLI / UI**: `archive-lookup {url, source?, limit?}`; `import-page` `source`; `archilyzer archive lookup`, + `wayback pages import --source`; the channel page's Import a capture (a source select), **Look up a page** (each + source's copies, an Import per copy), **Connect archive session**; Settings → **Archive sources** (host, gap, + cool-down, the browser fallback, the session line and Connect). +6. **The fake**: `common/testing/web/fakeArchiveToday.mjs` (timemaps, copies wrapped as archive.today wraps them — + `wrapLikeArchiveToday` — its redirects, a CAPTCHA page at any status, a plain 429; lane C's fixtures as copies via + `fixtureCopy`), and `fakeWayback.mjs`'s `excluded` option (its own block). + +## Adding an archive source + +One module and one registry entry; nothing else names a source. + +1. `common/lib/archives/<source>.ts` (pure reading: its listing format, a copy's facts, an unwrap if its copies are + rewritten) and `<source>Client.ts` (its paced client: one chain, its own gap, a 429 that stops, `E2E_<SOURCE>_ + ORIGIN_FILE` for the e2e fake). Implement `ArchiveSource` (`types.ts`): `matchesUrl`, `parseMementoUrl`, + `listCaptures`, `closestCapture`, `getCapture` — `getCapture` answers the body AS SERVED (what is stored) and + `page`, the copy as the extractors read it; refusals are `ArchiveRefusal` with the existing codes. +2. Add its id to `ARCHIVE_SOURCE_IDS` (`types.ts`), its label to `ARCHIVE_SOURCE_LABELS` (`mementos.ts`), its URL + form to `mementoSourceOf`, its id to `WAYBACK_TARGET_SOURCES` (`waybackPages/config.ts`, a leaf), and its entry to + `ARCHIVE_SOURCES` (`index.ts`). +3. Teach `parseArchiveCaptureAsk` (`ask.ts`) its copy URLs, `importPage` a branch like `importArchiveTodayCopy` (or + generalise that one: it already only uses the `ArchiveSource` surface plus the store), and `extractInputOfCapture` + its unwrap; `importPageQueueOf` its queue. +4. A fake under `common/testing/web/`, unit tests (URL forms, listing parse, unwrap parity on lane C's fixtures, + pacing, its 429 and its check), and its settings in `archives/settings.ts`. + +## Interfaces (for lanes B, D, E after merge) + +- **B (scan/Captures):** `targetSources(target)` to know which sources a target scans; `archiveSource(id).listCaptures(url, + {from, to, limit})` for a source other than Wayback; wrap `cdxPage` errors with `waybackExcludedOf(e, url)` (or check + `isWaybackExcluded`) to show "excluded from the Wayback Machine (cause unknown)"; Import selected passes a row's + `mementoUrl` to `startImportPageJob({slug, url: mementoUrl})` (an archive.today copy URL routes itself). +- **D (cite):** `pageArchiveLink(page)` → `{source, label, url}` for every citation, shot and moment page of a page + record — never `page.waybackUrl` as "Wayback" alone; `archiveSourceLabel(page.source)`. +- **E (live):** `archiveLookup(url, {source?})` for availability across sources; `ARCHIVE_SOURCES` / + `archiveSource("archive.today")` for find-copy; `archiveRefusalOf(e)` to read any source's refusal. + +## Gates + +All through the session's locks, from the worktree root. Baseline (main b8458892 + this branch's first edits in +flight): common 4764 tests (the 4 fails were this lane's own half-written env/settings docs, so 4762 pass / 2 skipped +clean), editor 356/356, mcp 379/379, test:scripts 1317 (1313 pass / 4 skipped). + +Final, on the branch merged with main through r38/x-search (`60d35f87` + the regenerated CHANNEL.md/COMMANDS.md): + +- `pnpm -r … exec tsc --noEmit`: **clean** (also clean before each code commit and after the B and E merges). +- common: **4919 tests / 4915 pass / 2 fail / 2 skipped** — the 2 were `cli-docs.test.ts` and `fileSchemaDocs.test.ts` + (COMMANDS.md / CHANNEL.md not yet regenerated after the x-search merge); regenerated, those files and + `settingsSchema.test.ts` re-run **39 / 39**. Before the x-search and D merges (B + E merged): **4839 / 4837 / 0 / 2**. + This lane's own tests: `lib/archives/{mementos,archiveToday,archiveTodayClient,wayback}.test.ts`, + `controller/importPage.archiveToday.test.ts` (+ B's form-save test extended with `sources`). +- editor unit: **368 / 368** (357 / 357 after B + E). +- mcp: **384 / 384**. +- test:scripts: **1329: 1325 pass / 0 fail / 4 skipped** (one new: archive-lookup + import-page source). +- Docs: `docs env --check`, `docs files --check`, `docs cli --check`, `settings example --check`: **all 0**. +- e2e (editor, start mode, stamp `cbf0857e60a0` at `60d35f87`, build 297 s): `wayback-pages.spec.ts` + + `archive-today-pages.spec.ts` **2 / 2 passed (1.1 min)** — archive-today-pages 31.6 s, wayback-pages 15.1 s. + +## Rulings followed / decisions + +- **The stored body is the copy AS SERVED** (archive.today's rewritten snapshot, bar and all); it is unwrapped each time + it is read, so a better unwrap is a `reextract-pages`, never a refetch. `getCapture` answers both (`body`, `page`). +- **Records keep the id scheme** (`pageRecordId(captureTs, originalUrl)`): a Wayback capture and an archive.today copy + of one page at the same second would share a record; judged negligible, and the second is not stored again. +- **`waybackUrl`/`rawUrl` hold the archive.today copy's URL** for such a record (the fields are required; an older + reader still links the copy) and `archiveUrl` + `source` say whose; `pageArchiveLink` is the one reader to use. +- **A 429 from archive.today is never retried**: the run stops with a sentence and the process client rests 30 min + (settable). 502/503/504 are retried three times. A check page at any status is a check, not a rate limit. +- **The browser fallback is one headless read on the archive profile** (the forum browser's profile code), only when + `archives.archiveTodayBrowser` is on and no e2e fake is active; it waits a check out and never clicks. A window opens + only on Connect. +- **Nearest by time**, not by digits, for archive.today (the Wayback client's CDX re-sort by digit distance is A's and + untouched). +- **archive.today's layout is as known**, unverified live (synthetic fixtures only): `#HEADER`/`#CONTENT`, + `/o/<id>/<url>` links, `old-src` images, Memento headers. If a live copy drops class names, site extractors will + not claim it and the generic one reads it; the raw copy is kept for a later re-extract. +- **The panel's region label stays "Wayback pages"** (an e2e contract of lanes A and B); only the New channel form's + kind is renamed "Archived pages". +- **find-copy's page mode (lane E)** asks `nearestAcrossSources` (Wayback, then archive.today; an exclusion passes + on) and imports the row's own copy URL; given an explicit Wayback client (its tests) it stays Wayback-only. +- **`cdxPage` (lane B)** maps a 403 to `WaybackExcludedError` (still an `ArchiveOrgRequestError` 403). +- **`archilyzer archive lookup`** was added beside the ops action so the orchestrator can look without an editor. diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -133,6 +133,9 @@ // 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 import-page --json '{"slug":"demo-pages","url":"https://archive.ph/AbCdE","dryRun":true}' +// pnpm ops import-page --json '{"slug":"demo-pages","url":"https://blog.example/a-post.html","at":"20190601","source":"archive.today"}' --wait +// pnpm ops archive-lookup --json '{"url":"https://blog.example/a-post.html"}' // 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 @@ -471,6 +474,10 @@ const ACTIONS = [ // keys), the capture imported into slug, as a save-page-now job. "check-post-availability", "save-page-now", + // ARCHIVE SOURCES (release 37 lane F): the copies of a page across archive + // sources — the Wayback Machine and archive.today — read only and paced + // ({url, source?, limit?}). + "archive-lookup", // X SEARCH (release 38): an X search channel's lead, acted on — archive the // account as its own X channel on no site, or never archive it (hidden), // or restore it ({slug, handle, action, name?, fetch?, dryRun?}). @@ -1469,7 +1476,9 @@ export function usage() { ' captures that recorded a 200, "limit"?: 100 (at most 500) -> {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.", + " manners (one at a time, 2 s apart, 429s waited out). Read only. A URL", + ' the Wayback Machine answers 403 for is excluded: HTTP 403, "refusal":', + ' "excluded" ("excluded from the Wayback Machine (cause unknown)").', "", '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:', @@ -1581,6 +1590,26 @@ export function usage() { ' 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?}.", + ' archive.today (release 37 lane F): "url" may be an archive.today copy', + " (archive.ph/<id>, /<timestamp>/<page>, /newest/<page>), or the page's", + ' own URL with "at" and "source": "archive.today" for its copy nearest that', + " date (one timemap request); the job runs on the platform:archive.today", + " queue at archive.today's pace (one request at a time, 8 s apart; a 429", + " stops it and rests the client). The copy is stored as served with its", + " source and URL. A check page (a CAPTCHA) is refused, never solved:", + " Connect archive session on the channel page or Settings, then again.", + ' The result carries "source", "mementoUrl" and, for a refusal, "refusal":', + ' "excluded" (the Wayback Machine answered 403 for the page), "challenge",', + ' "rate-limited", ….', + "", + 'archive-lookup answers the copies of a page each archive source holds:', + ' {"url"} (the page\'s own URL), "source"?: "wayback" | "archive.today"', + ' (default both), "limit"?: 50 per source (at most 500) -> {url, found,', + " sources: [{source, label, ok, captures: [{source, captureTs, originalUrl,", + " mementoUrl, status?, mimetype?}], refusal?, error?}]}, oldest first. Each", + " source through its own paced client; one that refuses is its own entry's", + ' sentence (refusal "excluded": excluded from the Wayback Machine (cause', + ' unknown); "challenge"; "rate-limited"). Read only. wayback-lookup stays.', "", "reextract-pages re-derives a Wayback pages channel's records from the raw", ' captures it stores: {"slug", "dryRun"?}. No request. A reextract-pages job', diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs @@ -941,3 +941,17 @@ test("check-post-availability, save-page-now and find-copy's page mode are POSTs assert.match(usage(), /save-page-now asks the Wayback Machine to capture a live page now/); assert.match(usage(), /The page mode \(release 37\)/); }); + +// Release 37 lane F: the copies of a page across archive sources, and an +// archive.today copy's import, are POSTs to their routes. +test("archive-lookup is a POST to its route; import-page passes source through; both named in the usage", () => { + const p = parseArgs(["archive-lookup", "--json", '{"url":"https://blog.example/a.html","source":"archive.today","limit":5}']); + assert.equal(p.method, "POST"); + assert.equal(p.path, "/api/ops/archive-lookup"); + assert.deepEqual(p.body, { url: "https://blog.example/a.html", source: "archive.today", limit: 5 }); + const i = parseArgs(["import-page", "--json", '{"slug":"old-blog","url":"https://blog.example/a.html","at":"2019","source":"archive.today"}']); + assert.deepEqual(i.body, { slug: "old-blog", url: "https://blog.example/a.html", at: "2019", source: "archive.today" }); + assert.match(usage(), /Actions:.*save-page-now, archive-lookup/); + assert.match(usage(), /archive-lookup answers the copies of a page each archive source holds/); + assert.match(usage(), /excluded from the Wayback Machine \(cause/); +}); diff --git a/settings.json.example b/settings.json.example @@ -198,6 +198,12 @@ "maxUploadKiBps": 0, "s3KeyFile": "~/.config/archilyzer/archive-org.env" }, + "archives": { + "archiveTodayHost": "archive.ph", + "archiveTodayGapSeconds": 8, + "archiveTodayCooldownMinutes": 30, + "archiveTodayBrowser": true + }, "publish": { "enabled": false, "held": false, diff --git a/umtool/lib/articles/evidence.ts b/umtool/lib/articles/evidence.ts @@ -10,6 +10,7 @@ import type { CitedPlay } from "@/lib/clips/types"; import { channelPosts, corpusMediaUrl, postShotFile, recordDir, recordMeta } from "./article"; import { storeFor } from "./sites"; import { pageCaptureView, pageCopyLinks } from "yt-dlp-transcript-common/lib/waybackPages/view"; +import { mementoSourceOf } from "yt-dlp-transcript-common/lib/archives/mementos"; import type { PageCaptureView } from "yt-dlp-transcript-common/lib/waybackPages/view"; import { parseWaybackUrl } from "yt-dlp-transcript-common/lib/wayback"; import { ARTICLES_KEY, CHANNELS_DIR } from "@/lib/paths"; @@ -197,7 +198,8 @@ export async function citationEvidence(siteId: string, report: Report, citeId: s ? { copy: ref ? pageCopyLinks({ originalUrl: c.url, captureTs: ref.captureTs, waybackUrl: c.archiveUrl, rawUrl: c.archiveUrl }).copy - : { label: "archived copy", url: c.archiveUrl }, + : // Release 37 lane F: an archive.today copy says so. + { label: mementoSourceOf(c.archiveUrl) === "archive.today" ? "archive.today copy" : "archived copy", url: c.archiveUrl }, } : {}), ...(ref ? { importCapture: { site: siteId, report: report.id, writable: siteId === ARTICLES_KEY, host } } : {}),