Archilyzer · Source

archilyzer

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

commit d4d25eb5d0cd0fb28e45fafdbc4d249b1b9ab757
parent 82f476a0b5505ea7a21fdc3465e8469457941208
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 10 Nov 2026 12:45:53 -0500

umtool: the uploads leave the proxy and refuse cross-site themselves; the proxy's body cap back to 16 MB

Review blocker: for a request the proxy matches, Next tees the body into
two unbackpressured in-memory streams BEFORE the proxy runs (the proxy's,
never read, and the route's) and answers only once the request has ended
(next-server.js runMiddleware, body-streams.js). With a 1 GB cap a
cross-site tab could make umtool buffer 2 GB per request before the 403.

- next.config.ts: proxyClientMaxBodySize 16mb (above the largest JSON a
  page sends, a manifest under 3 MB).
- The three recording uploads (/api/report/voices, /api/report/post-
  narration, .../record) are left out of the matcher by a literal negative
  lookahead (writeGuard.mjs EXEMPT -> GUARD_MATCHER), so they stream whole,
  and each POST refuses cross-site as its first use of the request.
- The sweep: every write is inside the matcher (read as the regex it is),
  or EXEMPT with crossSiteRefusal(request.headers) as the handler's first
  use of the request; `export const { POST } = h` is read too.
- guardedPath judges the path decoded and lower case.
- GETs that write the manifest (post-narration ?id&job, post-item
  ?takeWords and ?job: a job followed to done) refuse cross-site in that
  branch: the proxy passes reads, and an <img> could ask them.
- e2e: a 20 MB recording reaches /api/report/voices whole; each exempt
  route refuses a cross-site text/plain and multipart POST; the GET write
  branch refuses cross-site; the /api/./ case dropped.

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

Diffstat:
Mumtool/app/api/report/post-item/route.ts | 9+++++++++
Mumtool/app/api/report/post-narration/record/route.ts | 4++++
Mumtool/app/api/report/post-narration/route.ts | 8++++++++
Mumtool/app/api/report/voices/route.ts | 4++++
Mumtool/docs/knobs.md | 4+++-
Mumtool/e2e/write-guard.spec.ts | 40++++++++++++++++++++++++++++++++++++----
Mumtool/lib/report/writeGuard.mjs | 27++++++++++++++++++++++-----
Mumtool/lib/report/writeGuard.test.mjs | 47+++++++++++++++++++++++++++++++++++++++++------
Mumtool/next.config.ts | 23+++++++++++++----------
Mumtool/proxy.ts | 13+++++++------
10 files changed, 147 insertions(+), 32 deletions(-)

diff --git a/umtool/app/api/report/post-item/route.ts b/umtool/app/api/report/post-item/route.ts @@ -18,6 +18,7 @@ import { recognizedOf, takeWordSources, wordsFileOf } from "@/lib/report/postFxC import { rangeResponse, resolveReport } from "@/lib/report/serve.mjs"; import { resolveTakeManifest } from "@/lib/report/takeManifest.mjs"; import { refuseCaller } from "@/lib/report/caller"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; import { withTakeScope } from "@/lib/report/takeScope.mjs"; import { isTakeId } from "@/lib/report/takes.mjs"; import { projectRedaction } from "@/lib/report/postRedaction.mjs"; @@ -187,6 +188,10 @@ export async function GET(request: Request) { const tw = q.get("takeWords"); if (tw) { + // A GET that WRITES the manifest (a job followed to done): the proxy passes reads, so an <img> on another site + // could ask it; refused cross-site here (lib/report/sameOrigin.mjs). + const cross = crossSiteRefusal(request.headers); + if (cross) return Response.json({ error: cross }, { status: 403 }); const jobs = tw.split(",").filter(Boolean); const take = pickedTake(found.item) as (Record<string, unknown> & { file: string; index: number; script?: string; parts?: unknown[] }) | null; if (!take) return Response.json({ state: "failed", error: `${id} has no take` }, { status: 404 }); @@ -215,6 +220,10 @@ export async function GET(request: Request) { const job = q.get("job"); if (job) { + // A GET that WRITES the manifest (a job followed to done): the proxy passes reads, so an <img> on another site + // could ask it; refused cross-site here (lib/report/sameOrigin.mjs). + const cross = crossSiteRefusal(request.headers); + if (cross) return Response.json({ error: cross }, { status: 403 }); const i = Number(q.get("media")); const m = found.item.media?.[i]; if (!m || typeof m.src !== "string") return Response.json({ error: `no attachment ${q.get("media")}` }, { status: 404 }); diff --git a/umtool/app/api/report/post-narration/record/route.ts b/umtool/app/api/report/post-narration/record/route.ts @@ -1,6 +1,7 @@ import { readFile, stat } from "node:fs/promises"; import { resolveReport } from "@/lib/report/serve.mjs"; import { refuseCaller } from "@/lib/report/caller"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; import { StaleToken, StructureRefused } from "@/lib/report/manifest.mjs"; import { discardPart, finishSession, partFile, readSession, savePart } from "@/lib/report/recordSession.mjs"; @@ -55,6 +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. + const cross = crossSiteRefusal(request.headers); + if (cross) return Response.json({ error: cross }, { status: 403 }); const refused = refuseCaller(request, "/api/report/post-narration/record"); if (refused) return refused; if ((request.headers.get("content-type") ?? "").startsWith("multipart/form-data")) { diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts @@ -10,6 +10,7 @@ import { StaleToken, StructureRefused, fitPostItems, manifestToken, undoStructur import { resolveReport } from "@/lib/report/serve.mjs"; import { readManifest } from "@/lib/projects/report.mjs"; import { refuseCaller } from "@/lib/report/caller"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; import { deleteTake, measureTake } from "@/lib/report/postNarrationCli.mjs"; import { parseTempoSpec, rereadTake } from "@/lib/report/postReread.mjs"; import { parsePauseSpec, pauseTake } from "@/lib/report/postPause.mjs"; @@ -77,6 +78,10 @@ export async function GET(request: Request) { const id = q.get("id"); const job = q.get("job"); if (id && job) { + // A GET that WRITES the manifest (a job followed to done): the proxy passes reads, so an <img> on another site + // could ask it; refused cross-site here (lib/report/sameOrigin.mjs). + const cross = crossSiteRefusal(request.headers); + if (cross) return Response.json({ error: cross }, { status: 403 }); const e = postsOf(m).find((x) => x.id === id); if (!e) return Response.json({ error: `no post item ${id}` }, { status: 404 }); const rel = q.get("file") ?? ""; @@ -161,6 +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. + 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); const text = await request.text(); let parsed: Record<string, unknown> | null = null; diff --git a/umtool/app/api/report/voices/route.ts b/umtool/app/api/report/voices/route.ts @@ -5,6 +5,7 @@ import { listTtsEngines } from "yt-dlp-transcript-common/lib/ttsApps"; import { getJob, jobView, runningJob, startJob } from "@/lib/jobs"; import { projectRef } from "@/lib/projects"; import { refuseCaller } from "@/lib/report/caller"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; import { castCommand } from "@/lib/report/castCli.mjs"; import { auditionSteps, auditionView, referenceFor, AUDITION_MAX } from "@/lib/report/castAudition.mjs"; import { castForProject } from "@/lib/report/castStore.mjs"; @@ -98,6 +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. + const cross = crossSiteRefusal(request.headers); + if (cross) return Response.json({ error: cross }, { status: 403 }); const refused = refuseCaller(request, "/api/report/voices"); if (refused) return refused; const multipart = (request.headers.get("content-type") ?? "").startsWith("multipart/"); diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -1876,7 +1876,9 @@ What a form may name, and what it asks first: under `/api/` (`lib/report/writeGuard.mjs`): a request a browser sent -- it carries an `Origin` or a `Sec-Fetch-Site` -- is answered 403 `{error}` when it comes from another site, a sibling site (the editor's page on :3001 is one) or an opaque origin, or when its Host, X-Forwarded-Host or Origin is not this machine, by the same - rule as above. A request no browser sent (curl, the CLI, an agent, the editor's server with its Bearer) and every + rule as above. The recording uploads (`/api/report/voices`, `/api/report/post-narration`, `…/record`) are outside + the proxy, so their bodies stream to the route whole, and each refuses the same way itself, before it reads the body. + A request no browser sent (curl, the CLI, an agent, the editor's server with its Bearer) and every read pass; who may write is still the Bearer rule. Serving umtool under another name (a reverse proxy, a LAN name, a tailnet name) needs that name in `UMTOOL_ALLOWED_HOSTS`, or the app's own pages cannot save anything. - **Runs.** What a form started stays under **Runs** in the palette (nothing typed) for the page's life: an Escape diff --git a/umtool/e2e/write-guard.spec.ts b/umtool/e2e/write-guard.spec.ts @@ -24,12 +24,12 @@ test("another site's write is refused by the proxy; a terminal's, a read and the expect(r.status(), method).toBe(403); } // DNS rebinding: the page's own origin, but a name that is not this machine. - r =await request.post("/api/projects/new", { data: "{}", headers: { ...plain, origin: "http://rebind.example", "x-forwarded-host": "rebind.example", "sec-fetch-site": "same-origin" } }); + r = await request.post("/api/projects/new", { data: "{}", headers: { ...plain, origin: "http://rebind.example", "x-forwarded-host": "rebind.example", "sec-fetch-site": "same-origin" } }); expect(r.status()).toBe(403); expect(await said(r)).toContain("UMTOOL_ALLOWED_HOSTS"); // Another spelling of the path never reaches the route unjudged. - for (const p of ["/%61pi/projects/new", "/api/projects/new/", "/api//projects/new", "/api/projects/%6eew", "/api/./projects/new"]) { + for (const p of ["/%61pi/projects/new", "/api/projects/new/", "/api//projects/new", "/api/projects/%6eew"]) { r = await request.post(p, { data: "{}", headers: { ...plain, origin: "https://evil.example" }, maxRedirects: 0 }); expect([403, 404, 307, 308], `${p}: ${r.status()} ${await r.text()}`).toContain(r.status()); } @@ -38,8 +38,8 @@ 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: "{}", headers: plain }); expect(r.status()).toBe(400); expect(await said(r)).toContain("unknown kind"); - // A body over Next's 10 MB proxy default arrives whole (next.config.ts, proxyClientMaxBodySize): cut, it would - // not parse ("bad json"). + // A JSON body over Next's 10 MB default and under the proxy's cap (16 MB, next.config.ts proxyClientMaxBodySize) + // arrives whole through the proxy: cut, it would not parse ("bad json"). 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"); @@ -56,3 +56,35 @@ test("another site's write is refused by the proxy; a terminal's, a read and the expect(fromPage.status).toBe(400); expect(fromPage.body.error).toContain("unknown kind"); }); + +// THE UPLOADS ARE OUTSIDE THE PROXY (writeGuard.mjs EXEMPT): a body the proxy matches is held in memory and cut at its +// cap, so a recording's routes are left out of the matcher and refuse another site themselves, before the body. +const EXEMPT = ["/api/report/voices", "/api/report/post-narration", "/api/report/post-narration/record"]; +const NO_PROJECT = "reports/no-such-project"; + +test("the upload routes are outside the proxy: another site is refused by the route itself, and a 20 MB recording arrives whole", async ({ request }) => { + for (const p of EXEMPT) { + let r = await request.post(p, { data: "{}", headers: { "content-type": "text/plain", origin: "https://evil.example" } }); + expect(r.status(), p).toBe(403); + expect(await said(r), p).toContain("evil.example"); + // The attack's own shape: a multipart form, which no browser preflights either. + r = await request.post(p, { multipart: { project: NO_PROJECT, part: { name: "p1.webm", mimeType: "audio/webm", buffer: Buffer.alloc(1024) } }, headers: { "sec-fetch-site": "cross-site" } }); + expect(r.status(), `${p} multipart`).toBe(403); + } + // 20 MB, over the proxy's 16 MB cap: through the proxy it would reach the route cut, and not parse ("bad form"). + const big = Buffer.alloc(20 * 1024 * 1024, 1); + const r = await request.post("/api/report/voices", { + multipart: { project: NO_PROJECT, op: "recording", item: "x", file: { name: "take.wav", mimeType: "audio/wav", buffer: big } }, + }); + expect(r.status()).toBe(404); + expect(await said(r)).toContain("no such project"); +}); + +test("a GET that writes the manifest (a TTS job followed to done) is refused cross-site; the page's own poll is not", async ({ request }) => { + const q = `/api/report/post-narration?project=${encodeURIComponent("reports/post-narration-fixture")}&id=no-such-post&job=no-such-job&file=x`; + let r = await request.get(q, { headers: { "sec-fetch-site": "cross-site" } }); + expect(r.status()).toBe(403); + r = await request.get(q, { headers: { "sec-fetch-site": "same-origin" } }); + expect(r.status()).toBe(404); + expect(await said(r)).toContain("no post item"); +}); diff --git a/umtool/lib/report/writeGuard.mjs b/umtool/lib/report/writeGuard.mjs @@ -2,8 +2,8 @@ // only when it called crossSiteRefusal itself, and on 10 Nov about 80 of the 141 route files that export a write // did not: a page on any site the operator has open could send a `text/plain` POST (no preflight; the routes read // `request.json()` whatever the type) to localhost:3050 and create or delete projects, start renders, write -// manifests. `umtool/proxy.ts` now asks `writeRefusal` before ANY write under /api/ reaches its handler; the -// per-route calls stay (belt and braces). The proxy's matcher is GUARD_MATCHER, and writeGuard.test.mjs sweeps every +// manifests. `umtool/proxy.ts` now asks `writeRefusal` before any write under /api/ reaches its handler (EXEMPT's +// uploads aside, which refuse cross-site themselves); the per-route calls stay (belt and braces). The proxy's matcher is GUARD_MATCHER, and writeGuard.test.mjs sweeps every // app/**/route.ts that exports a write and checks the proxy covers it. // // WHO IS ASKED. Only a request a browser sent: a browser puts `Origin` on every write (the Fetch standard appends it @@ -18,8 +18,18 @@ import { crossSiteRefusal } from "./sameOrigin.mjs"; -/** The proxy's matcher (umtool/proxy.ts must say exactly this; the sweep test checks). */ -export const GUARD_MATCHER = "/api/:path*"; +// 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). +export const EXEMPT = ["/api/report/voices", "/api/report/post-narration", "/api/report/post-narration/record"]; + +/** + * 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). + */ +export const GUARD_MATCHER = `/api/((?!${EXEMPT.map((p) => `${p.slice("/api/".length)}$`).join("|")}).*)`; const READS = new Set(["GET", "HEAD", "OPTIONS"]); @@ -27,7 +37,14 @@ const READS = new Set(["GET", "HEAD", "OPTIONS"]); export function guardedPath(method, pathname) { const m = String(method ?? "").toUpperCase(); if (READS.has(m)) return false; - const p = String(pathname ?? ""); + // Judged as decoded and lower case, so `/%61pi/…` or `/API/…` is a write too, whatever Next routes it to. + let p = String(pathname ?? ""); + try { + p = decodeURIComponent(p); + } catch { + /* undecodable: judged as sent */ + } + p = p.toLowerCase(); return p === "/api" || p.startsWith("/api/"); } 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 { GUARD_MATCHER, guardedPath, writeRefusal } from "./writeGuard.mjs"; +import { EXEMPT, GUARD_MATCHER, guardedPath, writeRefusal } from "./writeGuard.mjs"; const UMTOOL = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); const APP = path.join(UMTOOL, "app"); @@ -47,6 +47,9 @@ test("guardedPath: writes under /api/ only", () => { assert.equal(guardedPath("GET", "/api/cli"), false); assert.equal(guardedPath("POST", "/apix"), false); assert.equal(guardedPath("POST", "/reports/x"), false); + assert.equal(guardedPath("POST", "/%61pi/projects/new"), true, "an encoded spelling"); + assert.equal(guardedPath("POST", "/API/projects/new"), true, "another case"); + assert.equal(guardedPath("POST", "/api/%E0%A4%A"), true, "undecodable, judged as sent"); }); /** Every route.ts under app/, as [file, url, write methods]. */ @@ -64,6 +67,9 @@ function routes() { const src = fs.readFileSync(file, "utf8"); const methods = new Set(); for (const m of src.matchAll(/export\s+(?:async\s+)?(?:function\s*\*?|const|let|var)\s+(POST|PUT|PATCH|DELETE)\b/g)) methods.add(m[1]); + for (const m of src.matchAll(/export\s+(?:const|let|var)\s*\{([^}]*)\}\s*=/g)) { + for (const w of m[1].matchAll(/\b(POST|PUT|PATCH|DELETE)\b/g)) methods.add(w[1]); // export const { POST } = h + } for (const m of src.matchAll(/export\s*\{([^}]*)\}/g)) { for (const w of m[1].matchAll(/\b(POST|PUT|PATCH|DELETE)\b/g)) methods.add(w[1]); } @@ -75,11 +81,18 @@ function routes() { }); } -/** Next's matcher for the one pattern the proxy uses: `/<prefix>/:path*` matches the prefix and anything below. */ +/** Next's matcher, as the regular expression its source is (a `/…((?!…).*)` pattern has no named parameters). */ function matcherCovers(matcher, url) { - const m = /^(\/[^:]*?)\/:path\*$/.exec(matcher); - assert.ok(m, `the sweep understands only "/<prefix>/:path*", not ${matcher}`); - return url === m[1] || url.startsWith(m[1] + "/"); + assert.ok(!/:/.test(matcher), `the sweep reads a matcher as a plain regular expression, not ${matcher}`); + return new RegExp(`^${matcher}$`).test(url); +} + +/** A handler's source: from `export … function <M>(` to the next top-level export. */ +function handlerSource(src, method) { + const at = src.search(new RegExp(`export\\s+(?:async\\s+)?function\\s+${method}\\s*\\(`)); + if (at < 0) return null; + const next = src.slice(at + 1).search(/\nexport\s/); + return next < 0 ? src.slice(at) : src.slice(at, at + 1 + next); } test("every route that exports a write is behind the proxy", () => { @@ -87,6 +100,10 @@ test("every route that exports a write is behind the proxy", () => { const said = /matcher:\s*(["'])([^"']+)\1/.exec(proxySrc); assert.ok(said, "proxy.ts names a literal matcher"); assert.equal(said[2], GUARD_MATCHER, "proxy.ts's matcher is GUARD_MATCHER"); + for (const p of ["/api/cli", "/api/projects/new", "/api/report/voices/x", "/api/report/post-narration/other", "/api/report/voicesx"]) { + assert.ok(matcherCovers(GUARD_MATCHER, p), `the matcher covers ${p}`); + } + 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.ok(!fs.existsSync(path.join(UMTOOL, "middleware.ts")), "no middleware.ts beside proxy.ts"); @@ -95,10 +112,28 @@ test("every route that exports a write is behind the proxy", () => { const writers = all.filter((r) => r.methods.length); assert.ok(writers.length >= 140, `the sweep found ${writers.length} write routes: too few, so the walk is wrong`); const uncovered = []; + const exempt = []; for (const r of writers) { for (const m of r.methods) { - if (!matcherCovers(GUARD_MATCHER, r.url) || !guardedPath(m, r.url)) uncovered.push(`${m} ${r.url} (${r.file})`); + if (!guardedPath(m, r.url)) uncovered.push(`${m} ${r.url} (${r.file}): not a guarded path`); + else if (matcherCovers(GUARD_MATCHER, r.url)) continue; + else if (!EXEMPT.includes(r.url)) uncovered.push(`${m} ${r.url} (${r.file}): outside the matcher and not EXEMPT`); + else { + // An exempt write refuses cross-site itself, as the FIRST use of its request: before any body read. + exempt.push(`${m} ${r.url}`); + const src = handlerSource(fs.readFileSync(path.join(UMTOOL, r.file), "utf8"), m); + if (!src) { + uncovered.push(`${m} ${r.url} (${r.file}): exempt, but not a plain \`export async function ${m}\` the sweep can read`); + continue; + } + const body = src.slice(src.indexOf("{")); + const firstUse = body.search(/\brequest\b/); + if (firstUse < 0 || !body.slice(firstUse).startsWith("request.headers") || !/crossSiteRefusal\(\s*$/.test(body.slice(0, firstUse))) { + uncovered.push(`${m} ${r.url} (${r.file}): exempt, but its first use of the request is not crossSiteRefusal(request.headers)`); + } + } } } 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"); }); diff --git a/umtool/next.config.ts b/umtool/next.config.ts @@ -19,16 +19,19 @@ const nextConfig: NextConfig = { // fail the whole module graph. Every page importing lib/projects then 500s // with "Can't resolve 'cbor-x'", which names a package nothing here uses. serverExternalPackages: ["lmdb"], - // THE PROXY READS EVERY API WRITE'S BODY FIRST (proxy.ts, the cross-site - // guard). With a proxy, Next clones a non-GET request's body for it and hands - // the route that clone -- cut at proxyClientMaxBodySize, 10 MB by default, - // with only a console warning: an upload over it reached its route - // truncated. A recording uploaded from a page (post narration, its parts up - // to 200 MB each, several in one body; a voice's recording; "keep my - // recording") is bigger than that, so the cap is far above any of them. The - // body was held whole in memory before too (`request.formData()`). - // e2e/write-guard.spec.ts sends one over 10 MB and checks it arrives whole. - experimental: { proxyClientMaxBodySize: "1gb" }, + // WHAT THE PROXY COSTS A WRITE'S BODY (proxy.ts, the cross-site guard). For + // a request the proxy matches, Next tees the body into two in-memory + // streams before the proxy runs (next/dist/server/body-streams.js): one is + // the proxy's, which it never reads, and one is the route's. Neither applies + // backpressure, and the response waits for the request to end. So a matched + // body is held twice in memory, even one the proxy refuses, and the route + // gets a copy cut off at this cap. The cap therefore stays SMALL, above the + // largest JSON body a page sends (a manifest, under 3 MB on 10 Nov), so a + // cross-site tab cannot buffer gigabytes. The uploads (a recording, parts up + // to 200 MB) are outside the matcher (lib/report/writeGuard.mjs, EXEMPT), + // so they stream to their route whole, and each refuses cross-site itself. + // e2e/write-guard.spec.ts sends one over the cap and checks it arrives whole. + experimental: { proxyClientMaxBodySize: "16mb" }, // The dev indicator defaults to the bottom-left corner, which is the rail's // foot -- it sat over the theme control on the e2e dev server. (The live // umtool runs `next start`, which shows no indicator.) diff --git a/umtool/proxy.ts b/umtool/proxy.ts @@ -2,11 +2,12 @@ import { NextResponse, type NextRequest } from "next/server"; import { 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, -// before its handler reads a byte. A request no browser sent (curl, the CLI, an agent, the editor's server) passes; -// so does every read. The rule is lib/report/writeGuard.mjs; its test sweeps every route file that exports a write. -// The matcher keeps the proxy off pages and static assets; it must stay the literal GUARD_MATCHER (a matcher is read -// at build time, so it cannot be imported). +// 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 +// 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); @@ -15,5 +16,5 @@ export function proxy(request: NextRequest) { } export const config = { - matcher: "/api/:path*", + matcher: "/api/((?!report/voices$|report/post-narration$|report/post-narration/record$).*)", };