Archilyzer · Source

archilyzer

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

commit 18c82af1500d8fb94d510d414259e76a8e8a5daa
parent 0c677c785250a3f8b1db04163bcfad1277e80cf2
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 10 Nov 2026 12:57:32 -0500

Merge lane/write-guard: every umtool API write refuses another site's page -- one guard in umtool/proxy.ts in front of all 141 write routes (130 had none), the three recording uploads guarding themselves, and the GETs that wrote a manifest (overnight E4, found in L4's security review)

- umtool/proxy.ts on /api/*: a POST/PUT/PATCH/DELETE carrying Origin or Sec-Fetch-Site goes through crossSiteRefusal (another site, an opaque origin, a rebound Host -> 403); the CLI, agents and the editor's server pass as before
- proxyClientMaxBodySize 16mb: Next tees a body twice before the proxy runs, so a large cap let a refused cross-site request be buffered twice (review blocker, fixed)
- report/voices, report/post-narration and report/post-narration/record stay outside the proxy and call crossSiteRefusal before reading a byte
- post-narration GET ?id&job and post-item GET ?takeWords / ?job (they write the manifest) refuse cross-site
- writeGuard.test.mjs sweeps every app/**/route.ts write: inside the matcher, or EXEMPT with the check first; e2e/write-guard.spec.ts on the real proxy
- serving umtool under another name needs that name in UMTOOL_ALLOWED_HOSTS (docs/knobs.md, RUNNING_IN_DOCKER.md)

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

Diffstat:
MRUNNING_IN_DOCKER.md | 6+++---
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 | 9+++++++++
Aumtool/e2e/write-guard.spec.ts | 90+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/writeGuard.mjs | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/writeGuard.test.mjs | 139+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/next.config.ts | 13+++++++++++++
Aumtool/proxy.ts | 20++++++++++++++++++++
11 files changed, 366 insertions(+), 3 deletions(-)

diff --git a/RUNNING_IN_DOCKER.md b/RUNNING_IN_DOCKER.md @@ -224,9 +224,9 @@ of a YAML config file and a mandatory database. Templates are in Both attach through Caddy's `forward_auth`. The overlays set `ARCHILYZER_AUTH_MODE=forward` for you. -**umtool answers writes only to the names it knows.** Its pages' writes -- -Save version and Open in draft, an ingredient's actions, every ⌘K command -(`POST /api/cli`) -- are refused when the address the browser used is not +**umtool answers writes only to the names it knows.** Every write its pages +make (any POST/PUT/PATCH/DELETE under `/api/`: saving a knob, Save version, an +ingredient's action, every ⌘K command) is refused when the address the browser used is not this machine (`localhost`, `*.localhost`, `127.x`, `::1`): a page whose DNS name is re-pointed at the box (DNS rebinding) must not drive it. Caddy passes the address on, so reaching umtool as `http://192.168.1.20:8083`, a custom 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 @@ -1872,6 +1872,15 @@ What a form may name, and what it asks first: rebinding) cannot drive it. `UMTOOL_ALLOWED_HOSTS=name,name` (host names, no ports) adds the names a proxy in front of umtool serves it as. `POST /api/cli` also refuses a request with no Origin and no `Sec-Fetch-Site` (a terminal runs the command itself). +- **Every API write is refused cross-site.** `umtool/proxy.ts` stands in front of every POST/PUT/PATCH/DELETE + 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. 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 mid-run loses nothing. The same queued command sent twice within 5 s is the one step. diff --git a/umtool/e2e/write-guard.spec.ts b/umtool/e2e/write-guard.spec.ts @@ -0,0 +1,90 @@ +import { test, expect } from "@playwright/test"; +import * as urls from "./urls"; + +// EVERY API WRITE IS REFUSED CROSS-SITE (umtool/proxy.ts, lib/report/writeGuard.mjs): the proxy, under the server +// the suite runs (`next start` by default), answers another site's write 403 before the route reads its body -- +// here on /api/projects/new, a route with no per-route check of its own. `{}` names no kind, so a write that does +// get through is refused by the route (400) and writes nothing. + +const said = async (r: { json(): Promise<unknown> }) => ((await r.json()) as { error?: string }).error ?? ""; + +test("another site's write is refused by the proxy; a terminal's, a read and the app's own page are not", async ({ page, request }) => { + // A text/plain POST, the kind no browser preflights. + const plain = { "content-type": "text/plain" }; + let r = await request.post("/api/projects/new", { data: "{}", headers: { ...plain, origin: "https://evil.example" } }); + expect(r.status()).toBe(403); + expect(await said(r)).toContain("evil.example"); + r = await request.post("/api/projects/new", { data: "{}", headers: { ...plain, "sec-fetch-site": "cross-site" } }); + expect(r.status()).toBe(403); + expect(await said(r)).toContain("cross-site"); + r = await request.post("/api/projects/new", { data: "{}", headers: { ...plain, "sec-fetch-site": "same-site", origin: "http://localhost:3001" } }); + expect(r.status(), "the editor's page").toBe(403); + for (const method of ["put", "patch", "delete"] as const) { + r = await request[method]("/api/projects/new", { data: "{}", headers: { ...plain, origin: "https://evil.example" } }); + 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" } }); + 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"]) { + 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()); + } + + // A terminal (no Origin, no Sec-Fetch-Site): the route answers. + r = await request.post("/api/projects/new", { data: "{}", headers: plain }); + expect(r.status()).toBe(400); + expect(await said(r)).toContain("unknown kind"); + // 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"); + // 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); + + // The app's own page: a real browser's same-origin write carries Origin and Sec-Fetch-Site, and passes. + await page.goto(urls.homeHref()); + const fromPage = await page.evaluate(async () => { + const res = await fetch("/api/projects/new", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" }); + return { status: res.status, body: (await res.json()) as { error?: string } }; + }); + 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 @@ -0,0 +1,67 @@ +// ONE GUARD IN FRONT OF EVERY WRITE (umtool redesign E4). A route that writes used to refuse another site's page +// 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 (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 +// to any method but GET/HEAD) and `Sec-Fetch-Site` on every request, and a page can set neither. One carrying +// either is judged by crossSiteRefusal in full -- another site, a sibling site (the editor's page on :3001), an +// opaque origin, and a Host / X-Forwarded-Host / Origin that is not this machine (DNS rebinding) are refused. A +// request with NEITHER (curl, the CLI, an agent, the editor's server with its Bearer) passes here: who may write is +// lib/report/caller.ts's business, and its Host is whatever it chose to send, so checking it protects nothing -- +// while refusing it would refuse the editor in docker (`UMTOOL_URL=http://umtool:3050`) and an agent on the LAN. +// +// Plain ESM so `node --test` reads it. + +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). +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"]); + +/** Whether a request is a write the guard judges: any method but GET/HEAD/OPTIONS, to /api or below. */ +export function guardedPath(method, pathname) { + const m = String(method ?? "").toUpperCase(); + if (READS.has(m)) return false; + // 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/"); +} + +/** Whether a request carries what only a browser sends (and a page cannot forge). */ +export function fromBrowser(headers) { + return Boolean((headers.get("origin") ?? "").trim() || (headers.get("sec-fetch-site") ?? "").trim()); +} + +/** + * The sentence to refuse a request with (403), or null to let it through. + * @param {string} method + * @param {string} pathname + * @param {{ get(name: string): string | null }} headers + * @param {Record<string, string | undefined>} [env] + */ +export function writeRefusal(method, pathname, headers, env = process.env) { + if (!guardedPath(method, pathname)) return null; + if (!fromBrowser(headers)) return null; + return crossSiteRefusal(headers, env); +} diff --git a/umtool/lib/report/writeGuard.test.mjs b/umtool/lib/report/writeGuard.test.mjs @@ -0,0 +1,139 @@ +// Every API write is refused cross-site (writeGuard.mjs, umtool/proxy.ts): the proxy's decision, and a sweep of +// every route file that exports a write, each of which the proxy must cover. +import assert from "node:assert/strict"; +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"; + +const UMTOOL = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); +const APP = path.join(UMTOOL, "app"); +const h = (o) => ({ get: (k) => o[k.toLowerCase()] ?? null }); +const NO_ENV = {}; + +test("writeRefusal: another site's, a sibling site's and a rebound page's writes are refused; the app's own, a non-browser's and every read pass", () => { + const post = (headers, env = NO_ENV, p = "/api/projects/new") => writeRefusal("POST", p, h(headers), env); + // Refused. + assert.match(String(post({ origin: "https://evil.example", host: "localhost:3050" })), /evil\.example/, "a cross-site Origin"); + assert.match(String(post({ origin: "https://evil.example", host: "localhost:3050", "sec-fetch-site": "cross-site" })), /cross-site/); + assert.match(String(post({ "sec-fetch-site": "cross-site", host: "localhost:3050" })), /cross-site/, "Sec-Fetch-Site: cross-site, no Origin"); + assert.match(String(post({ "sec-fetch-site": "same-site", origin: "http://localhost:3001", host: "localhost:3050" })), /same-site/, "the editor's page"); + assert.match(String(post({ origin: "http://evil.example:3050", host: "evil.example:3050", "sec-fetch-site": "same-origin" })), /UMTOOL_ALLOWED_HOSTS/, "Host: evil.example (DNS rebinding)"); + assert.match(String(post({ origin: "http://localhost:3050", host: "localhost:3050", "x-forwarded-host": "rebind.example:3050" })), /rebind\.example/, "a rebound X-Forwarded-Host"); + assert.match(String(post({ origin: "null", host: "localhost:3050" })), /opaque/); + for (const m of ["PUT", "PATCH", "DELETE", "post"]) { + assert.ok(writeRefusal(m, "/api/report/manifest", h({ origin: "https://evil.example", host: "localhost:3050" }), NO_ENV), m); + } + // Pass. + assert.equal(post({ origin: "http://localhost:3050", host: "localhost:3050", "sec-fetch-site": "same-origin" }), null, "the app's own page"); + assert.equal(post({ origin: "http://127.0.0.1:3050", host: "127.0.0.1:3050" }), null, "by address"); + assert.equal(post({ host: "localhost:3050" }), null, "curl, the CLI"); + assert.equal(post({ host: "localhost:3050", authorization: "Bearer t" }), null, "an agent with its Bearer"); + assert.equal(post({ host: "umtool:3050", authorization: "Bearer t" }), null, "the editor's server in docker (UMTOOL_URL=http://umtool:3050)"); + assert.equal(post({ host: "box.lan:3050" }), null, "a terminal on the LAN: no browser, its Host is its own"); + assert.equal(post({ origin: "https://umtool.lan", host: "umtool.lan", "sec-fetch-site": "same-origin" }, { UMTOOL_ALLOWED_HOSTS: "umtool.lan" }), null, "a listed host"); + assert.ok(post({ origin: "https://umtool.lan", host: "umtool.lan", "sec-fetch-site": "same-origin" }), "the same, unlisted"); + for (const m of ["GET", "HEAD", "OPTIONS", "get"]) { + assert.equal(writeRefusal(m, "/api/projects/new", h({ origin: "https://evil.example", "sec-fetch-site": "cross-site", host: "evil.example" }), NO_ENV), null, `${m} from anywhere`); + } + assert.equal(post({ origin: "https://evil.example", host: "localhost:3050" }, NO_ENV, "/projects"), null, "not under /api/"); +}); + +test("guardedPath: writes under /api/ only", () => { + assert.equal(guardedPath("POST", "/api"), true); + assert.equal(guardedPath("POST", "/api/cli"), true); + assert.equal(guardedPath("DELETE", "/api/a/b/c"), true); + 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]. */ +function routes() { + const out = []; + const walk = (dir) => { + for (const e of fs.readdirSync(dir, { withFileTypes: true })) { + const p = path.join(dir, e.name); + if (e.isDirectory()) walk(p); + else if (/^route\.(ts|tsx|js|mjs)$/.test(e.name)) out.push(p); + } + }; + walk(APP); + return out.map((file) => { + 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]); + } + if (/export\s+\*\s+from/.test(src)) methods.add("POST"); // a re-export may carry a write: count it as one + const segs = path.relative(APP, path.dirname(file)).split(path.sep).filter(Boolean) + .filter((s) => !/^\(.*\)$/.test(s) && !s.startsWith("@")) + .map((s) => (/^\[\[?\.\.\./.test(s) ? "a/b" : /^\[.*\]$/.test(s) ? "x" : s)); + return { file: path.relative(UMTOOL, file), url: "/" + segs.join("/"), methods: [...methods] }; + }); +} + +/** Next's matcher, as the regular expression its source is (a `/…((?!…).*)` pattern has no named parameters). */ +function matcherCovers(matcher, url) { + 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", () => { + const proxySrc = fs.readFileSync(path.join(UMTOOL, "proxy.ts"), "utf8"); + 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"); + + const all = routes(); + 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 (!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,6 +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"], + // 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 @@ -0,0 +1,20 @@ +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, 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); + if (refused) return NextResponse.json({ error: refused }, { status: 403, headers: { "cache-control": "no-store" } }); + return NextResponse.next(); +} + +export const config = { + matcher: "/api/((?!report/voices$|report/post-narration$|report/post-narration/record$).*)", +};