Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.
TypeScript
fix(security): authenticate before parsing large bodies (#134)
OKNOTOK6b0440ecb4d4
diff --git a/server/src/__integration__/_helpers.ts b/server/src/__integration__/_helpers.tsindex 76fdbe3..f706dc2 100644--- a/server/src/__integration__/_helpers.ts+++ b/server/src/__integration__/_helpers.ts@@ -143,7 +143,6 @@ export async function buildApiTestApp(userId: string): Promise<import('express')const expressMod = await import('express')const express = expressMod.defaultconst app = express()- app.use(express.json({ limit: '34mb' }))// Fake auth middleware: stamp authUserId from the test's choice. Real// requireAuth() just reads this field, so handlers can't distinguish.app.use((req, _res, next) => {diff --git a/server/src/__integration__/inbound.test.ts b/server/src/__integration__/inbound.test.tsindex ec8aec1..468279e 100644--- a/server/src/__integration__/inbound.test.ts+++ b/server/src/__integration__/inbound.test.ts@@ -48,9 +48,13 @@ after(async () => {async function postInbound(body: unknown, opts?: { signature?: string }): Promise<{ status: number; body: any }> {const raw = JSON.stringify(body)const sig = opts?.signature ?? signInboundPayload(raw)+ return postInboundRaw(raw, sig)+}++async function postInboundRaw(raw: string, signature: string): Promise<{ status: number; body: any }> {const res = await fetch(`${baseUrl}/webhooks/email/inbound`, {method: 'POST',- headers: { 'content-type': 'application/json', 'x-cumora-signature': sig },+ headers: { 'content-type': 'application/json', 'x-cumora-signature': signature },body: raw,})const text = await res.text()@@ -83,6 +87,29 @@ test('[integration] rejects requests missing the signature header', async () =>assert.equal(res.status, 400)})+test('[integration] rejects a bad HMAC before attempting to parse malformed JSON', async () => {+ const r = await postInboundRaw('{malformed', `sha256=${'0'.repeat(64)}`)+ assert.equal(r.status, 401)+ assert.deepEqual(r.body, { error: 'bad signature' })+})++test('[integration] parses JSON only after a valid HMAC succeeds', async () => {+ const raw = '{malformed'+ const r = await postInboundRaw(raw, signInboundPayload(raw))+ assert.equal(r.status, 400)+ assert.deepEqual(r.body, { error: 'invalid JSON body' })+})++test('[integration] rejects a missing signature before a multi-megabyte malformed body is parsed', async () => {+ const res = await fetch(`${baseUrl}/webhooks/email/inbound`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: `{${'x'.repeat(1024 * 1024)}`,+ })+ assert.equal(res.status, 400)+ assert.deepEqual(await res.json(), { error: 'missing signature' })+})+test('[integration] returns 404 when no recipient resolves to a known agent', async () => {await seedCompanyWithAgent({ agentEmail: '[email protected]' })const r = await postInbound({diff --git a/server/src/__integration__/request-body-auth.test.ts b/server/src/__integration__/request-body-auth.test.tsnew file mode 100644index 0000000..81782b8--- /dev/null+++ b/server/src/__integration__/request-body-auth.test.ts@@ -0,0 +1,140 @@+/**+ * Regression coverage for request-body limits and authentication ordering.+ *+ * The API router must never parse the large base64 upload allowance before a+ * user session has been established. Ordinary/public API requests stay on a+ * much smaller ceiling, while authenticated uploads retain their larger+ * route-specific parser.+ */+import { createServer, type Server } from 'node:http'+import assert from 'node:assert/strict'+import { after, before, beforeEach, test } from 'node:test'+import {+ ensureSchemaOnce,+ resetAllTables,+ seedUserMembership,+ teardownAll,+} from './_helpers.js'+import { pool } from '../db/pool.js'+import { createSession } from '../auth.js'++const USER_ID = 'body-auth-user'+const COMPANY_ID = 'body-auth-company'++let server: Server+let baseUrl = ''+let sessionToken = ''++before(async () => {+ await ensureSchemaOnce()+ const expressMod = await import('express')+ const express = expressMod.default+ const { api } = await import('../api/router.js')+ const app = express()+ app.use('/api', api)++ await new Promise<void>((resolve) => {+ server = createServer(app).listen(0, () => {+ const address = server.address()+ if (!address || typeof address === 'string') throw new Error('missing test address')+ baseUrl = `http://127.0.0.1:${address.port}`+ resolve()+ })+ })+})++beforeEach(async () => {+ await resetAllTables()+ await pool.query(+ `INSERT INTO companies (id, name, slug, owner_user_id)+ VALUES ($1, 'Body Auth Test', $2, $3)`,+ [COMPANY_ID, COMPANY_ID, USER_ID],+ )+ await seedUserMembership(USER_ID, COMPANY_ID)+ sessionToken = (await createSession(USER_ID, {})).token+})++after(async () => {+ await teardownAll(server)+})++async function postRaw(+ path: string,+ body: string,+ headers: Record<string, string> = {},+): Promise<{ status: number; body: string }> {+ const response = await fetch(`${baseUrl}${path}`, {+ method: 'POST',+ headers: { 'content-type': 'application/json', ...headers },+ body,+ })+ return { status: response.status, body: await response.text() }+}++test('[integration] upload rejects an anonymous multi-megabyte body before parsing JSON', async () => {+ const response = await postRaw('/api/uploads', `{${'x'.repeat(1024 * 1024)}`)+ assert.equal(response.status, 401)+ assert.deepEqual(JSON.parse(response.body), { error: 'authentication required' })+})++test('[integration] authenticated upload retains its route-specific large JSON allowance', async () => {+ const response = await postRaw(+ '/api/uploads',+ JSON.stringify({+ name: 'probe.bin',+ mime: 'application/x-not-allowed',+ dataBase64: 'A'.repeat(300 * 1024),+ }),+ {+ authorization: `Bearer ${sessionToken}`,+ 'x-company-id': COMPANY_ID,+ },+ )+ assert.equal(response.status, 415)+ assert.match(response.body, /mime not allowed/i)+})++test('[integration] an expired session rejects a large malformed upload before JSON parsing', async () => {+ await pool.query(+ `UPDATE sessions SET expires_at = NOW() - INTERVAL '1 minute' WHERE user_id = $1`,+ [USER_ID],+ )+ const response = await postRaw(+ '/api/uploads',+ `{${'x'.repeat(1024 * 1024)}`,+ { authorization: `Bearer ${sessionToken}` },+ )+ assert.equal(response.status, 401)+ assert.deepEqual(JSON.parse(response.body), { error: 'authentication required' })+})++test('[integration] ordinary anonymous API JSON is capped at 256KB', async () => {+ const response = await postRaw(+ '/api/auth/apple/native',+ JSON.stringify({ padding: 'x'.repeat(300 * 1024) }),+ )+ assert.equal(response.status, 413)+ assert.deepEqual(JSON.parse(response.body), { error: 'request entity too large' })+})++test('[integration] malformed ordinary JSON returns a stable 400 response', async () => {+ const response = await postRaw('/api/auth/apple/native', '{malformed')+ assert.equal(response.status, 400)+ assert.deepEqual(JSON.parse(response.body), { error: 'invalid JSON body' })+})++test('[integration] unsupported JSON charset remains a stable 415 client error', async () => {+ const response = await postRaw('/api/auth/apple/native', '{}', {+ 'content-type': 'application/json; charset=iso-8859-1',+ })+ assert.equal(response.status, 415)+ assert.deepEqual(JSON.parse(response.body), { error: 'unsupported request encoding' })+})++test('[integration] unsupported content encoding remains a stable 415 client error', async () => {+ const response = await postRaw('/api/auth/apple/native', '{}', {+ 'content-encoding': 'x-unsupported',+ })+ assert.equal(response.status, 415)+ assert.deepEqual(JSON.parse(response.body), { error: 'unsupported request encoding' })+})diff --git a/server/src/__integration__/runtime-aux-authorization.test.ts b/server/src/__integration__/runtime-aux-authorization.test.tsindex 91a13ff..2fcbb25 100644--- a/server/src/__integration__/runtime-aux-authorization.test.ts+++ b/server/src/__integration__/runtime-aux-authorization.test.ts@@ -37,7 +37,6 @@ before(async () => {const express = expressMod.defaultconst { runtimeRouter } = await import('../agents/runtime/server.js')const app = express()- app.use(express.json({ limit: '4mb' }))app.use('/runtime', runtimeRouter)await new Promise<void>((resolve) => {server = createServer(app).listen(0, () => {diff --git a/server/src/__integration__/runtime-server.test.ts b/server/src/__integration__/runtime-server.test.tsindex 9cb91d4..229eaad 100644--- a/server/src/__integration__/runtime-server.test.ts+++ b/server/src/__integration__/runtime-server.test.ts@@ -45,7 +45,6 @@ before(async () => {const express = expressMod.defaultconst { runtimeRouter } = await import('../agents/runtime/server.js')const app = express()- app.use(express.json({ limit: '4mb' }))app.use('/runtime', runtimeRouter)await new Promise<void>((resolve) => {server = createServer(app).listen(0, () => {@@ -81,6 +80,20 @@ async function call(return { status: res.status, body: parsed }}+async function callRaw(+ path: string,+ opts: { method?: string; token?: string; body: string },+): Promise<{ status: number; body: string }> {+ const headers: Record<string, string> = { 'content-type': 'application/json' }+ if (opts.token) headers.authorization = `Bearer ${opts.token}`+ const res = await fetch(`${baseUrl}${path}`, {+ method: opts.method ?? 'POST',+ headers,+ body: opts.body,+ })+ return { status: res.status, body: await res.text() }+}+async function seedAgent(): Promise<{ agentId: string; companyId: string; token: string }> {const companyId = `c-${randomUUID().slice(0, 8)}`const agentId = `a-${randomUUID().slice(0, 8)}`@@ -145,6 +158,52 @@ test('[integration] runtime: missing Authorization → 401', async () => {assert.match(String(r.body?.error ?? ''), /bearer/i)})+test('[integration] runtime: authentication rejects malformed multi-megabyte JSON before parsing', async () => {+ const r = await callRaw('/runtime/status', {+ body: `{${'x'.repeat(5 * 1024 * 1024)}`,+ })+ assert.equal(r.status, 401)+ assert.match(r.body, /missing bearer token/i)+})++test('[integration] runtime: authenticated JSON remains bounded to 4MB', async () => {+ const { token } = await seedAgent()+ const r = await callRaw('/runtime/status', {+ token,+ body: JSON.stringify({ status: 'avail', padding: 'x'.repeat(4 * 1024 * 1024) }),+ })+ assert.equal(r.status, 413)+ assert.deepEqual(JSON.parse(r.body), { error: 'request entity too large' })+})++test('[integration] runtime: FUSE whole-file writes authenticate before their large parser', async () => {+ const r = await callRaw('/runtime/fs/write', {+ method: 'PUT',+ body: `{${'x'.repeat(5 * 1024 * 1024)}`,+ })+ assert.equal(r.status, 401)+ assert.match(r.body, /missing bearer token/i)+})++test('[integration] runtime: FUSE preserves authenticated whole-file writes above 4MB', async () => {+ const { agentId, token } = await seedAgent()+ const fileBody = 'x'.repeat(5 * 1024 * 1024)+ const r = await call('/runtime/fs/write', {+ method: 'PUT',+ token,+ body: { path: 'large-workspace-file.txt', body: fileBody },+ })+ assert.equal(r.status, 200)+ assert.deepEqual(r.body, { ok: true })+ const { rows } = await pool.query<{ bytes: number }>(+ `SELECT OCTET_LENGTH(body)::int AS bytes+ FROM agent_workspace+ WHERE agent_id = $1 AND path = 'large-workspace-file.txt'`,+ [agentId],+ )+ assert.equal(rows[0]?.bytes, Buffer.byteLength(fileBody))+})+test('[integration] runtime: wrong scheme (Basic instead of Bearer) → 401', async () => {const r = await call('/runtime/inbox', {method: 'GET',diff --git a/server/src/agents/runtime/fs-endpoints.ts b/server/src/agents/runtime/fs-endpoints.tsindex 86a0b7c..003206a 100644--- a/server/src/agents/runtime/fs-endpoints.ts+++ b/server/src/agents/runtime/fs-endpoints.ts@@ -23,7 +23,7 @@* existing row counts as a directory. There are no explicit* directory rows in `agent_workspace`.*/-import type { Router, Response } from 'express'+import { json, type Router, type Response } from 'express'import { pool } from '../../db/pool.js'import { isSafePath, likeEscape } from './fs-namespace.js'import type { AgentRuntimeClaims } from './jwt.js'@@ -114,7 +114,10 @@ export function attachFsEndpoints(}))// PUT /runtime/fs/write { path, body } — upsert- router.put('/fs/write', withAgent(async (c, req, res) => {+ // FUSE flushes the whole file in one JSON request. Preserve the historical+ // 34MB compatibility ceiling, but install it here so runtime authentication+ // and current-assignment validation always run before the body is consumed.+ router.put('/fs/write', json({ limit: '34mb' }), withAgent(async (c, req, res) => {const body = req.body as { path?: string; body?: string; conversationId?: string } | undefinedconst p = ensureSafePath(body?.path, res)if (p === null) returndiff --git a/server/src/agents/runtime/server.ts b/server/src/agents/runtime/server.tsindex 454a138..615b1b6 100644--- a/server/src/agents/runtime/server.ts+++ b/server/src/agents/runtime/server.ts@@ -15,7 +15,7 @@* `/api` because the cookie-auth middleware on /api would reject these* (and we don't want pods sharing the human session cookie path).*/-import { Router, type Request, type Response, type NextFunction } from 'express'+import { Router, json, type Request, type Response, type NextFunction } from 'express'import { runCli } from '../cli.js'import { buildTriageRequest, gatherClaimsByConvo } from '../inbox-triage.js'import { buildTeamRosterText, getPersona } from '../personas.js'@@ -33,6 +33,7 @@ import { attachFsEndpoints } from './fs-endpoints.js'import { inprocClient } from './inproc-client.js'import { verifyAgentToken, type AgentRuntimeClaims } from './jwt.js'import { attachWakeStream, } from './wake-bus.js'+import { publicBodyParserError } from '../../body-parser-errors.js'export type { WakeEvent } from './wake-bus.js'@@ -100,6 +101,17 @@ function withAgent(export const runtimeRouter: Router = Router()runtimeRouter.use(authMiddleware as never)+// JWT signature, tenant claim, and current agent assignment are all checked+// before any body parser reads JSON. Most runtime calls are small; the FUSE+// whole-file write endpoint installs its compatibility parser at the route.+const runtimeJsonParser = json({ limit: '4mb' })+runtimeRouter.use((req, res, next) => {+ if (req.method === 'PUT' && /^\/fs\/write\/?$/.test(req.path)) {+ next()+ return+ }+ runtimeJsonParser(req, res, next)+})// ─── wake stream: server pushes events to the agent's long-running pod ─@@ -776,3 +788,15 @@ runtimeRouter.post('/notices', withAgent(async (c, req, res) => {}res.json({ posted: out.posted })}))++// Keep body-parser failures machine-readable and avoid exposing its default+// HTML error page to runtime clients. Authentication failures have already+// returned before this parser can run.+runtimeRouter.use((err: unknown, _req: Request, res: Response, next: NextFunction) => {+ const parserError = publicBodyParserError(err)+ if (parserError) {+ res.status(parserError.status).json({ error: parserError.message })+ return+ }+ next(err)+})diff --git a/server/src/api/inbound-email.ts b/server/src/api/inbound-email.tsindex 3b46b2a..1a14b2d 100644--- a/server/src/api/inbound-email.ts+++ b/server/src/api/inbound-email.ts@@ -20,13 +20,14 @@* Mount at /webhooks/email/inbound (NOT /api/...) so the user-auth* middleware doesn't intercept and 401 the worker.*/-import express, { Router, type Request, type Response } from 'express'+import express, { Router, type Request, type Response, type NextFunction } from 'express'import { createHmac, timingSafeEqual, randomUUID } from 'node:crypto'import { pool } from '../db/pool.js'import { env } from '../env.js'import { storage } from '../storage.js'import { inc } from '../metrics.js'import { alertDiscord } from '../alert.js'+import { publicBodyParserError } from '../body-parser-errors.js'import {parseAddress,formatAddress,@@ -41,23 +42,59 @@ import {export const inboundEmailRouter = Router()-/** Capture the raw body bytes so we can HMAC-verify before the global- * express.json (in index.ts) gets to it — `verify` runs as part of- * body-parser's parse step, perfect spot to stash the raw buffer.- * Mount this router BEFORE the generic `express.json` in the app- * middleware chain; body-parser sets `req._body = true` after parsing,- * so the global parser becomes a no-op for these requests.- *- * 25mb mirrors the upload ceiling — same rationale (don't accept emails- * bigger than what we'd let a human upload). */-inboundEmailRouter.use(- express.json({- limit: '25mb',- verify: (req, _res, buf) => {- (req as Request & { rawBody?: Buffer }).rawBody = Buffer.from(buf)- },- }),-)+// Reject disabled, missing, or malformed authentication before reading a+// potentially large request body. A well-formed signature still requires the+// raw bytes for HMAC, but JSON parsing and object allocation happen only after+// the constant-time comparison succeeds.+inboundEmailRouter.use((req, res, next) => {+ if (!env.EMAIL_INBOUND_HMAC_SECRET) {+ res.status(503).json({ error: 'inbound email disabled (EMAIL_INBOUND_HMAC_SECRET unset)' })+ return+ }+ const signature = String(req.headers['x-cumora-signature'] ?? '')+ if (!signature) {+ res.status(400).json({ error: 'missing signature' })+ return+ }+ if (!normalizeSignature(signature)) {+ inc('email.inbound.bad_signature')+ res.status(401).json({ error: 'bad signature' })+ return+ }+ next()+})++// 25mb mirrors the upload ceiling. `raw` bounds bytes without JSON.parse;+// the following middleware authenticates those exact bytes first.+inboundEmailRouter.use(express.raw({ type: 'application/json', limit: '25mb' }))+inboundEmailRouter.use((err: unknown, _req: Request, res: Response, next: NextFunction) => {+ const parserError = publicBodyParserError(err)+ if (parserError) {+ res.status(parserError.status).json({ error: parserError.message })+ return+ }+ next(err)+})+inboundEmailRouter.use((req, res, next) => {+ const raw = Buffer.isBuffer(req.body) ? req.body : null+ if (!raw) {+ res.status(400).json({ error: 'missing JSON body' })+ return+ }+ const signature = String(req.headers['x-cumora-signature'] ?? '')+ if (!verifySignature(raw, signature)) {+ inc('email.inbound.bad_signature')+ res.status(401).json({ error: 'bad signature' })+ return+ }+ try {+ req.body = JSON.parse(raw.toString('utf8')) as unknown+ } catch {+ res.status(400).json({ error: 'invalid JSON body' })+ return+ }+ next()+})interface InboundPayload {/** The full RFC 5322 Message-ID, with or without angle brackets. */@@ -92,13 +129,18 @@ interface InboundPayload {/** Verify a hex-encoded HMAC-SHA256 against the raw body bytes. Constant-* time compare so no timing oracle. */+function normalizeSignature(signature: string): string | null {+ let normalized = signature.trim().toLowerCase()+ if (normalized.startsWith('sha256=')) normalized = normalized.slice(7)+ return /^[a-f0-9]{64}$/.test(normalized) ? normalized : null+}+function verifySignature(rawBody: Buffer, signature: string): boolean {const secret = env.EMAIL_INBOUND_HMAC_SECRETif (!secret) return falseconst want = createHmac('sha256', secret).update(rawBody).digest('hex')- let got = signature.trim().toLowerCase()- if (got.startsWith('sha256=')) got = got.slice(7)- if (got.length !== want.length) return false+ const got = normalizeSignature(signature)+ if (!got) return falsetry {return timingSafeEqual(Buffer.from(want, 'hex'), Buffer.from(got, 'hex'))} catch {@@ -212,23 +254,6 @@ async function resolveSender(args: {}inboundEmailRouter.post('/inbound', async (req: Request, res: Response) => {- const raw = (req as Request & { rawBody?: Buffer }).rawBody- const sig = String(req.headers['x-cumora-signature'] ?? '')- if (!raw || !sig) {- res.status(400).json({ error: 'missing signature or body' })- return- }- if (!env.EMAIL_INBOUND_HMAC_SECRET) {- // Feature off — refuse so a misconfigured worker can't silently- // succeed and have the operator wonder why no mail appears.- res.status(503).json({ error: 'inbound email disabled (EMAIL_INBOUND_HMAC_SECRET unset)' })- return- }- if (!verifySignature(raw, sig)) {- inc('email.inbound.bad_signature')- res.status(401).json({ error: 'bad signature' })- return- }const payload = req.body as InboundPayloadif (!payload || typeof payload.messageId !== 'string' || typeof payload.from !== 'string') {res.status(400).json({ error: 'bad payload — need messageId + from' })diff --git a/server/src/api/router.ts b/server/src/api/router.tsindex f3de301..2105a4b 100644--- a/server/src/api/router.ts+++ b/server/src/api/router.ts@@ -1,4 +1,4 @@-import { Router, type Request, type Response, type NextFunction } from 'express'+import { Router, json, type Request, type Response, type NextFunction } from 'express'import type { PoolClient } from 'pg'import {storage, UPLOAD_DIR, freshenAttachmentUrl, normalizeStorageKey,@@ -8,6 +8,7 @@ import { pool } from '../db/pool.js'import { CH_MESSAGE_NEW, CH_REACTIONS, CH_CONVO_UPDATED, CH_DOCS, CH_TYPING, CH_CALENDAR_EVENTS, publish } from '../redis.js'import { createPoll, castVote, closePoll, PollError } from '../polls.js'import { env } from '../env.js'+import { publicBodyParserError } from '../body-parser-errors.js'import { startConvene } from '../agents/convene.js'import { ensureDirectConversation } from '../agents/private_chat.js'import { fetchImageBytes } from '../agents/image-fetcher.js'@@ -110,6 +111,21 @@ export const api = Router()// a logged-in user call `requireAuth(req)` which throws 401 otherwise.api.use(authMiddleware as never)+// Ordinary API payloads do not contain file bytes. Keep their ceiling small+// even for anonymous/public endpoints so an unauthenticated caller can never+// make the server parse the former global 34MB JSON allowance. The one route+// that legitimately carries base64 file data is excluded here and installs+// its larger parser only after a valid user session has been established.+const defaultJsonParser = json({ limit: '256kb' })+const uploadJsonParser = json({ limit: '34mb' })+api.use((req, res, next) => {+ if (req.method === 'POST' && /^\/uploads\/?$/.test(req.path)) {+ next()+ return+ }+ defaultJsonParser(req, res, next)+})+class HttpError extends Error {constructor(public status: number, message: string) { super(message) }}@@ -121,6 +137,19 @@ function requireAuth(req: Request & AuthedRequest): string {return id}+/** Reject the only large JSON route before its parser consumes any bytes. */+function requireAuthBeforeLargeBody(+ req: Request & AuthedRequest,+ res: Response,+ next: NextFunction,+): void {+ if (!req.authUserId) {+ res.status(401).json({ error: 'authentication required' })+ return+ }+ next()+}+/** Backwards-compat alias for older handlers. Same semantics as requireAuth.* Auth is now enforced everywhere — no more dev-mode header spoofing. */function userId(req: Request & AuthedRequest): string {@@ -436,6 +465,11 @@ function errorHandler(err: unknown, _req: Request, res: Response, _next: NextFunres.status(err.status).json({ error: err.message })return}+ const parserError = publicBodyParserError(err)+ if (parserError) {+ res.status(parserError.status).json({ error: parserError.message })+ return+ }console.error('[api] 500', err)// Dev mode: surface the actual message + stack to the client so failures// can be debugged without log-diving. Production hides the cause.@@ -522,7 +556,7 @@ api.post('/uploads/presign', async (req, res) => {* path AND the R2-mode fallback for tiny files where the round-trip cost* of presign isn't worth it.*/-api.post('/uploads', async (req, res) => {+api.post('/uploads', requireAuthBeforeLargeBody, uploadJsonParser, async (req, res) => {// Auth + tenant gate. Without this, anyone on the open internet could push// 25MB blobs into our storage — a DoS + cost vector. Membership-only is// sufficient since attachments are a baseline chat feature.diff --git a/server/src/body-parser-errors.ts b/server/src/body-parser-errors.tsnew file mode 100644index 0000000..d51f314--- /dev/null+++ b/server/src/body-parser-errors.ts@@ -0,0 +1,31 @@+/**+ * Convert body-parser's documented client errors into a stable public shape.+ *+ * Only known body-parser error types with a 4xx status are accepted. This+ * keeps parser failures from becoming noisy 500s without trusting arbitrary+ * application errors that happen to carry a `status` field.+ */+const CLIENT_ERROR_TYPES = new Set([+ 'charset.unsupported',+ 'encoding.unsupported',+ 'entity.parse.failed',+ 'entity.too.large',+ 'entity.verify.failed',+ 'parameters.too.many',+ 'request.aborted',+ 'request.size.invalid',+])++export function publicBodyParserError(err: unknown): { status: number; message: string } | null {+ if (!err || typeof err !== 'object') return null+ const candidate = err as { type?: unknown; status?: unknown; statusCode?: unknown }+ if (typeof candidate.type !== 'string' || !CLIENT_ERROR_TYPES.has(candidate.type)) return null+ const status = candidate.status ?? candidate.statusCode+ if (typeof status !== 'number' || !Number.isInteger(status) || status < 400 || status > 499) {+ return null+ }+ if (status === 413) return { status, message: 'request entity too large' }+ if (status === 415) return { status, message: 'unsupported request encoding' }+ if (candidate.type === 'entity.parse.failed') return { status, message: 'invalid JSON body' }+ return { status, message: 'invalid request body' }+}diff --git a/server/src/index.ts b/server/src/index.tsindex 009c4ea..ff2467d 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -102,17 +102,11 @@ async function main() {}next()})- // Inbound-email webhook (Cloudflare Email Worker → here). Mount BEFORE- // the generic JSON parser — the router has its own express.json with a- // `verify` hook that captures rawBody for HMAC validation. Once it- // parses, body-parser flips req._body=true so the generic parser below- // becomes a no-op for these requests.+ // Inbound-email webhook (Cloudflare Email Worker → here). It owns its+ // endpoint-specific 25MB parser and raw-body HMAC capture; the API and+ // runtime routers below own their smaller/authenticated JSON policies.app.use('/webhooks/email', inboundEmailRouter)- // Bumped from 256kb to 32mb because the upload endpoint takes base64-encoded- // file bodies up to MAX_UPLOAD_BYTES (25MB raw → ~34MB base64). R2-mode- // uploads bypass this limit entirely (browser PUTs directly to R2).- app.use(express.json({ limit: '34mb' }))if (storage.mode === 'local') {app.use('/uploads', express.static(UPLOAD_DIR, {fallthrough: false,