Archilyzer · Source

archilyzer

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

commit 02a2f04fb73508ea5745e03258118bc936fbeef3
parent a4391ba7a74194d97d1492fc845d16dcc2baaf7c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 10 Nov 2026 11:02:02 -0500

umtool: one cross-site guard in front of every API write -- umtool/proxy.ts

A route that writes refused another site's page only when it called
crossSiteRefusal itself, and 130 of the 141 route files exporting a
POST/PUT/PATCH/DELETE did not: a text/plain POST from any open page could
create or delete projects, start renders, write manifests.

umtool/proxy.ts (Next 16's proxy, Node runtime, matcher /api/:path*) asks
lib/report/writeGuard.mjs before any write under /api/ reaches its handler.
A request a browser sent (Origin or Sec-Fetch-Site) is judged by
crossSiteRefusal in full -- another site, a sibling site, an opaque origin,
a Host / X-Forwarded-Host / Origin that is not this machine -- and answered
403 {error}. A request no browser sent passes: its Host is its own, and
refusing it would refuse the editor in docker (http://umtool:3050) and a
LAN agent; who may write stays the Bearer rule. Reads pass. The per-route
calls stay.

writeGuard.test.mjs: the decision, and a sweep of every app/**/route.ts
exporting a write (141 files, 143 handlers), each covered by the proxy's
literal matcher. e2e/write-guard.spec.ts: the proxy under next start.
Docs: knobs.md (the ⌘K section), RUNNING_IN_DOCKER.md.

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

Diffstat:
MRUNNING_IN_DOCKER.md | 6+++---
Mumtool/docs/knobs.md | 7+++++++
Aumtool/e2e/write-guard.spec.ts | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/writeGuard.mjs | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/writeGuard.test.mjs | 104+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/proxy.ts | 19+++++++++++++++++++
6 files changed, 236 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/docs/knobs.md b/umtool/docs/knobs.md @@ -1841,6 +1841,13 @@ 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. 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,53 @@ +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", "/api/./projects/new"]) { + 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 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"); +}); diff --git a/umtool/lib/report/writeGuard.mjs b/umtool/lib/report/writeGuard.mjs @@ -0,0 +1,50 @@ +// 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; 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 proxy's matcher (umtool/proxy.ts must say exactly this; the sweep test checks). */ +export const GUARD_MATCHER = "/api/:path*"; + +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; + const p = String(pathname ?? ""); + 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,104 @@ +// 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 { 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); +}); + +/** 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*\{([^}]*)\}/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 for the one pattern the proxy uses: `/<prefix>/:path*` matches the prefix and anything below. */ +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] + "/"); +} + +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"); + 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 = []; + 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})`); + } + } + assert.deepEqual(uncovered, [], "a write the proxy does not guard"); +}); diff --git a/umtool/proxy.ts b/umtool/proxy.ts @@ -0,0 +1,19 @@ +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). + +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/:path*", +};