commit 894f1bfc6accaf9f355414da6dd6d74af1ed05a6
parent 550e414a20eb475b2eb0364feccb7a1f0641719e
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 11 Nov 2026 23:48:40 -0500
umtool: an archive is untrusted input to the render too -- the cue walk, the link check and a source's build identity read a document on the archive's own origin (a manifest named elsewhere is not followed, a redirect elsewhere refused) and never past 32 MB (demo epic D1 re-review, items 3 and 4)
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
7 files changed, 286 insertions(+), 16 deletions(-)
diff --git a/umtool/lib/report/linkCheck.mjs b/umtool/lib/report/linkCheck.mjs
@@ -28,7 +28,7 @@
// Plain ESM: the CLI runs it under bare node.
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
import path from "node:path";
-import { createJsonCache, DEFAULT_CACHE_DIR, pagesVersionOf, pageUrlFrom } from "umtool-report-to-video/cues";
+import { createJsonCache, DEFAULT_CACHE_DIR, pagesVersionOf, pageUrlFrom, transcriptsManifestUrl } from "umtool-report-to-video/cues";
import { qrsOf } from "umtool-report-to-video/lint";
import { jitterUp } from "yt-dlp-transcript-common/lib/jitter.mjs";
import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs";
@@ -213,11 +213,13 @@ export async function checkLinks(
});
continue;
}
- const manifestUrl = ch.manifests?.transcripts;
- if (typeof manifestUrl !== "string" || !manifestUrl) {
+ if (typeof ch.manifests?.transcripts !== "string" || !ch.manifests.transcripts) {
out.push({ clip, url, state: "dead", origin: a.origin, why: `${host} publishes no transcripts for "${a.channel}"` });
continue;
}
+ // The manifest the corpus names, when it is on the archive's own origin;
+ // one named elsewhere is not followed (report-to-video/archive-fetch.mjs).
+ const manifestUrl = transcriptsManifestUrl(a.origin, ch);
const man = await channelManifest(manifestUrl);
if (!man.doc) {
out.push({ clip, url, state: "unverified", origin: a.origin, why: `couldn't read ${a.channel}'s manifest on ${host} (${man.error})` });
diff --git a/umtool/lib/research/sources.test.ts b/umtool/lib/research/sources.test.ts
@@ -17,7 +17,7 @@ process.env.SETTINGS_FILE = settingsFile;
process.env.TRANSCRIPT_LOCAL_DIR = local;
process.env.TRANSCRIPT_HUB_URL = "";
process.env.TRANSCRIPT_SITE_URL = "https://env.test";
-const { listSources } = await import("./sources");
+const { listSources, buildIdentity } = await import("./sources");
test.after(() => rm(root, { recursive: true, force: true }));
@@ -41,3 +41,49 @@ test("with a local build the local corpus is the default, the archives after it"
assert.equal(s[0].handle, `local:${local}`);
assert.deepEqual(s.slice(1).map((x) => x.handle), ["remote:https://stub.test", "remote:https://env.test"]);
});
+
+// demo epic D1 re-review, item 4: a source's build is read from its own origin, bounded.
+test("a remote source's build identity: corpus.json on its own origin; a redirect elsewhere or an oversize answer is no identity", async () => {
+ const option = { handle: "remote:https://stub.test", kind: "remote", label: "Stub" } as never;
+ const asked: { url: string; redirect?: string }[] = [];
+ const fake = (answers: Record<string, () => Response>) =>
+ (async (url: string, init?: { redirect?: string }) => {
+ asked.push({ url, redirect: init?.redirect });
+ return (answers[url] ?? (() => new Response("nope", { status: 404 })))();
+ }) as never;
+
+ assert.equal(await buildIdentity(option, fake({ "https://stub.test/corpus.json": () => new Response(JSON.stringify({ generatedAt: "2026-11-01T00:00:00Z" })) })), "2026-11-01T00:00:00Z");
+ assert.deepEqual(asked, [{ url: "https://stub.test/corpus.json", redirect: "manual" }]);
+
+ // A same-origin redirect is followed.
+ assert.equal(
+ await buildIdentity(
+ option,
+ fake({
+ "https://stub.test/corpus.json": () => new Response(null, { status: 301, headers: { location: "/v2/corpus.json" } }),
+ "https://stub.test/v2/corpus.json": () => new Response(JSON.stringify({ generatedAt: "g2" })),
+ }),
+ ),
+ "g2",
+ );
+
+ // One that leaves the origin is not: nothing is asked of the other host.
+ asked.length = 0;
+ assert.equal(
+ await buildIdentity(
+ option,
+ fake({
+ "https://stub.test/corpus.json": () => new Response(null, { status: 302, headers: { location: "http://127.0.0.1:3001/api/ops/settings" } }),
+ "http://127.0.0.1:3001/api/ops/settings": () => new Response(JSON.stringify({ generatedAt: "leaked" })),
+ }),
+ ),
+ null,
+ );
+ assert.deepEqual(asked.map((a) => a.url), ["https://stub.test/corpus.json"]);
+
+ // An answer declaring more than the document bound is not read.
+ assert.equal(
+ await buildIdentity(option, fake({ "https://stub.test/corpus.json": () => new Response(JSON.stringify({ generatedAt: "big" }), { headers: { "content-length": String(64 * 1024 * 1024) } }) })),
+ null,
+ );
+});
diff --git a/umtool/lib/research/sources.ts b/umtool/lib/research/sources.ts
@@ -2,6 +2,7 @@ import { readdir, readFile, stat } from "node:fs/promises";
import path from "node:path";
import { SourceRegistry, type ShardSource, type SourceSpec } from "yt-dlp-transcript-mcp/research";
import { connectedArchives } from "yt-dlp-transcript-common/lib/remoteArchives";
+import { fetchOnOrigin, readBounded, type FetchLike } from "yt-dlp-transcript-common/lib/remoteArchives-server";
import { REPO_ROOT, REPORTS_ROOT, SITES_DIR } from "../paths.mjs";
import { readCensus } from "./census.mjs";
import type { SourceOption } from "./types";
@@ -149,7 +150,7 @@ const IDENTITY_TIMEOUT_MS = 10_000;
* file's mtime and size (a recomposed export/public changes both). Null when
* it cannot be told -- then the census is counted but not kept.
*/
-export async function buildIdentity(option: SourceOption): Promise<string | null> {
+export async function buildIdentity(option: SourceOption, doFetch: FetchLike = fetch as unknown as FetchLike): Promise<string | null> {
if (option.kind === "local") {
const file = path.join(/* turbopackIgnore: true */ option.handle.slice("local:".length), "corpus.json");
const st = await stat(/* turbopackIgnore: true */ file).catch(() => null);
@@ -159,9 +160,12 @@ export async function buildIdentity(option: SourceOption): Promise<string | null
}
const url = option.handle.replace(/^(remote|hub):/, "").replace(/#.*$/, "");
try {
- const res = await fetch(`${url}/corpus.json`, { signal: AbortSignal.timeout(IDENTITY_TIMEOUT_MS) });
+ // An archive is untrusted input: read on its own origin (no redirect
+ // elsewhere is followed) and never past the document bound.
+ const at = `${url}/corpus.json`;
+ const res = await fetchOnOrigin(doFetch, at, { signal: AbortSignal.timeout(IDENTITY_TIMEOUT_MS) });
if (!res.ok) return null;
- const j = (await res.json()) as { generatedAt?: unknown };
+ const j = JSON.parse(await readBounded(res, at)) as { generatedAt?: unknown };
return typeof j.generatedAt === "string" && j.generatedAt ? j.generatedAt : null;
} catch {
return null;
diff --git a/umtool/report-to-video/archive-fetch.mjs b/umtool/report-to-video/archive-fetch.mjs
@@ -0,0 +1,106 @@
+// READING A PUBLISHED ARCHIVE, AS UNTRUSTED INPUT (demo epic D1 re-review, item 3).
+//
+// An archive is someone else's server and someone else's JSON. The editor
+// reads one through common/lib/remoteArchives-server.ts (fetchOnOrigin,
+// readBounded, and archiveRecordOf's "a manifest the corpus names elsewhere is
+// not followed"); this is the same three rules for the render's cue walk and
+// the other readers of createJsonCache (cues.mjs), in plain JS because these
+// scripts run under bare node with no tsx. Change one, change the other.
+//
+// - a document is read on the origin it was asked on: a redirect is followed
+// by hand, up to three, and only to the same scheme, host and port;
+// - no document past 32 MB is read (a shard page is up to 8 MB);
+// - a channel's transcripts manifest is the one corpus.json names only when
+// that is on the corpus's own origin; otherwise the contract's URL.
+
+export const MAX_ARCHIVE_DOCUMENT_BYTES = 32 * 1024 * 1024;
+const MAX_REDIRECTS = 3;
+
+/** Whether `url` is on `origin`'s own scheme, host and port. */
+export function sameOrigin(url, origin) {
+ try {
+ return new URL(url).origin === new URL(origin).origin;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * A GET that stays on `url`'s origin. `fetchImpl(url, init)` is asked with
+ * `redirect: "manual"`; a 3xx with a Location is followed only on the same
+ * origin, at most three times, and one that leaves it throws before it is
+ * followed.
+ */
+export async function fetchOnOrigin(fetchImpl, url, init = {}) {
+ let at = url;
+ for (let hop = 0; ; hop += 1) {
+ const res = await fetchImpl(at, { ...init, redirect: "manual" });
+ const status = Number(res?.status);
+ if (!(status >= 300 && status <= 399) || status === 304) return res;
+ const location = res.headers?.get?.("location");
+ if (!location) return res;
+ const next = new URL(location, at).href;
+ if (!sameOrigin(next, url)) {
+ throw new Error(`GET ${at} redirects to ${new URL(next).origin}: an archive's documents are read from its own origin only`);
+ }
+ if (hop >= MAX_REDIRECTS) throw new Error(`GET ${url} redirects more than ${MAX_REDIRECTS} times`);
+ at = next;
+ }
+}
+
+/**
+ * A response's JSON, refused past `max` bytes: by its Content-Length first,
+ * then as the body streams. A response with no stream (a test's stub) is read
+ * as it offers itself, its text measured when it has one.
+ */
+export async function readJsonBounded(res, url, max = MAX_ARCHIVE_DOCUMENT_BYTES) {
+ const over = () => new Error(`GET ${url} is over ${Math.round(max / 1024 / 1024)} MB: an archive document that large is not read`);
+ const declared = Number(res.headers?.get?.("content-length"));
+ if (Number.isFinite(declared) && declared > max) {
+ await res.body?.cancel?.().catch(() => {});
+ throw over();
+ }
+ if (res.body && typeof res.body.getReader === "function") {
+ const reader = res.body.getReader();
+ const chunks = [];
+ let total = 0;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value.byteLength;
+ if (total > max) {
+ await reader.cancel().catch(() => {});
+ throw over();
+ }
+ chunks.push(value);
+ }
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
+ }
+ if (typeof res.text === "function") {
+ const text = await res.text();
+ if (Buffer.byteLength(text) > max) throw over();
+ return JSON.parse(text);
+ }
+ return res.json();
+}
+
+/**
+ * Where a channel's transcripts manifest is read: the URL its corpus.json
+ * entry names when that is on `origin` itself (a relative one is resolved
+ * against it), else the contract's `<origin>/transcripts/<slug>/manifest.json`
+ * — a manifest named on another origin is never followed.
+ */
+export function transcriptsManifestUrl(origin, entry) {
+ const base = new URL(origin).origin;
+ const contract = `${base}/transcripts/${encodeURIComponent(String(entry?.slug ?? ""))}/manifest.json`;
+ const named = entry?.manifests?.transcripts;
+ if (typeof named !== "string" || !named.trim()) return contract;
+ let resolved;
+ try {
+ resolved = new URL(named.trim(), `${base}/`);
+ } catch {
+ return contract;
+ }
+ if (resolved.origin !== base || resolved.username || resolved.password) return contract;
+ return resolved.href;
+}
diff --git a/umtool/report-to-video/cues.mjs b/umtool/report-to-video/cues.mjs
@@ -64,6 +64,10 @@ import os from "node:os";
import { createHash } from "node:crypto";
import { fileURLToPath } from "node:url";
import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
+import { fetchOnOrigin, readJsonBounded, transcriptsManifestUrl } from "./archive-fetch.mjs";
+
+// For the other readers of an archive that come through this module (linkCheck.mjs).
+export { transcriptsManifestUrl };
// This file lives at <repo>/umtool/report-to-video/, so the corpus a plain
// checkout would have is two levels up. Previously this defaulted to an absolute
@@ -244,9 +248,11 @@ export function createJsonCache({
if (inflight.has(flight)) return inflight.get(flight);
const pending = (async () => {
log(`fetch ${url}`);
- const res = await fetchImpl(url);
+ // An archive is untrusted input (archive-fetch.mjs): the document is
+ // read on the origin it was asked on, and never past 32 MB.
+ const res = await fetchOnOrigin(fetchImpl, url);
if (!res.ok) throw new Error(`GET ${url} -> ${res.status}`);
- const json = await res.json();
+ const json = await readJsonBounded(res, url);
mem.set(url, { version, body: json });
fetchedAt.set(url, Date.now());
if (disk) {
@@ -324,10 +330,11 @@ export function createCueSource({
// terrible one to pay silently, so the direct lookup fails with instructions
// instead and this runs only when asked.
async function resolveSiteId(origin, entry, wanted) {
- const manifest = await getJson(entry.manifests.transcripts);
+ const manifestAt = transcriptsManifestUrl(origin, entry);
+ const manifest = await getJson(manifestAt);
log(`resolving "${wanted}" by scanning ${manifest.pageCount} shard(s) of ${entry.slug}`);
for (let n = 0; n < manifest.pageCount; n += 1) {
- const page = await getJson(pageUrlFrom(entry.manifests.transcripts, n), { version: pagesVersionOf(manifest) });
+ const page = await getJson(pageUrlFrom(manifestAt, n), { version: pagesVersionOf(manifest) });
const hit = page.find(
(r) => r.id === wanted || r.slug === wanted || String(r.webpageUrl ?? "").includes(wanted),
);
@@ -348,7 +355,10 @@ export function createCueSource({
const siteChannel = hints.siteChannel ?? channelSlug;
const siteVideo = hints.siteVideo ?? videoId;
const entry = await channelEntry(origin, siteChannel);
- const manifest = await getJson(entry.manifests.transcripts);
+ // The manifest corpus.json names, when it is on the archive's own origin;
+ // one named elsewhere is not followed — the contract's URL is read instead.
+ const manifestAt = transcriptsManifestUrl(origin, entry);
+ const manifest = await getJson(manifestAt);
const pageNumber = manifest.slugToPage?.[siteVideo];
if (pageNumber === undefined) {
@@ -365,17 +375,17 @@ export function createCueSource({
` up to 8 MB per shard until it matches).\n` +
` Note that a clip's citeUrl is NOT usable here — it may deliberately cite a\n` +
` different recording (a mirror that reads better), whose clock is not the same.`,
- { channelSlug, videoId, tried: [entry.manifests.transcripts] },
+ { channelSlug, videoId, tried: [manifestAt] },
);
}
- const page = await getJson(pageUrlFrom(entry.manifests.transcripts, pageNumber), { version: pagesVersionOf(manifest) });
+ const page = await getJson(pageUrlFrom(manifestAt, pageNumber), { version: pagesVersionOf(manifest) });
const record = page.find((r) => r.id === siteVideo || r.slug === siteVideo);
if (!record) {
throw new CueLookupError(
`${siteChannel}/${siteVideo} is on shard ${pageNumber} per the manifest, but no record ` +
`there has that id — the published archive is inconsistent`,
- { channelSlug, videoId, tried: [pageUrlFrom(entry.manifests.transcripts, pageNumber)] },
+ { channelSlug, videoId, tried: [pageUrlFrom(manifestAt, pageNumber)] },
);
}
return { ...record, from: "http" };
diff --git a/umtool/report-to-video/cues.test.mjs b/umtool/report-to-video/cues.test.mjs
@@ -19,6 +19,7 @@ import {
pageUrlFrom,
siteOriginFromManifest,
} from "./cues.mjs";
+import { readJsonBounded, transcriptsManifestUrl } from "./archive-fetch.mjs";
const ORIGIN = "https://example.pages.dev";
@@ -567,6 +568,106 @@ test("prefer:local refuses to fall back rather than cut from other cues", async
});
});
+// --- an archive is untrusted input (demo epic D1 re-review, item 3) ----------
+
+test("a manifest corpus.json names on another origin is not followed: the contract's URL on the archive's own origin is read", async () => {
+ const seen = [];
+ const routes = {
+ ...ROUTES,
+ [`${ORIGIN}/corpus.json`]: { channels: [{ slug: "chan", manifests: { transcripts: "http://127.0.0.1:3001/api/ops/settings" } }] },
+ "http://127.0.0.1:3001/api/ops/settings": { pageCount: 1, slugToPage: { vid1: 0 } },
+ "http://127.0.0.1:3001/api/ops/page-0000.json": [{ ...RECORD, title: "from the other host" }],
+ };
+ const rec = await source({ fetchImpl: stubFetch(routes, seen) }).load("chan", "vid1");
+ assert.equal(rec.title, "A Title");
+ assert.deepEqual(seen, [`${ORIGIN}/corpus.json`, `${ORIGIN}/transcripts/chan/manifest.json`, `${ORIGIN}/transcripts/chan/page-0000.json`]);
+ // The opt-in shard scan walks the same manifest.
+ const seen2 = [];
+ const hit = await source({ fetchImpl: stubFetch(routes, seen2), resolveSiteIds: true }).load("chan", "v94hyv");
+ assert.equal(hit.id, "other");
+ assert.equal(seen2.some((u) => !u.startsWith(ORIGIN)), false);
+});
+
+test("transcriptsManifestUrl: the named manifest on the origin (absolute or relative), else the contract's", () => {
+ const at = (transcripts, slug = "chan") => transcriptsManifestUrl(ORIGIN, { slug, manifests: { transcripts } });
+ assert.equal(at(`${ORIGIN}/transcripts/chan/manifest.json`), `${ORIGIN}/transcripts/chan/manifest.json`);
+ assert.equal(at(`${ORIGIN}/shared/chan/manifest.json`), `${ORIGIN}/shared/chan/manifest.json`, "a same-origin manifest elsewhere in the tree is the archive's to name");
+ assert.equal(at("/transcripts/chan/manifest.json"), `${ORIGIN}/transcripts/chan/manifest.json`);
+ for (const off of [
+ "https://evil.example/transcripts/chan/manifest.json",
+ "http://example.pages.dev/transcripts/chan/manifest.json", // another scheme is another origin
+ "https://example.pages.dev:8443/transcripts/chan/manifest.json",
+ "https://user:pw@example.pages.dev/transcripts/chan/manifest.json",
+ "//evil.example/m.json",
+ "file:///etc/passwd",
+ "",
+ undefined,
+ 42,
+ ]) {
+ assert.equal(at(off), `${ORIGIN}/transcripts/chan/manifest.json`, String(off));
+ }
+ assert.equal(at(undefined, "../../x"), `${ORIGIN}/transcripts/..%2F..%2Fx/manifest.json`, "a slug cannot climb out of the tree");
+ assert.equal(transcriptsManifestUrl(`${ORIGIN}/`, { slug: "chan" }), `${ORIGIN}/transcripts/chan/manifest.json`);
+});
+
+test("the cache reads a document on its own origin: a same-origin redirect is followed, one elsewhere refused unfollowed, more than three refused", async () => {
+ const asked = [];
+ const answers = {
+ [`${ORIGIN}/a.json`]: { status: 301, location: "/b.json" },
+ [`${ORIGIN}/b.json`]: { status: 200, body: { ok: 1 } },
+ [`${ORIGIN}/leave.json`]: { status: 302, location: "http://169.254.169.254/latest/meta-data/" },
+ "http://169.254.169.254/latest/meta-data/": { status: 200, body: { leaked: true } },
+ [`${ORIGIN}/loop.json`]: { status: 302, location: "/loop.json" },
+ };
+ const fetchImpl = async (url, init) => {
+ asked.push(url);
+ assert.equal(init?.redirect, "manual", "every request is asked not to follow redirects");
+ const a = answers[url];
+ if (!a) return new Response("nope", { status: 404 });
+ return new Response(a.body === undefined ? null : JSON.stringify(a.body), { status: a.status, headers: a.location ? { location: a.location } : {} });
+ };
+ const { getJson } = createJsonCache({ cacheDir: null, fetchImpl });
+ assert.deepEqual(await getJson(`${ORIGIN}/a.json`), { ok: 1 });
+ await assert.rejects(() => getJson(`${ORIGIN}/leave.json`), /redirects to http:\/\/169\.254\.169\.254: an archive's documents are read from its own origin only/);
+ assert.equal(asked.includes("http://169.254.169.254/latest/meta-data/"), false);
+ await assert.rejects(() => getJson(`${ORIGIN}/loop.json`), /redirects more than 3 times/);
+ assert.equal(asked.filter((u) => u.endsWith("/loop.json")).length, 4);
+});
+
+test("the cache reads no document past the bound: by its declared length, and as it streams", async () => {
+ const big = 33 * 1024 * 1024;
+ const declared = createJsonCache({
+ cacheDir: null,
+ fetchImpl: async () => new Response("{}", { headers: { "content-length": String(big) } }),
+ });
+ await assert.rejects(() => declared.getJson(`${ORIGIN}/big.json`), /is over 32 MB: an archive document that large is not read/);
+ // No Content-Length: counted as it arrives, and the stream cancelled.
+ let sent = 0;
+ let cancelled = false;
+ const chunk = new Uint8Array(1024 * 1024).fill(0x20);
+ const streaming = createJsonCache({
+ cacheDir: null,
+ fetchImpl: async () =>
+ new Response(
+ new ReadableStream({
+ pull(c) {
+ sent += 1;
+ c.enqueue(chunk);
+ },
+ cancel() {
+ cancelled = true;
+ },
+ }),
+ ),
+ });
+ await assert.rejects(() => streaming.getJson(`${ORIGIN}/endless.json`), /is over 32 MB/);
+ assert.equal(cancelled, true);
+ assert.ok(sent < 40, `stopped reading soon after the bound (${sent} MB sent)`);
+ // A document under it is read as before.
+ assert.deepEqual(await readJsonBounded(new Response(JSON.stringify({ a: 1 })), `${ORIGIN}/x.json`), { a: 1 });
+ await assert.rejects(() => readJsonBounded(new Response("x".repeat(64)), `${ORIGIN}/x.json`, 16), /is over 0 MB/);
+});
+
// --- origin discovery -------------------------------------------------------
test("the archive origin comes from the manifest, in priority order", () => {
diff --git a/umtool/report-to-video/post-links.mjs b/umtool/report-to-video/post-links.mjs
@@ -64,7 +64,8 @@ export function createPostChannelResolver({
refreshAfterMs = Infinity,
now = Date.now,
} = {}) {
- const timed = (url) => fetchImpl(url, { signal: AbortSignal.timeout(timeoutMs) });
+ // `init` is the cache's (archive-fetch.mjs asks with `redirect: "manual"`).
+ const timed = (url, init) => fetchImpl(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
const get = getJson ?? createJsonCache({ ...(cacheDir !== undefined ? { cacheDir } : {}), fetchImpl: timed, log, refreshAfterMs }).getJson;
// ONE memo of failed reads, `url -> { err, at, refresh }`, consulted by both
// passes (the cached read and the fresh one): a URL that failed is not asked