commit d694be7a3493778496e746b6da6696fb34e30ef9
parent b1bbf2cb0fdcd68b49193f49775d6bd246a370c0
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 11 Nov 2026 12:17:25 -0500
archives: no archive document past 32 MB is read or kept (demo epic D1 review follow-up)
The probe, the plain reader and the disk cache read any body whole into
memory. readBounded refuses one past MAX_ARCHIVE_DOCUMENT_BYTES (32 MB; a
shard is up to 8 MB) by its Content-Length, else as it streams, and the
cache keeps nothing of it. (Also types archiveTrust.test's helper for tsc.)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat:
4 files changed, 66 insertions(+), 6 deletions(-)
diff --git a/common/lib/archiveCache-server.test.ts b/common/lib/archiveCache-server.test.ts
@@ -161,3 +161,25 @@ test("on by default on a server; off under node's test runner and with ARCHIVE_C
assert.equal(archiveCacheEnabled({ NODE_TEST_CONTEXT: "child-v8" }), false);
assert.equal(archiveCacheEnabled({ NODE_TEST_CONTEXT: "child-v8", ARCHIVE_CACHE: "1" }), true);
});
+
+// demo epic D1 review follow-up: no archive document past 32 MB is read or kept.
+test("a document over the bound is refused: by its Content-Length, or as it streams; nothing is kept", async () => {
+ const { MAX_ARCHIVE_DOCUMENT_BYTES, OversizeError, readBounded, probeArchive } = await import("./remoteArchives-server");
+ const declared = new Response("{}", { headers: { "content-length": String(MAX_ARCHIVE_DOCUMENT_BYTES + 1) } });
+ await assert.rejects(readBounded(declared, "https://stub.test/a.json"), (e: unknown) => e instanceof OversizeError && /is over 32 MB/.test((e as Error).message));
+ // No length said: counted as it streams, refused at the bound (a small one here).
+ const streamed = new Response(new ReadableStream({ start(c) { for (let i = 0; i < 10; i++) c.enqueue(new Uint8Array(100)); c.close(); } }));
+ await assert.rejects(readBounded(streamed, "https://stub.test/b.json", 500), OversizeError);
+ assert.equal(await readBounded(new Response('{"ok":1}'), "https://stub.test/c.json"), '{"ok":1}');
+ // The probe says so, and the cache keeps nothing.
+ const big: FetchLike = async () => new Response("{}", { status: 200, headers: { "content-length": String(MAX_ARCHIVE_DOCUMENT_BYTES + 1) } });
+ await assert.rejects(probeArchive("https://stub.test", { fetch: big }), /is over 32 MB/);
+ const dir = mkdtempSync(path.join(tmpdir(), "archive-cache-"));
+ try {
+ const cache = new ArchiveDiskCache({ dir, fetch: big, sleep: async () => {} });
+ await assert.rejects(cache.fetch("https://stub.test/corpus.json"), OversizeError);
+ await assert.rejects(cache.fetch("https://stub.test/corpus.json"), OversizeError, "nothing was kept to answer from");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/common/lib/archiveCache-server.ts b/common/lib/archiveCache-server.ts
@@ -39,7 +39,7 @@ import { mkdir, readdir, readFile, rm, stat, utimes } from "node:fs/promises";
import path from "node:path";
import { getPaths } from "./paths";
import { writeFileAtomic } from "./atomicFile.mjs";
-import { OffOriginError, fetchOnOrigin, plainGetJson, type FetchLike, type GetJson } from "./remoteArchives-server";
+import { OffOriginError, fetchOnOrigin, plainGetJson, readBounded, type FetchLike, type GetJson } from "./remoteArchives-server";
export const CORPUS_TTL_MS = 10 * 60_000;
export const GAP_MS = 250;
@@ -214,7 +214,8 @@ export class ArchiveDiskCache {
if (meta && res.status >= 500) return this.fromDisk(file, meta, base, corpus);
return res;
}
- const body = await res.text();
+ // Bounded: a document past MAX_ARCHIVE_DOCUMENT_BYTES is refused, never kept.
+ const body = await readBounded(res, url);
if (corpus) this.noteCorpus(base, body);
const next: Meta = {
url,
diff --git a/common/lib/archiveTrust.test.ts b/common/lib/archiveTrust.test.ts
@@ -8,7 +8,7 @@ import { archiveRecordOf } from "../controller/remoteOnlyChannel";
// demo epic D1 review, blocker 2: an archive is untrusted input.
test("a record's page URL: only a video platform's host, the channel's own platform, no credentials", () => {
- const r = (u: string, p: string | null = null) => recordPageRefusal(u, p, detectPlatform);
+ const r = (u: string | undefined, p: string | null = null) => recordPageRefusal(u, p, detectPlatform);
assert.equal(r("https://www.youtube.com/watch?v=a1", "youtube"), null);
assert.equal(r("https://rumble.com/v9-x.html"), null);
assert.match(r("http://127.0.0.1:3001/api/ops/settings")!, /127\.0\.0\.1:3001 is not a video platform's host/);
diff --git a/common/lib/remoteArchives-server.ts b/common/lib/remoteArchives-server.ts
@@ -46,6 +46,42 @@ export class ArchiveProbeError extends Error {
const PROBE_TIMEOUT_MS = 15_000;
const MAX_REDIRECTS = 3;
+// The largest archive document read (demo epic D1 review follow-up): a shard
+// page is up to 8 MB; anything past 32 MB is refused, not buffered.
+export const MAX_ARCHIVE_DOCUMENT_BYTES = 32 * 1024 * 1024;
+
+export class OversizeError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "OversizeError";
+ }
+}
+
+/** A response's body as text, refused past `max` bytes (by its Content-Length, then as it streams). */
+export async function readBounded(res: Response, url: string, max = MAX_ARCHIVE_DOCUMENT_BYTES): Promise<string> {
+ const declared = Number(res.headers.get("content-length"));
+ const over = () => new OversizeError(`${url} is over ${Math.round(max / 1024 / 1024)} MB: an archive document that large is not read`);
+ if (Number.isFinite(declared) && declared > max) {
+ await res.body?.cancel().catch(() => {});
+ throw over();
+ }
+ if (!res.body) return "";
+ const reader = res.body.getReader();
+ const chunks: Uint8Array[] = [];
+ 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 Buffer.concat(chunks).toString("utf8");
+}
+
export class OffOriginError extends Error {
constructor(message: string) {
super(message);
@@ -97,8 +133,9 @@ export async function probeArchive(rawOrigin: string, opts: { fetch?: FetchLike;
if (!res.ok) throw new ArchiveProbeError(`${url} answered HTTP ${res.status} — is ${origin} a published archive?`, 502);
let j: Record<string, unknown>;
try {
- j = (await res.json()) as Record<string, unknown>;
- } catch {
+ j = JSON.parse(await readBounded(res, url)) as Record<string, unknown>;
+ } catch (e) {
+ if (e instanceof OversizeError) throw new ArchiveProbeError(e.message, 502);
throw new ArchiveProbeError(`${url} is not JSON — ${origin} does not serve an archive's contract`, 502);
}
if (!j || typeof j !== "object" || Array.isArray(j)) throw new ArchiveProbeError(`${url} is not an archive's corpus.json`, 502);
@@ -183,7 +220,7 @@ export function plainGetJson(doFetch: FetchLike = fetch as unknown as FetchLike)
return async (url) => {
const res = await fetchOnOrigin(doFetch, url, { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS), headers: { accept: "application/json" } });
if (!res.ok) throw new ArchiveChannelError(`${url} answered HTTP ${res.status}`, res.status === 404 ? 404 : 502);
- return res.json();
+ return JSON.parse(await readBounded(res, url));
};
}