Archilyzer · Source

archilyzer

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

commit 08e75b86df272c6f38167b8ab55a0bedb9a839ef
parent 82800aa4597cdee5b847fae72ae3a005f005a275
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 12 Nov 2026 01:55:08 -0500

archives: a record's page URL is judged and handed on as ONE string -- one carrying a backslash, whitespace or a control character is refused unparsed (Node and Python read its host differently), and the fetcher gets the URL the check parsed, never the archive's or the ask's own; NAT64's local-use block 64:ff9b:1::/48 is private whole; umtool's chain asks nothing of an archive removed from settings (demo epic D1 re-check)

recordPage (common/lib/remoteArchives.ts) answers {href, platform} or
{refused}; recordPageRefusal is its sentence. The single window route, the
fetch-windows batch and umtool's chain (archiveRecordPageHref) hand href on.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Mcommon/controller/remoteOnlyChannel.test.ts | 27+++++++++++++++++++++++++++
Mcommon/controller/remoteOnlyChannel.ts | 23++++++++++++++++++++++-
Mcommon/lib/archiveHosts-server.test.ts | 10++++++++--
Mcommon/lib/archiveHosts-server.ts | 7++++---
Mcommon/lib/archiveTrust.test.ts | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mcommon/lib/remoteArchives.ts | 53++++++++++++++++++++++++++++++++++++++++-------------
Meditor/app/api/media/fetch-window/route.remote.test.ts | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Meditor/app/api/media/fetch-window/route.ts | 12++++++++----
Meditor/app/api/ops/fetch-windows/route.remote.test.ts | 45++++++++++++++++++++++++++++++++++++++++++++-
Meditor/app/channels/[slug]/videos/fetchWindowsAction.ts | 21+++++++++++++--------
Mumtool/lib/report/chain-run.mjs | 19++++++++++++++-----
Mumtool/lib/report/chain-run.test.mjs | 18++++++++++++++++++
Mumtool/report-to-video/cues.test.mjs | 11+++++++++++
13 files changed, 334 insertions(+), 43 deletions(-)

diff --git a/common/controller/remoteOnlyChannel.test.ts b/common/controller/remoteOnlyChannel.test.ts @@ -6,11 +6,13 @@ import path from "node:path"; import { WHOLE_RECORDING_REFUSED, archiveRecordOf, + archiveRecordPageHref, ensureRemoteOnlyChannel, estimateRecordingBytes, wholeRecordingRefusal, } from "./remoteOnlyChannel"; import type { GetJson } from "../lib/remoteArchives-server"; +import { detectPlatform } from "../lib/detectPlatform.mjs"; import type { Paths } from "../lib/paths"; import { isRemoteOnlyChannel, remoteOnlyRefusal } from "../lib/channelConfig"; @@ -133,3 +135,28 @@ test("a manifest the corpus names on another origin is not followed: the archive assert.equal((await archiveRecordOf("https://stub.test", "a", "v1", { getJson }))?.webpageUrl, "https://www.youtube.com/watch?v=v1"); assert.equal(asked.some((u) => u.includes("192.168")), false); }); + +// demo epic D1 re-check: what umtool's chain sends the editor for a record is the URL the check parsed. +test("a record's page for an ask is the normalised href; one two parsers read differently, or off its platform, is no page", async () => { + const docs: Record<string, unknown> = { + "https://stub.test/corpus.json": { channels: [{ slug: "a" }] }, + "https://stub.test/transcripts/a/manifest.json": { slugToPage: { ok: 0, loud: 0, slash: 0, tab: 0, dot: 0, off: 0, none: 0 } }, + "https://stub.test/transcripts/a/page-0000.json": [ + { id: "ok", webpageUrl: "https://www.youtube.com/watch?v=ok" }, + { id: "loud", webpageUrl: "HTTPS://WWW.YouTube.com:443/watch?v=loud" }, + { id: "slash", webpageUrl: "https://youtube.com\\@evil.example/watch?v=x" }, + { id: "tab", webpageUrl: "https://you\ttube.com/watch?v=x" }, + { id: "dot", webpageUrl: "https://rumble.com\\.evil.example/v1" }, + { id: "off", webpageUrl: "http://169.254.169.254/latest/meta-data/" }, + { id: "none" }, + ], + }; + const getJson = async (url: string) => { + if (!(url in docs)) throw new Error("404"); + return docs[url]; + }; + const href = (id: string) => archiveRecordPageHref("https://stub.test", "a", id, detectPlatform, { getJson }); + assert.equal(await href("ok"), "https://www.youtube.com/watch?v=ok"); + assert.equal(await href("loud"), "https://www.youtube.com/watch?v=loud"); + for (const id of ["slash", "tab", "dot", "off", "none", "not-held"]) assert.equal(await href(id), null, id); +}); diff --git a/common/controller/remoteOnlyChannel.ts b/common/controller/remoteOnlyChannel.ts @@ -30,7 +30,7 @@ import type { Paths } from "../lib/paths"; import type { ChannelConfig } from "../lib/channelConfig"; import { PLATFORM_VALUES, type Platform } from "../lib/platform"; import { corpusUrl, manifestUrl, pageUrl } from "../lib/archive/contract"; -import { WHOLE_RECORDING_REFUSED, archiveOriginOf, sameOrigin, type ConnectedArchive } from "../lib/remoteArchives"; +import { WHOLE_RECORDING_REFUSED, archiveOriginOf, recordPage, sameOrigin, type ConnectedArchive } from "../lib/remoteArchives"; import { archiveChannelFacts, plainGetJson, type ArchiveChannelFacts, type GetJson } from "../lib/remoteArchives-server"; import { createChannel, readChannelConfig } from "./channels"; @@ -116,6 +116,27 @@ export async function archiveRecordOf(origin: string, slug: string, id: string, }; } +/** + * The page URL an ask for a window carries for a recording of `origin`'s + * channel: its archive record's, JUDGED AND NORMALISED (lib/remoteArchives.ts + * recordPage) — the URL the check parsed, written back — or null when the + * archive holds no record, names no page, or names one that is refused. Never + * the record's own string (umtool's chain sends this to the editor, which + * judges it again). + */ +export async function archiveRecordPageHref( + origin: string, + slug: string, + id: string, + detect: (u: string) => string | null, + deps: { getJson?: GetJson } = {}, +): Promise<string | null> { + const record = await archiveRecordOf(origin, slug, id, deps).catch(() => null); + if (!record?.webpageUrl) return null; + const page = recordPage(record.webpageUrl, null, detect); + return "refused" in page ? null : page.href; +} + // A whole recording's size, ESTIMATED from its length: what the saved-video // store's copy weighs at about this height. Approximate on purpose (no request // is made to learn it): video of this kind runs ~0.8 Mb/s at 360p up to ~5 Mb/s diff --git a/common/lib/archiveHosts-server.test.ts b/common/lib/archiveHosts-server.test.ts @@ -56,10 +56,16 @@ test("a mapped literal in an origin is refused at connect, and a name resolving }); test("the other ways an IPv6 literal carries a private IPv4: NAT64's local-use prefix, IPv4-translated, 6to4", () => { - for (const a of ["64:ff9b:1::7f00:1", "::ffff:0:7f00:1", "::ffff:0:10.0.0.1", "2002:7f00:1::", "2002:c0a8:101::1", "2002:a9fe:a9fe::"]) { + for (const a of ["::ffff:0:7f00:1", "::ffff:0:10.0.0.1", "2002:7f00:1::", "2002:c0a8:101::1", "2002:a9fe:a9fe::"]) { assert.equal(isPrivateAddress(a), true, a); } - for (const a of ["64:ff9b:1::808:808", "::ffff:0:808:808", "2002:808:808::1"]) assert.equal(isPrivateAddress(a), false, a); + for (const a of ["::ffff:0:808:808", "2002:808:808::1"]) assert.equal(isPrivateAddress(a), false, a); + // 64:ff9b:1::/48 is local-use whole: private wherever an IPv4 sits in it, and when it carries a public one. + for (const a of ["64:ff9b:1::7f00:1", "64:ff9b:1::808:808", "64:ff9b:1:7f00:0:1::", "64:ff9b:1:a00:0:1::", "64:ff9b:1:ffff:ffff:ffff:ffff:ffff", "64:ff9b:1::"]) { + assert.equal(isPrivateAddress(a), true, a); + } + // Its neighbours are not it. + for (const a of ["64:ff9b:2::808:808", "64:ff9b:10::1"]) assert.equal(isPrivateAddress(a), false, a); }); test("every spelling of a local address in an origin is refused: decimal, hex, octal, short, a trailing dot, bracketed IPv6", async () => { diff --git a/common/lib/archiveHosts-server.ts b/common/lib/archiveHosts-server.ts @@ -70,8 +70,9 @@ const v4Of = (hi: number, lo: number) => `${hi >> 8}.${hi & 255}.${lo >> 8}.${lo * Whether an IP address is loopback, private, link-local, site-local, CGNAT, * unspecified or multicast — in IPv6 also when it only CARRIES such an IPv4 * address: IPv4-mapped (`::ffff:a.b.c.d`, in either spelling), the old - * IPv4-compatible form (`::a.b.c.d`), NAT64 (`64:ff9b::/96` and the local-use - * `64:ff9b:1::/48`), IPv4-translated (`::ffff:0:a.b.c.d`) and 6to4 (`2002::/16`). + * IPv4-compatible form (`::a.b.c.d`), NAT64 (`64:ff9b::/96`), IPv4-translated + * (`::ffff:0:a.b.c.d`) and 6to4 (`2002::/16`). NAT64's local-use block + * `64:ff9b:1::/48` is private whole. */ export function isPrivateAddress(address: string): boolean { const a = address.replace(/^\[|\]$/g, "").toLowerCase(); @@ -85,7 +86,7 @@ export function isPrivateAddress(address: string): boolean { if (zero(0, 5) && g[5] === 0xffff) return v4Private(v4Of(g[6], g[7])); // IPv4-mapped if (zero(0, 6)) return v4Private(v4Of(g[6], g[7])); // IPv4-compatible (deprecated) if (g[0] === 0x64 && g[1] === 0xff9b && zero(2, 6)) return v4Private(v4Of(g[6], g[7])); // NAT64 - if (g[0] === 0x64 && g[1] === 0xff9b && g[2] === 1) return v4Private(v4Of(g[6], g[7])); // NAT64, the local-use prefix 64:ff9b:1::/48 + if (g[0] === 0x64 && g[1] === 0xff9b && g[2] === 1) return true; // 64:ff9b:1::/48, NAT64's local-use block: never globally routable, whatever it carries if (zero(0, 4) && g[4] === 0xffff && g[5] === 0) return v4Private(v4Of(g[6], g[7])); // IPv4-translated ::ffff:0:a.b.c.d if (g[0] === 0x2002) return v4Private(v4Of(g[1], g[2])); // 6to4 2002:a.b.c.d::/48 return ( diff --git a/common/lib/archiveTrust.test.ts b/common/lib/archiveTrust.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { connectedArchives, disconnectedArchiveRefusal, isPlatformHost, recordPageRefusal, sameOrigin } from "./remoteArchives"; +import { connectedArchives, disconnectedArchiveRefusal, isPlatformHost, recordPage, recordPageRefusal, sameOrigin } from "./remoteArchives"; import { fetchOnOrigin, OffOriginError, plainGetJson, type FetchLike } from "./remoteArchives-server"; import { detectPlatform } from "./detectPlatform.mjs"; @@ -36,7 +36,6 @@ test("a record's page URL: a look-alike of a platform's host is not that platfor "https://evil-rumble.com/v9-x.html", "https://rumble.comevil.example/v9-x.html", "https://evil.example/youtube.com/watch?v=a1", - "https://evil.example\\@youtube.com/watch?v=a1", "https://youtube.com%2eevil.example/watch?v=a1", "https://youtubе.com/watch?v=a1", // a Cyrillic е ]) { @@ -66,6 +65,62 @@ test("a record's page URL: a look-alike of a platform's host is not that platfor assert.equal(isPlatformHost("twitter", "x.com"), false, "not a video platform: no table, no host"); }); +// demo epic D1 re-check: the host judged must be the host fetched. Node's URL +// parser and Python's urlsplit (yt-dlp's) read these differently. +test("a page URL two parsers read differently is refused unparsed: a backslash, whitespace, a control character", () => { + const r = (u: string, p: string | null = null) => recordPageRefusal(u, p, detectPlatform); + // What Node makes of the first: the platform's own host. Python's urlsplit says evil.example. + assert.equal(new URL("https://youtube.com\\@evil.example/watch?v=x").hostname, "youtube.com"); + assert.equal(new URL("https://you\ttube.com/watch?v=x").hostname, "youtube.com"); + for (const u of [ + "https://youtube.com\\@evil.example/watch?v=x", + "https://youtube.com\\@127.0.0.1/x", + "https://rumble.com\\.evil.example/v1", + "https://you\ttube.com/watch?v=x", + " https://youtube.com/watch?v=x", + "https://youtube.com/watch?v=x ", + "https://youtube.com/watch?v=x\n", + "https://youtube.com\r\n@evil.example/", + "https://youtube.com/\\evil.example", + "https:\\\\youtube.com/watch?v=x", + "https://youtube.com/watch?v=x\u0000", + "https://youtube.com/wa tch?v=x", + "https://youtube.com /watch?v=x", + "https://youtube.com @evil.example/", + "​https://youtube.com/watch?v=x", + "https://youtube.com/watch?v=x", + "https://youtube.com/watch?v=x\u007f", + ]) { + assert.match(r(u) ?? "(allowed)", /carries a backslash, whitespace or a control character/, JSON.stringify(u)); + assert.match(r(u, "youtube") ?? "(allowed)", /carries a backslash, whitespace or a control character/, JSON.stringify(u)); + } +}); + +test("a page URL that passes is handed on as the parser wrote it back, never as it was given", () => { + const page = (u: string, p: string | null = null) => recordPage(u, p, detectPlatform); + for (const [given, href, platform] of [ + ["https://www.youtube.com/watch?v=a1", "https://www.youtube.com/watch?v=a1", "youtube"], + ["HTTPS://WWW.YouTube.com:443/watch?v=a1", "https://www.youtube.com/watch?v=a1", "youtube"], + ["https:youtube.com/watch?v=a1", "https://youtube.com/watch?v=a1", "youtube"], + ["https:///youtu.be/a1", "https://youtu.be/a1", "youtube"], + ["http://RUMBLE.com", "http://rumble.com/", "rumble"], + ["https://rumble.com/a/../v9-x.html", "https://rumble.com/v9-x.html", "rumble"], + ["https://youtube.com./watch?v=a1", "https://youtube.com./watch?v=a1", "youtube"], + ] as const) { + const got = page(given); + if ("refused" in got) { + // A spelling the platform table does not vouch for is refused, not passed raw. + assert.equal(given, "https://youtube.com./watch?v=a1", `${given}: ${got.refused}`); + continue; + } + assert.deepEqual(got, { href, platform }, given); + assert.equal(got.href, new URL(given).href); + // And the href is its own fixed point: judged again it is the same URL. + assert.deepEqual(page(got.href), got); + } + assert.deepEqual(page("https://rumble.com/v9-x.html", "youtube"), { refused: "rumble.com is rumble, and the channel is youtube's: the archive's page URL is not fetched" }); +}); + test("an archive removed from settings is not read for the channel registered from it (re-review, item 6)", () => { const list = connectedArchives([{ id: "stub", origin: "https://stub.test", title: "Stub", addedAt: "2026-11-11T00:00:00Z" }], {}); assert.equal(disconnectedArchiveRefusal("https://stub.test", list), null); diff --git a/common/lib/remoteArchives.ts b/common/lib/remoteArchives.ts @@ -225,30 +225,57 @@ export function isPlatformHost(platform: string, host: string): boolean { return !!domains && domains.some((d) => h === d || h.endsWith(`.${d}`)); } +// A page URL is refused when it carries a backslash, whitespace or a control +// character ANYWHERE — before it is parsed. URL parsers disagree about exactly +// these: Node reads `https://youtube.com\@evil.example/` as host youtube.com +// (a backslash is a slash to it), Python's urlsplit — what yt-dlp reads it +// with — as host evil.example; Node drops a tab or newline inside a host and +// trims the ends. So the host judged here would not be the host fetched +// (demo epic D1 re-check, the parser differential). +const UNSAFE_PAGE_CHARS = /[\\\s\u0000-\u001f\u007f-\u009f\u00a0\u1680\u2000-\u200f\u2028-\u202f\u205f-\u2060\u3000\ufeff]/; + +export type RecordPage = { href: string; platform: string } | { refused: string }; + /** - * Why a remote-only channel's page URL — an archive record's `webpageUrl`, or - * one an ask carried for it — is not fetched, or null when it may be. The - * archive is someone else's JSON: a URL is accepted only when it is http(s) - * with no credentials, its host names a known video platform, and that is the - * channel's own platform when the channel has one. Refused before any request. + * A remote-only channel's page URL — an archive record's `webpageUrl`, or one + * an ask carried for it — judged, and NORMALISED: `{href, platform}` when a + * window may be fetched from it, `{refused}` with the sentence when not. The + * archive is someone else's JSON: a URL is accepted only when it has no + * backslash, whitespace or control character, is http(s) with no credentials, + * its host names a known video platform, and that is the channel's own + * platform when the channel has one. Refused before any request. + * + * `href` is what the parser that judged the host wrote back (`new URL().href`: + * the host lowercased, a default port dropped, an IDN in punycode), and it is + * THE ONLY string a caller hands on — never the one it was given. */ -export function recordPageRefusal(url: string | null | undefined, channelPlatform: string | null | undefined, detect: (u: string) => string | null): string | null { - if (!url) return "no page URL"; +export function recordPage(url: string | null | undefined, channelPlatform: string | null | undefined, detect: (u: string) => string | null): RecordPage { + if (!url) return { refused: "no page URL" }; + if (UNSAFE_PAGE_CHARS.test(url)) { + return { refused: `${JSON.stringify(url)} is not a page URL: it carries a backslash, whitespace or a control character, which URL parsers read differently — the archive's page URL is not fetched` }; + } let u: URL; try { u = new URL(url); } catch { - return `"${url}" is not a page URL`; + return { refused: `"${url}" is not a page URL` }; } - if ((u.protocol !== "https:" && u.protocol !== "http:") || u.username || u.password) return `${u.protocol}//${u.host} is not a page URL a window is fetched from`; - const platform = detect(url); + if ((u.protocol !== "https:" && u.protocol !== "http:") || u.username || u.password) return { refused: `${u.protocol}//${u.host} is not a page URL a window is fetched from` }; + const href = u.href; + const platform = detect(href); if (!platform || !(RECORD_PAGE_PLATFORMS as readonly string[]).includes(platform) || !isPlatformHost(platform, u.hostname)) { - return `${u.host} is not a video platform's host (${RECORD_PAGE_PLATFORMS.join(", ")}): the archive's page URL is not fetched`; + return { refused: `${u.host} is not a video platform's host (${RECORD_PAGE_PLATFORMS.join(", ")}): the archive's page URL is not fetched` }; } if (channelPlatform && channelPlatform !== platform) { - return `${u.host} is ${platform}, and the channel is ${channelPlatform}'s: the archive's page URL is not fetched`; + return { refused: `${u.host} is ${platform}, and the channel is ${channelPlatform}'s: the archive's page URL is not fetched` }; } - return null; + return { href, platform }; +} + +/** Why a remote-only channel's page URL is not fetched, or null when it may be (recordPage's sentence). */ +export function recordPageRefusal(url: string | null | undefined, channelPlatform: string | null | undefined, detect: (u: string) => string | null): string | null { + const page = recordPage(url, channelPlatform, detect); + return "refused" in page ? page.refused : null; } /** Whether `url` is on `origin`'s own scheme, host and port. */ diff --git a/editor/app/api/media/fetch-window/route.remote.test.ts b/editor/app/api/media/fetch-window/route.remote.test.ts @@ -1,6 +1,6 @@ import test from "node:test"; import assert from "node:assert/strict"; -import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; @@ -17,8 +17,24 @@ process.env.WORKER_TOKEN = "test-token"; process.env.TRANSCRIPTS_DIR = ROOT; process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); delete process.env.TRANSCRIPT_SITE_URL; +// yt-dlp is a fake that writes down what it was asked for: no test here reaches a platform. +const ARGS_LOG = path.join(ROOT, "argv.jsonl"); +const YTDLP = path.join(ROOT, "fake-ytdlp.mjs"); +await writeFile( + YTDLP, + `#!/usr/bin/env node +import { appendFileSync, writeFileSync } from "node:fs"; +const args = process.argv.slice(2); +appendFileSync(${JSON.stringify(ARGS_LOG)}, JSON.stringify(args) + "\\n"); +const o = args.indexOf("-o"); +if (o >= 0) writeFileSync(args[o + 1], "mp4"); +`, +); +await chmod(YTDLP, 0o755); +process.env.YTDLP_BIN = YTDLP; +process.env.E2E_CLIP_WINDOW_GAP_MS = "0"; const ORIGIN = "https://stub.test"; -await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ remoteArchives: [{ id: "stub", origin: ORIGIN, title: "Stub", addedAt: "2026-11-11T00:00:00Z" }] })); +await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ minFreeDiskGB: 0, remoteArchives: [{ id: "stub", origin: ORIGIN, title: "Stub", addedAt: "2026-11-11T00:00:00Z" }] })); const DOCS: Record<string, unknown> = { [`${ORIGIN}/corpus.json`]: { spec: 6, @@ -27,8 +43,15 @@ const DOCS: Record<string, unknown> = { { slug: "yt-evil", name: "Evil", platform: "youtube", manifests: { transcripts: `${ORIGIN}/transcripts/yt-evil/manifest.json` } }, ], }, - [`${ORIGIN}/transcripts/yt-evil/manifest.json`]: { slugToPage: { e1: 0 } }, - [`${ORIGIN}/transcripts/yt-evil/page-0000.json`]: [{ id: "e1", webpageUrl: "http://169.254.169.254/latest/meta-data/" }], + [`${ORIGIN}/transcripts/yt-evil/manifest.json`]: { slugToPage: { e1: 0, d1: 0, d2: 0, n1: 0 } }, + [`${ORIGIN}/transcripts/yt-evil/page-0000.json`]: [ + { id: "e1", webpageUrl: "http://169.254.169.254/latest/meta-data/" }, + // Read as youtube.com by Node's URL parser, as another host by Python's (re-check, the parser differential). + { id: "d1", webpageUrl: "https://youtube.com\\@evil.example/watch?v=d1" }, + { id: "d2", webpageUrl: "https://you\ttube.com/watch?v=d2" }, + // The platform's own page, spelled loudly. + { id: "n1", webpageUrl: "HTTPS://WWW.YouTube.com:443/watch?v=n1" }, + ], [`${ORIGIN}/transcripts/rb-remote/manifest.json`]: { slugToPage: { rb9: 0 } }, [`${ORIGIN}/transcripts/rb-remote/page-0000.json`]: [{ id: "rb9", duration: 600, webpageUrl: "https://rumble.com/vrb9-x.html" }], }; @@ -72,6 +95,47 @@ test("a single window whose archive record points at a non-platform host is refu assert.match(r.json.error ?? "", /^yt-evil\/e1: 169\.254\.169\.254 is not a video platform's host/); }); +test("a page URL two parsers read differently is refused (400) before any request, from the record or from the ask", async () => { + const ask = (videoId: string, webpageUrl?: string) => post({ channelSlug: "yt-evil", videoId, from: 10, to: 20, requestedBy: "test", reason: "a test", archive: ORIGIN, ...(webpageUrl ? { webpageUrl } : {}) }); + for (const r of [ + await ask("d1"), + await ask("d2"), + await ask("a1", "https://youtube.com\\@evil.example/watch?v=x"), + await ask("a2", "https://youtube.com\\@127.0.0.1/x"), + await ask("a3", "https://rumble.com\\.evil.example/v1"), + await ask("a4", "https://you\ttube.com/watch?v=x"), + ]) { + assert.equal(r.status, 400, r.json.error); + assert.match(r.json.error ?? "", /carries a backslash, whitespace or a control character/); + } + assert.equal(await readFile(ARGS_LOG, "utf8").catch(() => ""), "", "yt-dlp was never run"); +}); + +test("what reaches yt-dlp is the URL the check parsed, written back — never the record's own string", async () => { + const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); + const res = await POST( + new Request("http://localhost/api/media/fetch-window", { + method: "POST", + headers: { authorization: "Bearer test-token", "content-type": "application/json" }, + body: JSON.stringify({ channelSlug: "yt-evil", videoId: "n1", from: 10, to: 20, requestedBy: "test", reason: "a test", archive: ORIGIN }), + }), + ); + const body = (await res.json()) as { jobId?: string; error?: string }; + assert.equal(res.status, 202, body.error); + const reg = getRegistry(); + for (let i = 0; i < 200; i++) { + const s = reg.get(body.jobId!)?.status; + if (s !== "queued" && s !== "running") break; + await new Promise((r) => setTimeout(r, 50)); + } + const runs = (await readFile(ARGS_LOG, "utf8")).trim().split("\n").map((l) => JSON.parse(l) as string[]); + assert.ok(runs.length > 0, "yt-dlp was asked"); + for (const args of runs) { + assert.equal(args.at(-1), "https://www.youtube.com/watch?v=n1"); + assert.equal(args.some((a) => /YouTube|:443/.test(a)), false, "the record's own spelling is nowhere in the command"); + } +}); + // LAST: it disconnects the archive for the rest of the file. test("a remote-only channel whose archive was removed from settings is refused (400), and the archive is not read", async () => { await writeFile(process.env.SETTINGS_FILE!, JSON.stringify({ remoteArchives: [] })); diff --git a/editor/app/api/media/fetch-window/route.ts b/editor/app/api/media/fetch-window/route.ts @@ -22,7 +22,7 @@ import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { getSettings } from "yt-dlp-transcript-common/lib/settings"; import { detectPlatform } from "yt-dlp-transcript-common/lib/platform"; import { isRemoteOnlyChannel } from "yt-dlp-transcript-common/lib/channelConfig"; -import { connectedArchives, disconnectedArchiveRefusal, findConnectedArchive, recordPageRefusal } from "yt-dlp-transcript-common/lib/remoteArchives"; +import { connectedArchives, disconnectedArchiveRefusal, findConnectedArchive, recordPage } from "yt-dlp-transcript-common/lib/remoteArchives"; import { cachedArchiveGetJson } from "yt-dlp-transcript-common/lib/archiveCache-server"; import { readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; import { wholeRecordingFor } from "yt-dlp-transcript-common/controller/fetchWindows"; @@ -235,9 +235,13 @@ export async function POST(request: Request) { webpageUrl ||= record?.webpageUrl; // An archive is untrusted input (demo epic D1 review): its page URL must // name the channel's own video platform's host, before any request. - const refused = recordPageRefusal(webpageUrl, config.platform ?? null, detectPlatform); - if (refused) return NextResponse.json({ error: `${channelSlug}/${videoId}: ${refused}` }, { status: 400 }); - const platform = detectPlatform(webpageUrl) ?? config.platform ?? "unknown"; + const page = recordPage(webpageUrl, config.platform ?? null, detectPlatform); + if ("refused" in page) return NextResponse.json({ error: `${channelSlug}/${videoId}: ${page.refused}` }, { status: 400 }); + // From here on the URL is the one the check parsed, written back — never + // the string the archive or the ask gave (another parser may read that + // one as another host). + webpageUrl = page.href; + const platform = page.platform; const whole = body.full === true || wholeRecordingFor(getSettings(), platform, {}, undefined); if (whole && body.allowWholeRecording !== true) { return NextResponse.json( diff --git a/editor/app/api/ops/fetch-windows/route.remote.test.ts b/editor/app/api/ops/fetch-windows/route.remote.test.ts @@ -35,12 +35,18 @@ const DOCS: Record<string, unknown> = { [`${ORIGIN}/transcripts/rb-remote/manifest.json`]: { pageCount: 1, slugToPage: { rb9: 0 } }, [`${ORIGIN}/transcripts/rb-remote/page-0000.json`]: [{ id: "rb9", duration: 5400, webpageUrl: "https://rumble.com/vrb9-x.html" }], // An archive pointing the editor at its own API (review of 9fddc3bb, blocker 2). - [`${ORIGIN}/transcripts/evil-remote/manifest.json`]: { slugToPage: { e1: 0, e2: 0, e3: 0 } }, + [`${ORIGIN}/transcripts/evil-remote/manifest.json`]: { slugToPage: { e1: 0, e2: 0, e3: 0, d1: 0, d2: 0, d3: 0, n1: 0 } }, [`${ORIGIN}/transcripts/evil-remote/page-0000.json`]: [ { id: "e1", webpageUrl: "http://127.0.0.1:3001/api/ops/settings" }, { id: "e2", webpageUrl: "https://rumble.com/ve2-x.html" }, // A look-alike of the channel's platform (re-review, must-fix 1). { id: "e3", webpageUrl: "https://evilyoutube.com/watch?v=e3" }, + // Read as youtube.com by Node's URL parser, as another host by Python's (re-check, the parser differential). + { id: "d1", webpageUrl: "https://youtube.com\\@evil.example/watch?v=d1" }, + { id: "d2", webpageUrl: "https://youtube.com\\@127.0.0.1/x" }, + { id: "d3", webpageUrl: "https://you\ttube.com/watch?v=d3" }, + // The platform's own page, spelled loudly: handed on as the parser wrote it back. + { id: "n1", webpageUrl: "HTTPS://WWW.YouTube.com:443/watch?v=n1" }, ], }; const asked: string[] = []; @@ -123,6 +129,43 @@ test("a look-alike of the channel's platform host is refused before any request" assert.deepEqual(r.json.jobIds, []); }); +test("a page URL two parsers read differently is refused before any request, from the record or from the ask", async () => { + const r = await post({ + requestedBy: "test", + archive: ORIGIN, + items: [ + { slug: "evil-remote", id: "d1", from: 1, to: 5 }, + { slug: "evil-remote", id: "d2", from: 1, to: 5 }, + { slug: "evil-remote", id: "d3", from: 1, to: 5 }, + { slug: "evil-remote", id: "a1", from: 1, to: 5, webpageUrl: "https://youtube.com\\@evil.example/watch?v=x" }, + { slug: "evil-remote", id: "a2", from: 1, to: 5, webpageUrl: "https://rumble.com\\.evil.example/v1" }, + { slug: "evil-remote", id: "a3", from: 1, to: 5, webpageUrl: "https://you\ttube.com/watch?v=x" }, + { slug: "evil-remote", id: "a4", from: 1, to: 5, webpageUrl: "https://youtube.com/watch?v=x\nhttps://evil.example/" }, + ], + }); + assert.equal(r.status, 200, r.json.error); + const errors = (r.json.unresolved as Unresolved).map((u) => u.error); + assert.equal(errors.length, 7); + for (const e of errors) assert.match(e, /carries a backslash, whitespace or a control character/); + assert.deepEqual(r.json.jobIds, []); +}); + +test("what is planned for the fetcher is the URL the check parsed, written back — the record's and the ask's", async () => { + const r = await post({ + requestedBy: "test", + archive: ORIGIN, + dryRun: true, + items: [ + { slug: "evil-remote", id: "n1", from: 1, to: 5 }, + { slug: "evil-remote", id: "n2", from: 1, to: 5, webpageUrl: " https:YOUTUBE.com:443/watch?v=n2 " }, + ], + }); + assert.equal(r.status, 200, r.json.error); + assert.deepEqual(r.json.unresolved, []); + const urls = (r.json.groups as { items: { id: string; webpageUrl: string }[] }[]).flatMap((g) => g.items).map((i) => i.webpageUrl).sort(); + assert.deepEqual(urls, ["https://www.youtube.com/watch?v=n1", "https://youtube.com/watch?v=n2"]); +}); + // LAST: it disconnects the archive for the rest of the file. test("a remote-only channel whose archive was removed from settings is refused, and the archive is not read", async () => { await writeFile(process.env.SETTINGS_FILE!, JSON.stringify({ remoteArchives: [] })); diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.ts @@ -63,7 +63,7 @@ import { } from "yt-dlp-transcript-common/jobs/streamCommand"; import { safeRevalidate } from "../../../lib/safeRevalidate"; import { isRemoteOnlyChannel } from "yt-dlp-transcript-common/lib/channelConfig"; -import { connectedArchives, disconnectedArchiveRefusal, findConnectedArchive, recordPageRefusal, type ConnectedArchive } from "yt-dlp-transcript-common/lib/remoteArchives"; +import { connectedArchives, disconnectedArchiveRefusal, findConnectedArchive, recordPage, type ConnectedArchive } from "yt-dlp-transcript-common/lib/remoteArchives"; import { archiveRecordOf, ensureRemoteOnlyChannel, @@ -366,18 +366,23 @@ async function planFetchWindows( isRemoteOnlyChannel(config) && config.remoteArchive ? await archiveRecordOf(config.remoteArchive, item.slug, item.id, { getJson }).catch(() => null) : null; - const url = + let url = item.webpageUrl?.trim() || record?.webpageUrl || (isRemoteOnlyChannel(config) ? null : await findVideoSourceUrl(paths, item.slug, dirId, config)); // An archive is untrusted input (demo epic D1 review): a remote-only // channel's page URL must name its own video platform's host, or nothing - // is asked of it. - if (url && isRemoteOnlyChannel(config)) { - const why = recordPageRefusal(url, config.platform ?? null, detectPlatform); - if (why) { - unresolved.push({ item, error: why }); - continue; + // is asked of it. What goes on is the URL the check parsed, written back + // — never the string the archive or the ask gave. + if (isRemoteOnlyChannel(config)) { + const raw = item.webpageUrl?.trim() || record?.webpageUrl; + if (raw) { + const page = recordPage(raw, config.platform ?? null, detectPlatform); + if ("refused" in page) { + unresolved.push({ item, error: page.refused }); + continue; + } + url = page.href; } } if (!url) { diff --git a/umtool/lib/report/chain-run.mjs b/umtool/lib/report/chain-run.mjs @@ -59,9 +59,9 @@ import { PIPELINE_DIR } from "./driver.mjs"; import { resolveLocalSource } from "umtool-report-to-video/sources"; import { dedupeMedia, seedFromParent } from "./iterations.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; -import { WHOLE_RECORDING_REFUSED, originOfHandle, recordPageRefusal } from "yt-dlp-transcript-common/lib/remoteArchives"; +import { WHOLE_RECORDING_REFUSED, connectedArchives, disconnectedArchiveRefusal, originOfHandle } from "yt-dlp-transcript-common/lib/remoteArchives"; import { detectPlatform } from "yt-dlp-transcript-common/lib/detectPlatform.mjs"; -import { archiveRecordOf } from "yt-dlp-transcript-common/controller/remoteOnlyChannel"; +import { archiveRecordPageHref } from "yt-dlp-transcript-common/controller/remoteOnlyChannel"; import { cachedArchiveGetJson } from "yt-dlp-transcript-common/lib/archiveCache-server"; const OPS = path.join(REPO_ROOT, "scripts", "archilyzer-ops.mjs"); @@ -123,13 +123,22 @@ async function ownProblems(paths, article) { async function fetchWindowsStep(ctx, body, what) { const origin = originOfHandle(await lineageSource(ctx.article, ctx.n, ctx.paths).catch(() => null)); if (origin) { + // An archive removed from settings is not read any more (the editor + // refuses its channels' windows too): nothing is asked of it, and the step + // says to connect it again. The connected ones are settings.json's and + // TRANSCRIPT_SITE_URL's, as the source picker lists them (lib/research/sources.ts). + const settingsFile = process.env.SETTINGS_FILE?.trim() || path.join(REPO_ROOT, "settings.json"); + const stored = await readFile(settingsFile, "utf8").then((t) => JSON.parse(t)?.remoteArchives, () => null); + const gone = disconnectedArchiveRefusal(origin, connectedArchives(stored)); + if (gone) throw new StepFailed(`this article was swept over a published archive, and ${gone}`); const getJson = cachedArchiveGetJson(); body.archive = origin; for (const item of body.items) { if (item.webpageUrl) continue; - const r = await archiveRecordOf(origin, item.slug, item.id, { getJson }).catch(() => null); - // Only a video platform's page (the editor refuses any other, too). - if (r?.webpageUrl && !recordPageRefusal(r.webpageUrl, null, detectPlatform)) item.webpageUrl = r.webpageUrl; + // Only a video platform's page (the editor refuses any other, too), and + // as the URL the check parsed — never the record's own string. + const href = await archiveRecordPageHref(origin, item.slug, item.id, detectPlatform, { getJson }); + if (href) item.webpageUrl = href; } if (ctx.allowWholeRecording) body.allowWholeRecording = true; const dry = await editorCall(await editorEnv(), "POST", "/api/ops/fetch-windows", { ...body, dryRun: true }); diff --git a/umtool/lib/report/chain-run.test.mjs b/umtool/lib/report/chain-run.test.mjs @@ -176,6 +176,24 @@ test("manifest: with no sweep.md naming an origin, the archive the sweep read (s assert.equal(m.provenance.siteOrigin, "https://stub.test"); }); +test("windows: an article swept over an archive that is no longer connected asks nothing of it, and says to connect it again (demo epic D1 re-check)", () => { + // synth-remote's lineage read remote:https://stub.test (the test above); settings.json names no archive. + const env = { ...ENV }; + delete env.TRANSCRIPT_SITE_URL; + const r = spawnSync(process.execPath, ["--import", "tsx", CHAIN_RUN, "step", "synth-remote", "1", "windows", "--projects-root", PROJECTS], { + cwd: REPO_ROOT, + env, + encoding: "utf8", + timeout: 120_000, + }); + assert.equal(r.status, 1, `${r.stdout}\n${r.stderr}`); + const s = Object.fromEntries(json(path.join(ARTICLES, "synth-remote", "iterations", "1", "iteration.json")).steps.map((x) => [x.task, x]))["chain:windows"]; + assert.equal(s.status, "failed"); + assert.match(s.detail, /swept over a published archive, and its archive https:\/\/stub\.test is no longer connected — connect it again/); + // Refused before the plan is written or the editor asked. + assert.equal(existsSync(path.join(PROJECTS, "synth-remote", "i1", "windows.json")), false); +}); + test("cut-windows (Draft everything, demo epic D1): the cut's windows the project already holds are not asked of the editor", () => { // i2's project: its manifest (from the manifest test) and the cut's window in out/clips-raw. const project = path.join(PROJECTS, "synth-basic", "i2"); diff --git a/umtool/report-to-video/cues.test.mjs b/umtool/report-to-video/cues.test.mjs @@ -92,6 +92,17 @@ test("a page URL replaces only the manifest's last segment", () => { ); }); +test("a shard's URL stays on the manifest's origin, whatever the manifest says its page number is", () => { + // slugToPage is the archive's own JSON: a "page number" may be any value. + const at = "https://x.dev/transcripts/some-chan/manifest.json"; + for (const n of ["//evil.example/x", "/../../../../etc/passwd", "@evil.example/", "\\\\evil.example\\x", "https://evil.example/x", "?x=1#y", "$`$'$&", "\n", -1, 1.5, NaN, null, {}, [], "0000.json/../../../corpus"]) { + const url = new URL(pageUrlFrom(at, n)); + assert.equal(url.origin, "https://x.dev", String(n)); + assert.equal(url.search, "", String(n)); + assert.equal(url.hash, "", String(n)); + } +}); + test("resolves a video over HTTP with cues intact", async () => { const got = await source().load("chan", "vid1"); assert.equal(got.from, "http");