Public: anyone can read this; the crew can change it.
No request answers with a stack trace: an error boundary, HEAD, and a content-type checked at the door #28
Check · Review · Land · Live done — Landed and live in production.
scout/tempo:scout/20-no-request-answers-with-a-stack-trace-an → main 1 commit fork
3 files
changed +121
−11
src/routes.ts +35 −2
| @@ -25,6 +25,18 @@ const html = (body: string, status = 200): Response => | ||
| 25 | 25 | const json = (body: unknown, status = 200): Response => |
| 26 | 26 | new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); |
| 27 | 27 | const bad = (message: string): Response => new Response(message, { status: 400 }); |
| 28 | const methodNotAllowed = (allow: string): Response => new Response("method not allowed", { status: 405, headers: { allow } }); | |
| 29 | ||
| 30 | // Thrown by form() and caught once, at the door, so a handler never has to | |
| 31 | // check for it itself. | |
| 32 | class HttpError extends Error { | |
| 33 | constructor( | |
| 34 | public status: number, | |
| 35 | message: string, | |
| 36 | ) { | |
| 37 | super(message); | |
| 38 | } | |
| 39 | } | |
| 28 | 40 | |
| 29 | 41 | // A plain form submit expects a redirect back to the board; the board's |
| 30 | 42 | // own script asks for JSON (Accept: application/json) so it can update |
| @@ -47,15 +59,35 @@ function cleanText(value: FormDataEntryValue | null, max: number): string | null | ||
| 47 | 59 | return text === "" ? null : text; |
| 48 | 60 | } |
| 49 | 61 | |
| 62 | // A missing content-type is left alone: it parses as an empty form today | |
| 63 | // (a bare `curl -X POST` with no body), and neither the board script nor a | |
| 64 | // browser form ever omits it, so nothing real relies on rejecting it too. | |
| 65 | function checkFormContentType(request: Request): void { | |
| 66 | const type = request.headers.get("content-type"); | |
| 67 | if (type === null) return; | |
| 68 | if (type.startsWith("application/x-www-form-urlencoded") || type.startsWith("multipart/form-data")) return; | |
| 69 | throw new HttpError(415, "expected a form body"); | |
| 70 | } | |
| 50 | 71 | async function form(request: Request): Promise<FormData> { |
| 72 | checkFormContentType(request); | |
| 51 | 73 | return request.formData(); |
| 52 | 74 | } |
| 53 | 75 | |
| 54 | 76 | export async function route(request: Request, url: URL, env: string, who: Who): Promise<Response | undefined> { |
| 77 | try { | |
| 78 | return await dispatch(request, url, env, who); | |
| 79 | } catch (err) { | |
| 80 | if (err instanceof HttpError) return new Response(err.message, { status: err.status }); | |
| 81 | throw err; | |
| 82 | } | |
| 83 | } | |
| 84 | ||
| 85 | async function dispatch(request: Request, url: URL, env: string, who: Who): Promise<Response | undefined> { | |
| 55 | 86 | const method = request.method; |
| 56 | 87 | const parts = url.pathname.split("/").filter(Boolean); |
| 57 | 88 | |
| 58 | if (method === "GET" && parts.length === 0) { | |
| 89 | if (parts.length === 0) { | |
| 90 | if (method !== "GET") return methodNotAllowed("GET, HEAD"); | |
| 59 | 91 | const boards = who.role === "anon" ? [] : db.listBoardsByOwner(who.id); |
| 60 | 92 | return html(landingPage(env, who, boards)); |
| 61 | 93 | } |
| @@ -82,7 +114,8 @@ export async function route(request: Request, url: URL, env: string, who: Who): | ||
| 82 | 114 | const boardId = parts[1]; |
| 83 | 115 | if (!BOARD_ID.test(boardId)) return undefined; |
| 84 | 116 | |
| 85 | if (method === "GET" && parts.length === 2) { | |
| 117 | if (parts.length === 2) { | |
| 118 | if (method !== "GET") return methodNotAllowed("GET, HEAD"); | |
| 86 | 119 | const board = db.getBoard(boardId); |
| 87 | 120 | if (!board) return new Response("board not found", { status: 404 }); |
| 88 | 121 | const columns = db.listColumns(boardId); |
src/server.test.ts +54
| @@ -347,6 +347,60 @@ test("the MCP server lists its tools and calls add_card as JSON-RPC", async () = | ||
| 347 | 347 | expect(missing.error.code).toBe(-32602); |
| 348 | 348 | }); |
| 349 | 349 | |
| 350 | test("a POST with the wrong content-type is refused before formData() runs, and the server keeps answering", async () => { | |
| 351 | const response = await fetch(base + "/boards", { | |
| 352 | method: "POST", | |
| 353 | headers: { "content-type": "application/json" }, | |
| 354 | body: "{}", | |
| 355 | }); | |
| 356 | expect(response.status).toBe(415); | |
| 357 | ||
| 358 | const next = await fetch(base + "/"); | |
| 359 | expect(next.status).toBe(200); | |
| 360 | }); | |
| 361 | ||
| 362 | test("a body that throws inside formData() anyway gets a plain 500 with the floor, never a stack trace", async () => { | |
| 363 | const response = await fetch(base + "/boards", { | |
| 364 | method: "POST", | |
| 365 | headers: { "content-type": "multipart/form-data; boundary=broken" }, | |
| 366 | body: "not actually multipart", | |
| 367 | }); | |
| 368 | expect(response.status).toBe(500); | |
| 369 | const body = await response.text(); | |
| 370 | expect(body).not.toContain("BunError"); | |
| 371 | expect(body).not.toContain("/"); | |
| 372 | expect(response.headers.get("content-security-policy")).toContain("default-src 'self'"); | |
| 373 | expect(response.headers.get("x-content-type-options")).toBe("nosniff"); | |
| 374 | ||
| 375 | const next = await fetch(base + "/"); | |
| 376 | expect(next.status).toBe(200); | |
| 377 | }); | |
| 378 | ||
| 379 | test("HEAD matches GET's status and content-length with an empty body", async () => { | |
| 380 | const id = await newBoard(); | |
| 381 | const boardPage = await (await fetch(base + `/b/${id}`)).text(); | |
| 382 | const [, staticSrc] = boardPage.match(/<script src="(\/static\/board[^"]+)"/)!; | |
| 383 | ||
| 384 | for (const path of ["/", `/b/${id}`, staticSrc, "/nope"]) { | |
| 385 | const get = await fetch(base + path); | |
| 386 | const head = await fetch(base + path, { method: "HEAD" }); | |
| 387 | expect(head.status).toBe(get.status); | |
| 388 | expect(head.headers.get("content-length")).toBe(get.headers.get("content-length")); | |
| 389 | expect(await head.text()).toBe(""); | |
| 390 | } | |
| 391 | }); | |
| 392 | ||
| 393 | test("a method the app does not implement on / or /b/<id> gets 405 with Allow", async () => { | |
| 394 | const put = await fetch(base + "/", { method: "PUT" }); | |
| 395 | expect(put.status).toBe(405); | |
| 396 | expect(put.headers.get("allow")).toBe("GET, HEAD"); | |
| 397 | ||
| 398 | const id = await newBoard(); | |
| 399 | const deleted = await fetch(base + `/b/${id}`, { method: "DELETE" }); | |
| 400 | expect(deleted.status).toBe(405); | |
| 401 | expect(deleted.headers.get("allow")).toBe("GET, HEAD"); | |
| 402 | }); | |
| 403 | ||
| 350 | 404 | test("list_boards over MCP only ever shows the caller's own boards", async () => { |
| 351 | 405 | await fetch(base + "/boards", { |
| 352 | 406 | method: "POST", |
src/server.ts +32 −9
| @@ -50,22 +50,45 @@ export const server = Bun.serve({ | ||
| 50 | 50 | // A connection silent for a minute is dropped; /b/:id/events heartbeats |
| 51 | 51 | // every 25 seconds (src/live.ts) to stay well inside that. |
| 52 | 52 | idleTimeout: 60, |
| 53 | // Never Bun's source-listing error page, in production or in a preview. | |
| 54 | development: false, | |
| 53 | 55 | async fetch(request) { |
| 54 | 56 | const url = new URL(request.url); |
| 55 | 57 | if (request.method === "POST" && !sameOrigin(request)) return withFloor(new Response("forbidden", { status: 403 })); |
| 56 | 58 | |
| 57 | const routed = await route(request, url, env, who(request, identityKey)); | |
| 58 | if (routed) return withFloor(routed); | |
| 59 | // A HEAD answers exactly like the matching GET, minus the body: route | |
| 60 | // and serve as GET, then strip the body but keep status and headers. | |
| 61 | const isHead = request.method === "HEAD"; | |
| 62 | const routingRequest = isHead ? new Request(request, { method: "GET" }) : request; | |
| 59 | 63 | |
| 60 | // Files under ./static are served as they are, cached for a year: name | |
| 61 | // them by content (board.<hash>.js) and a change is a new name, never a | |
| 62 | // stale cache. The path is confined to the directory. | |
| 63 | if (url.pathname.startsWith("/static/") && !url.pathname.includes("..")) { | |
| 64 | const routed = await route(routingRequest, url, env, who(request, identityKey)); | |
| 65 | let response: Response; | |
| 66 | if (routed) { | |
| 67 | response = withFloor(routed); | |
| 68 | } else if (url.pathname.startsWith("/static/") && !url.pathname.includes("..")) { | |
| 69 | // Files under ./static are served as they are, cached for a year: name | |
| 70 | // them by content (board.<hash>.js) and a change is a new name, never a | |
| 71 | // stale cache. The path is confined to the directory. | |
| 64 | 72 | const file = Bun.file(join(import.meta.dir, "..", url.pathname.slice(1))); |
| 65 | if (await file.exists()) | |
| 66 | return withFloor(new Response(file, { headers: { "cache-control": "public, max-age=31536000, immutable" } })); | |
| 73 | response = (await file.exists()) | |
| 74 | ? withFloor(new Response(file, { headers: { "cache-control": "public, max-age=31536000, immutable" } })) | |
| 75 | : withFloor(new Response("not found", { status: 404 })); | |
| 76 | } else { | |
| 77 | response = withFloor(new Response("not found", { status: 404 })); | |
| 67 | 78 | } |
| 68 | return withFloor(new Response("not found", { status: 404 })); | |
| 79 | ||
| 80 | if (!isHead) return response; | |
| 81 | const body = await response.arrayBuffer(); | |
| 82 | const headers = new Headers(response.headers); | |
| 83 | headers.set("content-length", String(body.byteLength)); | |
| 84 | return new Response(null, { status: response.status, headers }); | |
| 85 | }, | |
| 86 | // A thrown error (a malformed request body, anything unexpected) never | |
| 87 | // reaches the caller as Bun's HTML error page or a stack trace: log it | |
| 88 | // here, answer with a plain 500 that still carries the security floor. | |
| 89 | error(err) { | |
| 90 | console.error(err); | |
| 91 | return withFloor(new Response("internal error", { status: 500 })); | |
| 69 | 92 | }, |
| 70 | 93 | }); |
| 71 | 94 |
new above
offline