commit cff7dfbdb0be558f6259213323bf2d14812cf31a
parent baf7673b1eb5727caf0307be9dab618531ebf972
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 10 Nov 2026 18:03:07 -0500
umtool: a write over the proxy's 16 MB cap is answered 413 with a JSON {error} (writeGuard.mjs bodyRefusal, asked by proxy.ts after the cross-site guard), never handed to its route cut at the cap; BODY_CAP held equal to next.config.ts's proxyClientMaxBodySize. The sweep gains its read rule: no GET/HEAD handler under app/api/ calls a manifest writer (MANIFEST_WRITERS, each checked still exported) nor writes a file, but the eight cache writers named with why (clip audio/video, face frame, ensureWindowFile's excerpts). The EXEMPT uploads' comment says what their code does: crossSiteRefusal on every call, a browser's or not, so a Host that is not this machine is refused even from curl (E5 A4, the E4 nits)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat:
7 files changed, 118 insertions(+), 8 deletions(-)
diff --git a/umtool/app/api/report/post-narration/record/route.ts b/umtool/app/api/report/post-narration/record/route.ts
@@ -56,7 +56,9 @@ export async function GET(request: Request) {
}
export async function POST(request: Request) {
- // OUTSIDE THE PROXY (an upload: lib/report/writeGuard.mjs EXEMPT), so refused cross-site here, before the body.
+ // OUTSIDE THE PROXY (an upload: lib/report/writeGuard.mjs EXEMPT), so crossSiteRefusal here, before the body, on
+ // EVERY call, a browser's or not: a Host / X-Forwarded-Host not this machine (nor UMTOOL_ALLOWED_HOSTS) is refused
+ // even from curl, and so is a write from another site's page.
const cross = crossSiteRefusal(request.headers);
if (cross) return Response.json({ error: cross }, { status: 403 });
const refused = refuseCaller(request, "/api/report/post-narration/record");
diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts
@@ -166,7 +166,9 @@ export async function GET(request: Request) {
// is a multipart upload, so those are made on the cut's bench.
const TAKE_OPS = new Set(["reread", "set", "fit"]);
export async function POST(request: Request) {
- // OUTSIDE THE PROXY (an upload: lib/report/writeGuard.mjs EXEMPT), so refused cross-site here, before the body.
+ // OUTSIDE THE PROXY (an upload: lib/report/writeGuard.mjs EXEMPT), so crossSiteRefusal here, before the body, on
+ // EVERY call, a browser's or not: a Host / X-Forwarded-Host not this machine (nor UMTOOL_ALLOWED_HOSTS) is refused
+ // even from curl, and so is a write from another site's page.
const cross = crossSiteRefusal(request.headers);
if (cross) return Response.json({ error: cross }, { status: 403 });
if ((request.headers.get("content-type") ?? "").startsWith("multipart/form-data")) return postHere(request);
diff --git a/umtool/app/api/report/voices/route.ts b/umtool/app/api/report/voices/route.ts
@@ -99,7 +99,9 @@ export async function GET(request: Request) {
}
export async function POST(request: Request) {
- // OUTSIDE THE PROXY (an upload: lib/report/writeGuard.mjs EXEMPT), so refused cross-site here, before the body.
+ // OUTSIDE THE PROXY (an upload: lib/report/writeGuard.mjs EXEMPT), so crossSiteRefusal here, before the body, on
+ // EVERY call, a browser's or not: a Host / X-Forwarded-Host not this machine (nor UMTOOL_ALLOWED_HOSTS) is refused
+ // even from curl, and so is a write from another site's page.
const cross = crossSiteRefusal(request.headers);
if (cross) return Response.json({ error: cross }, { status: 403 });
const refused = refuseCaller(request, "/api/report/voices");
diff --git a/umtool/e2e/write-guard.spec.ts b/umtool/e2e/write-guard.spec.ts
@@ -43,6 +43,10 @@ test("another site's write is refused by the proxy; a terminal's, a read and the
r = await request.post("/api/projects/new", { data: JSON.stringify({ kind: "", pad: "x".repeat(12 * 1024 * 1024) }), headers: plain });
expect(r.status()).toBe(400);
expect(await said(r)).toContain("unknown kind");
+ // Over the cap: answered 413 with its sentence (writeGuard.mjs bodyRefusal), never handed to the route cut.
+ r = await request.post("/api/projects/new", { data: JSON.stringify({ kind: "", pad: "x".repeat(20 * 1024 * 1024) }), headers: plain });
+ expect(r.status()).toBe(413);
+ expect(await said(r)).toContain("over the 16777216 (16 MB)");
// A read from anywhere is not the proxy's business.
r = await request.get("/api/projects/new?from=", { headers: { origin: "https://evil.example", "sec-fetch-site": "cross-site" } });
expect(r.status()).not.toBe(403);
diff --git a/umtool/lib/report/writeGuard.mjs b/umtool/lib/report/writeGuard.mjs
@@ -21,11 +21,35 @@ import { crossSiteRefusal } from "./sameOrigin.mjs";
// THE UPLOADS ARE OUTSIDE THE PROXY. For a request the proxy matches, Next holds the body twice in memory before
// the proxy runs and hands the route a copy cut off at proxyClientMaxBodySize (next.config.ts, kept small so a
// cross-site tab cannot make the server buffer gigabytes). A recording uploaded from a page is bigger than any such
-// cap, so these routes stay out of the matcher. Each one refuses cross-site ITSELF, as the first thing its write
-// handler does, before it reads the body (writeGuard.test.mjs checks the order in the source).
+// cap, so these routes stay out of the matcher. Each one calls crossSiteRefusal ITSELF, as the first thing its write
+// handler does, before it reads the body (writeGuard.test.mjs checks the order in the source) -- on EVERY request,
+// not only a browser's as writeRefusal does: one naming a Host or X-Forwarded-Host that is not this machine (nor in
+// UMTOOL_ALLOWED_HOSTS) is refused even from curl or the editor's server (`Host: umtool:3050` in docker), and so is
+// a browser's from another site.
export const EXEMPT = ["/api/report/voices", "/api/report/post-narration", "/api/report/post-narration/record"];
/**
+ * The proxy's body cap: next.config.ts `proxyClientMaxBodySize: "16mb"` (Next's bytes: 16 × 1024 × 1024), which
+ * writeGuard.test.mjs holds equal. A matched body over it reaches its route CUT at the cap, so it never parses.
+ */
+export const BODY_CAP = 16 * 1024 * 1024;
+
+/**
+ * The sentence to refuse a write with (413) when its declared length is over BODY_CAP, or null. A body with no
+ * `content-length` (chunked) is not judged here: the route sees it cut, and refuses it as it does any bad body.
+ * @param {string} method
+ * @param {string} pathname
+ * @param {{ get(name: string): string | null }} headers
+ */
+export function bodyRefusal(method, pathname, headers) {
+ if (!guardedPath(method, pathname)) return null;
+ const said = (headers.get("content-length") ?? "").trim();
+ const n = /^\d+$/.test(said) ? Number(said) : NaN;
+ if (!(n > BODY_CAP)) return null;
+ return `the body is ${n} bytes, over the ${BODY_CAP} (16 MB) a write to umtool's API takes -- an upload goes to its own route (a voice, a narration recording)`;
+}
+
+/**
* The proxy's matcher: everything under /api/ except EXEMPT. umtool/proxy.ts must say exactly this string, because
* Next reads a matcher at build time and it cannot be imported (the sweep test checks).
*/
diff --git a/umtool/lib/report/writeGuard.test.mjs b/umtool/lib/report/writeGuard.test.mjs
@@ -5,7 +5,7 @@ import fs from "node:fs";
import path from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
-import { EXEMPT, GUARD_MATCHER, guardedPath, writeRefusal } from "./writeGuard.mjs";
+import { BODY_CAP, bodyRefusal, EXEMPT, GUARD_MATCHER, guardedPath, writeRefusal } from "./writeGuard.mjs";
const UMTOOL = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
const APP = path.join(UMTOOL, "app");
@@ -106,6 +106,7 @@ test("every route that exports a write is behind the proxy", () => {
for (const p of EXEMPT) assert.ok(!matcherCovers(GUARD_MATCHER, p), `the matcher leaves out ${p}`);
assert.match(proxySrc, /export function proxy\b/, "proxy.ts exports proxy");
assert.match(proxySrc, /writeRefusal\(request\.method, request\.nextUrl\.pathname, request\.headers\)/, "proxy.ts asks writeRefusal");
+ assert.match(proxySrc, /bodyRefusal\(request\.method, request\.nextUrl\.pathname, request\.headers\)[\s\S]*status: 413/, "proxy.ts asks bodyRefusal, 413");
assert.ok(!fs.existsSync(path.join(UMTOOL, "middleware.ts")), "no middleware.ts beside proxy.ts");
const all = routes();
@@ -137,3 +138,74 @@ test("every route that exports a write is behind the proxy", () => {
assert.deepEqual(uncovered, [], "a write the proxy does not guard");
assert.deepEqual(exempt.sort(), EXEMPT.map((p) => `POST ${p}`).sort(), "every EXEMPT path is a POST route the sweep checked");
});
+
+test("bodyRefusal: a write declaring a body over the proxy's cap is refused (413, a sentence); at the cap, a read, or no length passes -- and the cap is next.config.ts's", () => {
+ const cfg = fs.readFileSync(path.join(UMTOOL, "next.config.ts"), "utf8");
+ const said = /proxyClientMaxBodySize:\s*"(\d+)mb"/.exec(cfg);
+ assert.ok(said, "next.config.ts names proxyClientMaxBodySize in mb");
+ assert.equal(Number(said[1]) * 1024 * 1024, BODY_CAP, "BODY_CAP is next.config.ts's cap");
+ const len = (n) => h({ "content-length": String(n) });
+ assert.match(String(bodyRefusal("POST", "/api/projects/new", len(BODY_CAP + 1))), /over the 16777216 \(16 MB\)/);
+ assert.match(String(bodyRefusal("PUT", "/api/report/window", len(20 * 1024 * 1024))), /20971520 bytes/);
+ assert.equal(bodyRefusal("POST", "/api/projects/new", len(BODY_CAP)), null, "at the cap");
+ assert.equal(bodyRefusal("POST", "/api/projects/new", h({})), null, "no length (chunked): the route judges what it gets");
+ assert.equal(bodyRefusal("POST", "/api/projects/new", h({ "content-length": "1e9" })), null, "not a length");
+ assert.equal(bodyRefusal("GET", "/api/projects/new", len(BODY_CAP + 1)), null, "a read");
+ assert.equal(bodyRefusal("POST", "/projects", len(BODY_CAP + 1)), null, "not under /api/");
+});
+
+// THE READS WRITE NO MANIFEST (umtool redesign E5 A4): a GET or HEAD is what a tab, a prefetch, a crawler or a
+// cross-site <img> may send without asking -- the proxy lets every read through -- so no GET/HEAD handler under
+// app/api/ calls a writer of the project's manifest, its draft, its versions or its undo stack, nor writes a file
+// itself, but for the cache writers named below with why each is only a cache.
+const MANIFEST_WRITERS = [
+ // lib/report/manifest.mjs
+ "updateClip", "updateClaim", "addLedgerRow", "updateLedgerRow", "removeLedgerRow", "updateOnscreen", "updateChrome", "updatePreset",
+ "addDeckChrome", "updateRenderKeys", "updateRender", "updatePosts", "updateStorage", "updateArticleLink", "updateLinkPolicy",
+ "updateClaimKnobs", "updateMarks", "updateVariants", "replaceManifest", "undoStructural", "redoStructural", "moveEntry", "removeEntry",
+ "insertEntry", "duplicateEntry", "upsertPost", "removePost", "updateFactcheck", "updateTeaser", "autoSnapshot", "pruneAutoSnapshots",
+ // lib/report/snapshots.mjs
+ "createSnapshot", "writeSnapshotRaw",
+ // lib/report/versions.mjs
+ "writeDraft", "saveVersion", "judgeDraft", "openVersion", "freezeTakes",
+ // lib/report/takeEdit.mjs, takes.mjs, takeManifest.mjs
+ "undoTakeEdit", "setTakeVerdict", "writePlayManifest",
+];
+const FILE_WRITES = ["writeFile", "writeFileSync", "rename", "renameSync", "writeFileAtomic", "writeFileAtomicSync", "writeJsonAtomic", "ensureWindowFile"];
+/** `<route file> <method> <writer>` -> why it is only a cache. */
+const CACHE_ONLY_GET = {
+ "app/api/clip/[key]/audio/route.ts GET writeFile": "the clip's audio window, level-normalised, cached under the clip cache by its stamp",
+ "app/api/clip/[key]/audio/route.ts GET rename": "the same cache file put in place",
+ "app/api/clip/[key]/video/route.ts GET rename": "the clip's video window cut once into the clip cache",
+ "app/api/face/frame/route.ts GET rename": "one extracted frame, cached by its source and second",
+ "app/api/report/audio/route.ts GET ensureWindowFile": "a recording's excerpt cut into out/clips-raw (serve.mjs, a cache any read may make)",
+ "app/api/report/clip/route.ts GET ensureWindowFile": "the same excerpt, started early for the bench's player",
+ "app/api/report/peaks/route.ts GET ensureWindowFile": "the same excerpt, for its waveform",
+ "app/api/report/raw/route.ts GET ensureWindowFile": "the same excerpt, served",
+};
+
+test("no GET or HEAD handler under app/api/ writes a manifest (MANIFEST_WRITERS), nor a file but the named caches", () => {
+ const sources = ["manifest.mjs", "snapshots.mjs", "versions.mjs", "takeEdit.mjs", "takes.mjs", "takeManifest.mjs"].map((f) =>
+ fs.readFileSync(path.join(UMTOOL, "lib", "report", f), "utf8"),
+ );
+ for (const w of MANIFEST_WRITERS) {
+ assert.ok(sources.some((src) => new RegExp(`export (?:async )?function ${w}\\b`).test(src)), `${w} is still a writer lib/report exports`);
+ }
+ const found = [];
+ const allowedSeen = new Set();
+ for (const file of routes().map((r) => r.file)) {
+ const src = fs.readFileSync(path.join(UMTOOL, file), "utf8");
+ for (const m of ["GET", "HEAD"]) {
+ const body = handlerSource(src, m);
+ if (!body) continue;
+ for (const w of [...MANIFEST_WRITERS, ...FILE_WRITES]) {
+ if (!new RegExp(`\\b${w}\\(`).test(body)) continue;
+ const key = `${file} ${m} ${w}`;
+ if (!MANIFEST_WRITERS.includes(w) && CACHE_ONLY_GET[key]) allowedSeen.add(key);
+ else found.push(key);
+ }
+ }
+ }
+ assert.deepEqual(found, [], "a read that writes");
+ assert.deepEqual([...allowedSeen].sort(), Object.keys(CACHE_ONLY_GET).sort(), "every cache-only GET writer named is still one (a stale entry is removed)");
+});
diff --git a/umtool/proxy.ts b/umtool/proxy.ts
@@ -1,17 +1,21 @@
import { NextResponse, type NextRequest } from "next/server";
-import { writeRefusal } from "@/lib/report/writeGuard.mjs";
+import { bodyRefusal, writeRefusal } from "@/lib/report/writeGuard.mjs";
// EVERY API WRITE IS REFUSED CROSS-SITE (umtool redesign E4): a POST/PUT/PATCH/DELETE under /api/ from another
// site's page, a sibling site's, or a page whose name is not this machine (DNS rebinding) is answered 403 here, and
// its route handler never runs (Next has already buffered the body, up to proxyClientMaxBodySize: next.config.ts). A
// request no browser sent (curl, the CLI, an agent, the editor's server) passes, and so does every read. The rule is
-// in lib/report/writeGuard.mjs, and its test sweeps every route file that exports a write. The matcher keeps the
+// in lib/report/writeGuard.mjs, and its test sweeps every route file that exports a write. A write declaring a body
+// over the cap is answered 413 with its sentence (bodyRefusal), not handed on cut. The matcher keeps the
// proxy off pages, static assets and the uploads (EXEMPT, which refuse cross-site themselves). It must stay the
// literal GUARD_MATCHER, because a matcher is read at build time and cannot be imported.
export function proxy(request: NextRequest) {
const refused = writeRefusal(request.method, request.nextUrl.pathname, request.headers);
if (refused) return NextResponse.json({ error: refused }, { status: 403, headers: { "cache-control": "no-store" } });
+ // A body over the cap would reach its route cut at it (next.config.ts proxyClientMaxBodySize): said here, 413.
+ const tooBig = bodyRefusal(request.method, request.nextUrl.pathname, request.headers);
+ if (tooBig) return NextResponse.json({ error: tooBig }, { status: 413, headers: { "cache-control": "no-store" } });
return NextResponse.next();
}