diff --git a/.changeset/request-body-limit.md b/.changeset/request-body-limit.md new file mode 100644 index 00000000000..648599641a5 --- /dev/null +++ b/.changeset/request-body-limit.md @@ -0,0 +1,27 @@ +--- +'@objectstack/plugin-hono-server': patch +'@objectstack/hono': patch +'@objectstack/service-storage': patch +'@objectstack/spec': patch +--- + +fix(plugin-hono-server, hono)!: a request body over the server's limit is answered 413 PAYLOAD_TOO_LARGE and is not read past the limit + +Clause-②: yes (narrowing) — a JSON, form or other body over 10 MiB that both HTTP doors read today is answered `413 PAYLOAD_TOO_LARGE`, unread past the limit, unless an operator raises the limit. The published surface also widens: `HonoPluginOptions.maxRequestBodyBytes`, `createHonoApp`'s `maxRequestBodyBytes` option, `HonoHttpServer.setMaxRequestBodyBytes()` / `getMaxRequestBodyBytes()`, the `OS_HTTP_MAX_BODY_BYTES` environment variable, and the `body-limit` exports of `@objectstack/plugin-hono-server`. +Metadata-protocol: none +Skills-docs: follow-up owed — content/docs/api/error-catalog.mdx (the `VALIDATION_ERROR` callout) and content/docs/protocol/kernel/error-handling.mdx (the 413 row) list the causes of `413 PAYLOAD_TOO_LARGE` and do not yet name a request body over the server's limit, nor `maxRequestBodyBytes` / `OS_HTTP_MAX_BODY_BYTES`; no file under `skills/**` teaches a request-body limit. + + + +**BREAKING** for a client that sends a JSON, form or other request body over 10 MiB to a data, API or auth route: that request is now answered `413 PAYLOAD_TOO_LARGE` instead of being read. + +- **Who moves.** The operator of a deployment whose clients send bodies that large. Raise the limit: `maxRequestBodyBytes` (in bytes) on `HonoServerPlugin` or `createHonoApp`, `HonoHttpServer.setMaxRequestBodyBytes()` on an embedded adapter, or the `OS_HTTP_MAX_BODY_BYTES` environment variable. Or send the content as a file through a storage upload door, which keeps its own limit. +- **File uploads** through the storage doors (the presigned raw PUT, the chunk PUT and the upload link, one file or several) see no change: they stay bounded by `max_upload_mb`. + +Both HTTP doors, the self-hosted server (`@objectstack/plugin-hono-server`) and `createHonoApp` (`@objectstack/hono`), now hold one request-body limit, 10 MiB by default. A request that declares a `Content-Length` over the limit is not read at all. A body with no declared length is counted while it is read, and reading stops once it passes the limit. In both cases the request is answered `413` with the registered code `PAYLOAD_TOO_LARGE`. A body of exactly the limit is read as before. The limit covers every reader of the body, not only the doors' own JSON and form parsing: routes mounted on the raw Hono app, and requests the doors forward whole to the auth service or to a domain, read through it as well. A route that never reads the body still reads nothing. + +To change the limit, set `maxRequestBodyBytes` (in bytes) on `HonoServerPlugin`, call `HonoHttpServer.setMaxRequestBodyBytes()` on an embedded adapter, or pass `maxRequestBodyBytes` to `createHonoApp`. Without an option, the `OS_HTTP_MAX_BODY_BYTES` environment variable sets it. A value that is not a positive whole number of bytes fails the boot instead of serving with no limit or the wrong one. + +Upload doors keep their own limit. The storage byte doors (the presigned raw PUT, the chunk PUT and the upload-link PUT) read the raw bytes through `IHttpRequest.rawBody()`, which still serves the whole body, so a file is bounded by the storage `max_upload_mb` setting exactly as before, even when that is larger than the request-body limit. + +The upload link's several-file form is bounded by that door's own form limit (each file within `max_upload_mb`, times the files the link takes, plus the form's framing), not by the request-body limit. A route that is refused `req.body` for size and then reads `rawBody()` takes the read over under its own bound, and its own answer stands. diff --git a/packages/adapters/hono/src/hono-body-refusal.test.ts b/packages/adapters/hono/src/hono-body-refusal.test.ts index b3c0adc75fb..04cbd426151 100644 --- a/packages/adapters/hono/src/hono-body-refusal.test.ts +++ b/packages/adapters/hono/src/hono-body-refusal.test.ts @@ -292,3 +292,175 @@ describe('[#23914, #24042] both Hono doors answer one body alike, media type by } }); }); + +/** + * The request-body limit (`@objectstack/plugin-hono-server`'s + * `src/body-limit.ts`), on both doors. The client's body is a stream that + * counts what the server pulled from it, so "not read" and "not read past the + * limit" are measured, not inferred from the status. + */ +describe('a request body over the transport limit is answered 413 and not read past the limit, on both doors', () => { + const LIMIT = 64; + const CHUNK = 16; + + /** A client body that yields `text` in `CHUNK`-byte pieces and counts the bytes the server pulled. */ + function countedBody(text: string) { + const bytes = new TextEncoder().encode(text); + let sent = 0; + const stream = new ReadableStream({ + pull(controller) { + if (sent >= bytes.byteLength) { + controller.close(); + return; + } + const piece = bytes.slice(sent, sent + CHUNK); + sent += piece.byteLength; + controller.enqueue(piece); + }, + }, { highWaterMark: 0 }); + return { stream, sent: () => sent, total: bytes.byteLength }; + } + + /** A JSON document of exactly `size` bytes. */ + const jsonOfSize = (size: number) => `{"a":"${'x'.repeat(size - 8)}"}`; + + /** `declared` sends `Content-Length: size`; `chunked` sends `Transfer-Encoding` and no length. */ + function init(method: string, contentType: string, stream: ReadableStream, framing: { declared?: number; chunked?: boolean }): RequestInit { + const headers: Record = { 'content-type': contentType }; + if (framing.declared !== undefined) headers['content-length'] = String(framing.declared); + if (framing.chunked) headers['transfer-encoding'] = 'chunked'; + return { method, headers, body: stream, duplex: 'half' } as RequestInit; + } + + const hostedApp = (limit = LIMIT) => createHonoApp({ kernel, prefix: PREFIX, cors: false, maxRequestBodyBytes: limit }); + + /** The self-hosted door: a reading route, a byte door that reads `rawBody()`, a raw-app reader, and a route that refuses before it reads. */ + function directServer(limit = LIMIT) { + const server = new HonoHttpServer(0); + server.setMaxRequestBodyBytes(limit); + server.post(`${PREFIX}/data/:object/query`, (req, res) => { res.json({ success: true, data: req.body }); }); + server.put(`${PREFIX}/bytes/:id`, async (req, res) => { + const bytes = await req.rawBody!(); + res.json({ success: true, data: { size: bytes.byteLength, text: bytes.toString('utf8') } }); + }); + server.post(`${PREFIX}/signed-in-only`, (_req, res) => { + res.status(401).json({ success: false, error: { code: 'UNAUTHENTICATED', message: 'Sign in first.' } }); + }); + // A raw-app route that reads the request itself, as the auth service's mount does. + server.getRawApp().post(`${PREFIX}/auth/sign-in/email`, async (c) => { + try { + return c.json({ success: true, data: await c.req.raw.json() }); + } catch { + return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: 'reader fault' } }, 500); + } + }); + return server; + } + + const hosted = (path: string, method: string, contentType: string, stream: ReadableStream, framing: { declared?: number; chunked?: boolean }, limit?: number) => + hostedApp(limit).request(`http://hosted.test${PREFIX}${path}`, init(method, contentType, stream, framing)); + const direct = (path: string, method: string, contentType: string, stream: ReadableStream, framing: { declared?: number; chunked?: boolean }, limit?: number) => + directServer(limit).getRawApp().fetch(new Request(`http://direct.test${PREFIX}${path}`, init(method, contentType, stream, framing))); + + async function expectTooLarge(res: Response) { + const json = await res.json() as any; + expect(res.status, JSON.stringify(json)).toBe(413); + expect(json).toEqual({ success: false, error: { code: 'PAYLOAD_TOO_LARGE', message: expect.stringContaining(`(${LIMIT} bytes)`) } }); + return json; + } + + /** [label, the door, the path, the method] — every reader of a body on each door. */ + const READERS: Array<[string, typeof hosted, string, string]> = [ + ['the hosted door, a domain that reads the parsed body', hosted, QUERY, 'POST'], + ['the hosted door, a domain that reads the forwarded request', hosted, '/webhooks/redeliver', 'POST'], + ['the hosted door, the auth fallback that reads the parsed body', hosted, '/auth/sign-in/email', 'POST'], + ['the self-hosted door, a route that reads req.body', direct, QUERY, 'POST'], + ['the self-hosted door, a raw-app route that reads the request itself', direct, '/auth/sign-in/email', 'POST'], + ]; + + it.each(READERS)('%s: a declared length over the limit is answered 413 and no byte of it is read', async (_label, door, path, method) => { + const body = countedBody(jsonOfSize(LIMIT + 1)); + await expectTooLarge(await door(path, method, 'application/json', body.stream, { declared: body.total })); + expect(body.sent()).toBe(0); + expect(seen).toEqual([]); + }); + + it.each(READERS)('%s: a body with no declared length is answered 413 once it passes the limit, and is not read further', async (_label, door, path, method) => { + const body = countedBody(jsonOfSize(LIMIT * 10)); + await expectTooLarge(await door(path, method, 'application/json', body.stream, { chunked: true })); + expect(body.sent()).toBeLessThanOrEqual(LIMIT + 2 * CHUNK); + expect(body.sent()).toBeLessThan(body.total); + expect(seen).toEqual([]); + }); + + it.each([ + ['declared', { declared: LIMIT }], + ['with no declared length', { chunked: true }], + ] as const)('a body of exactly the limit, %s, is read as before on both doors', async (_label, framing) => { + const text = jsonOfSize(LIMIT); + const hostedRes = await hosted(QUERY, 'POST', 'application/json', countedBody(text).stream, framing); + const directRes = await direct(QUERY, 'POST', 'application/json', countedBody(text).stream, framing); + expect(hostedRes.status).toBe(200); + expect(directRes.status).toBe(200); + expect(await hostedRes.json()).toEqual({ success: true, data: JSON.parse(text) }); + expect(await directRes.json()).toEqual({ success: true, data: JSON.parse(text) }); + }); + + it('an operator-raised limit admits the larger body, on both doors', async () => { + const text = jsonOfSize(LIMIT * 3); + const hostedRes = await hosted(QUERY, 'POST', 'application/json', countedBody(text).stream, { declared: LIMIT * 3 }, LIMIT * 4); + const directRes = await direct(QUERY, 'POST', 'application/json', countedBody(text).stream, { chunked: true }, LIMIT * 4); + expect(hostedRes.status).toBe(200); + expect(directRes.status).toBe(200); + expect((await directRes.json() as any).data).toEqual(JSON.parse(text)); + }); + + it.each([ + ['declared, sent as bytes', 'application/octet-stream', { declared: LIMIT * 4 }], + ['declared, sent as the JSON file it is', 'application/json', { declared: LIMIT * 4 }], + ['with no declared length, sent as bytes', 'application/octet-stream', { chunked: true }], + ['with no declared length, sent as the JSON file it is', 'application/json', { chunked: true }], + ] as const)('a byte door that reads rawBody() keeps its own bound: a body over the transport limit, %s, arrives whole', async (_label, contentType, framing) => { + const text = jsonOfSize(LIMIT * 4); + const res = await direct('/bytes/f_1', 'PUT', contentType, countedBody(text).stream, framing); + expect(res.status, await res.clone().text()).toBe(200); + expect(await res.json()).toEqual({ success: true, data: { size: LIMIT * 4, text } }); + }); + + it('a route that refuses an anonymous caller before reading keeps its answer, and reads nothing', async () => { + const body = countedBody(jsonOfSize(LIMIT * 10)); + const res = await direct('/signed-in-only', 'POST', 'application/json', body.stream, { declared: body.total }); + expect(res.status).toBe(401); + expect(body.sent()).toBe(0); + }); + + it('CONTROL: a JSON and a form body within the limit are read as before, on both doors', async () => { + for (const [contentType, text, expected] of [ + ['application/json', '{"where":{"status":"churned"}}', { where: { status: 'churned' } }], + ['application/x-www-form-urlencoded', 'token=abc&x=1', { token: 'abc', x: '1' }], + ] as const) { + for (const framing of [{ declared: Buffer.byteLength(text) }, { chunked: true }]) { + seen.length = 0; + const hostedRes = await hosted(QUERY, 'POST', contentType, countedBody(text).stream, framing); + expect(hostedRes.status).toBe(200); + expect(seen).toEqual([{ path: QUERY, read: expected }]); + const directRes = await direct(QUERY, 'POST', contentType, countedBody(text).stream, framing); + expect(directRes.status).toBe(200); + expect(await directRes.json()).toEqual({ success: true, data: expected }); + } + } + }); + + it('the default limit is 10 MiB on both doors, and a declared length over it is not read', async () => { + const TEN_MIB = 10 * 1024 * 1024; + expect(new HonoHttpServer(0).getMaxRequestBodyBytes()).toBe(TEN_MIB); + const server = new HonoHttpServer(0); + server.post(`${PREFIX}/data/:object/query`, (req, res) => { res.json({ success: true, data: req.body }); }); + for (const app of [createHonoApp({ kernel, prefix: PREFIX, cors: false }), server.getRawApp()]) { + const body = countedBody(jsonOfSize(LIMIT)); + const res = await app.request(`http://default.test${PREFIX}${QUERY}`, init('POST', 'application/json', body.stream, { declared: TEN_MIB + 1 })); + expect(res.status).toBe(413); + expect(body.sent()).toBe(0); + } + }); +}); diff --git a/packages/adapters/hono/src/index.ts b/packages/adapters/hono/src/index.ts index 5f40640c3d6..9266a55878c 100644 --- a/packages/adapters/hono/src/index.ts +++ b/packages/adapters/hono/src/index.ts @@ -45,6 +45,11 @@ import { DEFAULT_CORS_ALLOW_HEADERS, DEFAULT_CORS_EXPOSE_HEADERS, declaredEnvelopeForThrow, + installRequestBodyLimit, + requestBodyGuardOf, + requestBodyTooLargeAnswer, + resolveMaxRequestBodyBytes, + RequestBodyTooLarge, } from '@objectstack/plugin-hono-server'; export interface ObjectStackHonoCorsOptions { @@ -83,6 +88,18 @@ export interface ObjectStackHonoOptions { prefix?: string; /** CORS configuration. Set to `false` to disable entirely. */ cors?: ObjectStackHonoCorsOptions | false; + /** + * The request-body limit, in bytes: `@objectstack/plugin-hono-server`'s + * rule (`src/body-limit.ts`), on this door too. A body over it is not read + * past the limit and is answered `413 PAYLOAD_TOO_LARGE`; a declared length + * over it is not read at all, by this adapter or by a domain or auth service + * the request is forwarded to. + * + * Unset, the limit is `OS_HTTP_MAX_BODY_BYTES`, else 10 MiB. A value that is + * not a positive whole number of bytes makes `createHonoApp` throw. + * @default 10485760 + */ + maxRequestBodyBytes?: number; /** * @deprecated RETIRED (ADR-0006 Phase 5) — ignored. Multi-tenant routing is * owned by the host's `KernelResolver` (registered as the @@ -403,6 +420,15 @@ export function objectStackMiddleware(kernel: ObjectKernel) { * ahead of a route handler on `plugin-hono-server`. No list of routes is kept * here: whether a domain reads the body is answered by the domain reading it. * + * ## A body over the request-body limit + * + * `createHonoApp` installs `@objectstack/plugin-hono-server`'s limit + * (`src/body-limit.ts`) ahead of every route, so this reading, the auth + * service and every domain the request is forwarded to read through it. A + * declared length over the limit is not read here: the body handed on refuses + * with `413 PAYLOAD_TOO_LARGE` when read. A body with no declared length is + * read up to the limit, and a read the guard stopped is refused as too large. + * * `@objectstack/plugin-hono-server` answers the same body with the same * `status`, `code` and `message` (`hono-body-refusal.test.ts` drives both * doors over one table). @@ -411,12 +437,20 @@ async function readDispatchBody(c: Context): Promise { const lowered = (c.req.header('content-type') ?? '').toLowerCase(); const raw = c.req.raw; + // The request-body limit (`@objectstack/plugin-hono-server`'s + // `src/body-limit.ts`): a declared length over it is never read, and a read + // the guard stopped past it is refused as too large, not as unreadable. + const guard = requestBodyGuardOf(c); + if (guard?.declaredOverLimit) return refusedOnRead(new RequestBodyTooLarge(guard.limit)); + const tooLargeOr = (refusal: RequestBodyRefusal): DispatchBody => + refusedOnRead(guard?.tripped() ? new RequestBodyTooLarge(guard.limit) : refusal); + if (lowered.includes('application/json')) { let text: string; try { text = raw.bodyUsed ? await c.req.text() : await raw.clone().text(); } catch { - return refusedOnRead(new RequestBodyRefusal(UNREADABLE_BODY_MESSAGE)); + return tooLargeOr(new RequestBodyRefusal(UNREADABLE_BODY_MESSAGE)); } if (text.trim() === '') return readable({}); try { @@ -431,7 +465,7 @@ async function readDispatchBody(c: Context): Promise { try { return readable(raw.bodyUsed ? await c.req.parseBody() : await parseBody(raw.clone())); } catch { - return refusedOnRead(new RequestBodyRefusal(malformedFormMessage(mediaType))); + return tooLargeOr(new RequestBodyRefusal(malformedFormMessage(mediaType))); } } @@ -446,7 +480,7 @@ interface DispatchBody { /** The `body` argument for `dispatch()` / `handleAuth()`. */ readonly value: any; /** The refusal, once something READ a body this adapter could not parse; `undefined` otherwise. */ - readonly refusalRead: () => RequestBodyRefusal | undefined; + readonly refusalRead: () => RequestBodyRefusal | RequestBodyTooLarge | undefined; } const readable = (value: any): DispatchBody => ({ value, refusalRead: () => undefined }); @@ -458,7 +492,7 @@ const readable = (value: any): DispatchBody => ({ value, refusalRead: () => unde * is not a read: `typeof` is `'object'`, `Array.isArray` is `false`, and * passing it along, comparing it or testing it with `??` touch nothing. */ -function refusedOnRead(refusal: RequestBodyRefusal): DispatchBody { +function refusedOnRead(refusal: RequestBodyRefusal | RequestBodyTooLarge): DispatchBody { let read = false; const refuse = (): never => { read = true; @@ -628,6 +662,12 @@ function dispatchedMethod(method: string): string { */ export function createHonoApp(options: ObjectStackHonoOptions): Hono { const app = new Hono(); + // The request-body limit, first: every reader of a request body below (this + // adapter's own `readDispatchBody`, the auth service and every domain the + // request is forwarded to) reads through it. Resolved now, so a bad value + // refuses the app instead of serving it with no bound. + const maxRequestBodyBytes = resolveMaxRequestBodyBytes(options.maxRequestBodyBytes); + installRequestBodyLimit(app, () => maxRequestBodyBytes); const prefix = options.prefix || '/api'; // [#16025] Where `/auth/*` is mounted, and the boot refusal that guards it. // Computed BEFORE any route is registered so a misaligned composition never @@ -769,6 +809,10 @@ export function createHonoApp(options: ObjectStackHonoOptions): Hono { * unchanged; only the message is replaced. */ const thrownJson = (c: any, err: any) => { + // A body over the request-body limit: `413` is a status + // `declaredEnvelopeForThrow` does not render, so it is answered here. + const tooLarge = requestBodyTooLargeAnswer(err); + if (tooLarge) return c.json(tooLarge.body, tooLarge.status); const declared = declaredEnvelopeForThrow(err); if (declared) return c.json(declared.body, declared.status); const status = err.statusCode || 500; diff --git a/packages/plugins/plugin-hono-server/src/adapter.ts b/packages/plugins/plugin-hono-server/src/adapter.ts index 8653424a78a..7816148557b 100644 --- a/packages/plugins/plugin-hono-server/src/adapter.ts +++ b/packages/plugins/plugin-hono-server/src/adapter.ts @@ -39,6 +39,15 @@ import type { Socket } from 'node:net'; type OwedResponses = Set; import { matchesRoutePattern } from './route-pattern'; import { readRequestBody, type RequestBodyReading, type RequestBodyRefusal } from './request-body'; +import { + assertMaxRequestBodyBytes, + installRequestBodyLimit, + requestBodyGuardOf, + requestBodyTooLargeAnswer, + requestBodyTooLargeEnvelope, + resolveMaxRequestBodyBytes, + RequestBodyTooLarge, +} from './body-limit'; import { compressResponse } from './response-compression'; // The ADR-0112 wire vocabulary, read as DATA rather than restated: `ErrorCode` // is the closed union (`StandardErrorCode` ∪ `ERROR_CODE_LEDGER`) a registered @@ -713,6 +722,12 @@ export class HonoHttpServer implements IHttpServer { * the default is a REAL logger and not a no-op. */ private logger: Logger = createLogger({ name: 'hono' }); + /** + * The request-body limit (`./body-limit.ts`): the default or + * `OS_HTTP_MAX_BODY_BYTES` at construction, replaced by + * {@link setMaxRequestBodyBytes}. Read per request. + */ + private maxRequestBodyBytes: number = resolveMaxRequestBodyBytes(); constructor( private port: number = 3000, @@ -736,6 +751,24 @@ export class HonoHttpServer implements IHttpServer { this.app = new Hono(); this.installErrorEnvelopeSeam(); this.installResponseCompressionSeam(); + // Inside the compression seam, ahead of every other middleware and + // route, so every reader of a request body reads through the limit. + installRequestBodyLimit(this.app, () => this.maxRequestBodyBytes); + } + + /** + * Set the request-body limit, in bytes (`./body-limit.ts`): a body over it + * is not read past it and is answered `413 PAYLOAD_TOO_LARGE`. A value that + * is not a positive whole number throws. Upload doors that read + * `rawBody()` keep their own bound. + */ + setMaxRequestBodyBytes(bytes: number): void { + this.maxRequestBodyBytes = assertMaxRequestBodyBytes(bytes, 'maxRequestBodyBytes'); + } + + /** The request-body limit this server answers under, in bytes. */ + getMaxRequestBodyBytes(): number { + return this.maxRequestBodyBytes; } /** @@ -827,7 +860,8 @@ export class HonoHttpServer implements IHttpServer { // invented `{}`. `readRequestBody` (`./request-body.ts`) says what each // media type answers and why the refusal waits for `req.body` to be read. let bodyReading: RequestBodyReading = await readRequestBody(c); - let refusedBodyRead: RequestBodyRefusal | undefined; + let refusedBodyRead: RequestBodyRefusal | RequestBodyTooLarge | undefined; + let rawBodyRead: Promise | undefined; _endParse?.(); @@ -866,9 +900,30 @@ export class HonoHttpServer implements IHttpServer { headers: rawHeaders, method: c.req.method, path: c.req.path, - rawBody: async () => { - const ab = await c.req.arrayBuffer(); - return Buffer.from(ab); + /** + * A byte door's read: the ORIGINAL body, unbounded by the + * request-body limit, because the door bounds it by its own + * (`./body-limit.ts`). Hono's body cache once a pre-read of a body + * within the limit went through it. + * + * A route that read `body`, was refused it for size, and then + * reads `rawBody()` is a door taking over the read under its own + * bound (an upload door's form larger than the request-body + * limit), so that refusal no longer stands as the answer. Every + * other refusal still does. + */ + rawBody: () => { + if (refusedBodyRead instanceof RequestBodyTooLarge) refusedBodyRead = undefined; + // Repeatable: a second call answers the same bytes as the first. + rawBodyRead ??= (async () => { + const original = requestBodyGuardOf(c)?.readOriginal(); + if (original) { + const bytes = await original; + return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength); + } + return Buffer.from(await c.req.arrayBuffer()); + })(); + return rawBodyRead; }, /** * The transport's own peer address (`IHttpRequest.remoteAddress`) @@ -1017,7 +1072,7 @@ export class HonoHttpServer implements IHttpServer { // arm's 500, a classification's own dialect, or nothing. The refusal // is the answer, and it is not this handler's failure to report. if (refusedBodyRead) { - const envelope = declaredEnvelopeForThrow(refusedBodyRead); + const envelope = requestBodyTooLargeAnswer(refusedBodyRead) ?? declaredEnvelopeForThrow(refusedBodyRead); if (envelope) { closeStream(); return { response: c.json(envelope.body, envelope.status), failed: false }; @@ -1248,6 +1303,14 @@ export class HonoHttpServer implements IHttpServer { */ private installErrorEnvelopeSeam(): void { this.app.onError((err: Error, c: any) => { + // A read the request-body limit refused (`./body-limit.ts`) is the + // request's answer, and no transport escape to report. + const guard = requestBodyGuardOf(c); + if (guard?.tripped()) { + const tooLarge = requestBodyTooLargeEnvelope(guard.limit); + return c.json(tooLarge.body, tooLarge.status); + } + // Hono's own precedence, unchanged — see the docblock. if (err !== null && typeof err === 'object' && 'getResponse' in err) { const declared = (err as unknown as { getResponse(): Response }).getResponse(); diff --git a/packages/plugins/plugin-hono-server/src/body-limit.test.ts b/packages/plugins/plugin-hono-server/src/body-limit.test.ts new file mode 100644 index 00000000000..d7cec7bbca1 --- /dev/null +++ b/packages/plugins/plugin-hono-server/src/body-limit.test.ts @@ -0,0 +1,245 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The request-body limit (`./body-limit.ts`): where an operator sets it, how a + * bad value is refused, and the rule over a REAL listener, where the body is a + * socket stream and `Content-Length` frames it. The two-door table (the + * hosted `createHonoApp` door beside this one) lives in + * `packages/adapters/hono/src/hono-body-refusal.test.ts`. + */ + +import { connect } from 'node:net'; +import { describe, it, expect, afterEach } from 'vitest'; +import { HonoHttpServer } from './adapter'; +import { HonoServerPlugin } from './hono-plugin'; +import { + DEFAULT_MAX_REQUEST_BODY_BYTES, + MAX_REQUEST_BODY_BYTES_ENV, + resolveMaxRequestBodyBytes, +} from './body-limit'; + +describe('the request-body limit is 10 MiB unless an operator sets another', () => { + it('the default is 10 MiB', () => { + expect(DEFAULT_MAX_REQUEST_BODY_BYTES).toBe(10 * 1024 * 1024); + expect(resolveMaxRequestBodyBytes(undefined, {})).toBe(DEFAULT_MAX_REQUEST_BODY_BYTES); + expect(resolveMaxRequestBodyBytes(undefined, { [MAX_REQUEST_BODY_BYTES_ENV]: ' ' })).toBe(DEFAULT_MAX_REQUEST_BODY_BYTES); + }); + + it('the environment variable sets it, and the transport option wins over it', () => { + expect(MAX_REQUEST_BODY_BYTES_ENV).toBe('OS_HTTP_MAX_BODY_BYTES'); + expect(resolveMaxRequestBodyBytes(undefined, { OS_HTTP_MAX_BODY_BYTES: '2048' })).toBe(2048); + expect(resolveMaxRequestBodyBytes(4096, { OS_HTTP_MAX_BODY_BYTES: '2048' })).toBe(4096); + }); + + it.each([ + ['zero', 0], + ['a negative number', -1], + ['a fraction', 1.5], + ['not a number', Number.NaN], + ['infinity', Number.POSITIVE_INFINITY], + ])('a transport option that is %s is refused where it is set', (_label, value) => { + expect(() => resolveMaxRequestBodyBytes(value, {})).toThrow(TypeError); + expect(() => new HonoHttpServer(0).setMaxRequestBodyBytes(value)).toThrow(/maxRequestBodyBytes must be a positive whole number of bytes/); + expect(() => new HonoServerPlugin({ maxRequestBodyBytes: value })).toThrow(TypeError); + }); + + it.each([['10MB'], ['0'], ['-5'], ['1.5'], ['1e6']])('an environment value of %j is refused, naming the variable', (raw) => { + expect(() => resolveMaxRequestBodyBytes(undefined, { OS_HTTP_MAX_BODY_BYTES: raw })).toThrow(/OS_HTTP_MAX_BODY_BYTES must be a positive whole number of bytes/); + }); + + it('the plugin option reaches the server it builds, and the setter replaces the limit', () => { + const plugin = new HonoServerPlugin({ maxRequestBodyBytes: 1234 }); + const server = (plugin as unknown as { server: HonoHttpServer }).server; + expect(server.getMaxRequestBodyBytes()).toBe(1234); + server.setMaxRequestBodyBytes(99); + expect(server.getMaxRequestBodyBytes()).toBe(99); + }); +}); + +describe('over a real listener, a body over the limit is refused unread and a byte door still receives its bytes', () => { + const LIMIT = 1024; + let server: HonoHttpServer | undefined; + + afterEach(async () => { + await server?.close(); + server = undefined; + }); + + async function start() { + server = new HonoHttpServer(0); + server.setMaxRequestBodyBytes(LIMIT); + server.post('/api/v1/data/:object/query', (req, res) => { res.json({ success: true, data: req.body }); }); + server.put('/api/v1/bytes/:id', async (req, res) => { + const bytes = await req.rawBody!(); + res.json({ success: true, data: { size: bytes.byteLength } }); + }); + // A door with its own bound beyond the request-body limit: it is refused + // `req.body` for size, and takes the read over through `rawBody()`. + server.put('/api/v1/forms/:id', async (req, res) => { + try { + res.json({ success: true, data: { parsed: Object.keys(req.body ?? {}).length } }); + } catch (err) { + if ((err as { code?: unknown }).code !== 'PAYLOAD_TOO_LARGE') throw err; + const bytes = await req.rawBody!(); + res.json({ success: true, data: { size: bytes.byteLength } }); + } + }); + await server.listen(0); + return server.getPort(); + } + + it('a declared length over the limit is answered 413 before the client has sent the body', async () => { + const port = await start(); + // Only the head is written: the answer arriving at all proves the + // server did not wait for (or read) the declared bytes. + const answer = await new Promise((resolve, reject) => { + const socket = connect(port, '127.0.0.1'); + let text = ''; + socket.on('data', (chunk) => { + text += chunk.toString('utf8'); + if (text.includes('PAYLOAD_TOO_LARGE')) { + socket.destroy(); + resolve(text); + } + }); + socket.on('error', reject); + socket.write( + 'POST /api/v1/data/task/query HTTP/1.1\r\nHost: 127.0.0.1\r\n' + + `Content-Type: application/json\r\nContent-Length: ${LIMIT * 1024}\r\n\r\n`, + ); + }); + expect(answer).toMatch(/^HTTP\/1\.1 413 /); + expect(answer).toContain('"code":"PAYLOAD_TOO_LARGE"'); + }); + + it('a body with no declared length is answered 413 past the limit', async () => { + const port = await start(); + const res = await fetch(`http://127.0.0.1:${port}/api/v1/data/task/query`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode(`{"a":"${'x'.repeat(LIMIT * 4)}"}`)); + controller.close(); + }, + }), + duplex: 'half', + } as RequestInit); + expect(res.status).toBe(413); + expect(((await res.json()) as any).error.code).toBe('PAYLOAD_TOO_LARGE'); + }); + + it.each([['application/octet-stream'], ['application/json']])('a byte door receives a %s body over the transport limit whole', async (contentType) => { + const port = await start(); + const body = new Uint8Array(LIMIT * 8).fill(0x61); + const res = await fetch(`http://127.0.0.1:${port}/api/v1/bytes/f_1`, { method: 'PUT', headers: { 'content-type': contentType }, body }); + expect(res.status, await res.clone().text()).toBe(200); + expect(((await res.json()) as any).data.size).toBe(LIMIT * 8); + }); + + it.each([['declared', true], ['not declared', false]])( + 'a door refused req.body for size takes the read over through rawBody() and its own answer stands, length %s', + async (_label, declare) => { + const port = await start(); + const form = new FormData(); + form.append('file0', new Blob([new Uint8Array(LIMIT * 8).fill(0x62)]), 'f.bin'); + const encoded = new Response(form); + const bytes = new Uint8Array(await encoded.arrayBuffer()); + const res = await fetch(`http://127.0.0.1:${port}/api/v1/forms/f_1`, { + method: 'PUT', + headers: { 'content-type': encoded.headers.get('content-type')! }, + body: declare + ? bytes + : new ReadableStream({ + start(controller) { + controller.enqueue(bytes); + controller.close(); + }, + }), + duplex: 'half', + } as RequestInit); + expect(res.status, await res.clone().text()).toBe(200); + expect(((await res.json()) as any).data.size).toBe(bytes.byteLength); + }, + ); + + it('CONTROL: a JSON body within the limit is read as before', async () => { + const port = await start(); + const res = await fetch(`http://127.0.0.1:${port}/api/v1/data/task/query`, { + method: 'POST', headers: { 'content-type': 'application/json' }, body: '{"where":{"status":"open"}}', + }); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ success: true, data: { where: { status: 'open' } } }); + }); +}); + +describe('a body refused past the limit releases its source, and a byte door reads the same bytes twice', () => { + const LIMIT = 1024; + const CHUNK = 256; + + /** An endless body that records what was pulled from it and whether it was cancelled. */ + function endlessBody() { + const state = { pulled: 0, cancelled: false }; + const stream = new ReadableStream({ + pull(controller) { + state.pulled += CHUNK; + controller.enqueue(new TextEncoder().encode('x'.repeat(CHUNK))); + }, + cancel() { + state.cancelled = true; + }, + }, { highWaterMark: 0 }); + return { stream, state }; + } + + function serverWithRoutes() { + const server = new HonoHttpServer(0); + server.setMaxRequestBodyBytes(LIMIT); + server.post('/api/v1/data/:object/query', (req, res) => { res.json({ success: true, data: req.body }); }); + server.put('/api/v1/bytes/:id', async (req, res) => { + const first = await req.rawBody!(); + const second = await req.rawBody!(); + res.json({ success: true, data: { first: first.byteLength, second: second.byteLength, same: first.equals(second) } }); + }); + return server; + } + + it.each([['application/json'], ['application/x-www-form-urlencoded']])( + 'a %s body with no declared length is answered 413 and its source is cancelled after the refusal', + async (contentType) => { + const { stream, state } = endlessBody(); + const res = await serverWithRoutes().getRawApp().request('http://localhost/api/v1/data/task/query', { + method: 'POST', + headers: { 'content-type': contentType }, + body: stream, + duplex: 'half', + } as RequestInit); + expect(res.status).toBe(413); + expect(((await res.json()) as any).error.code).toBe('PAYLOAD_TOO_LARGE'); + expect(state.cancelled).toBe(true); + expect(state.pulled).toBeLessThanOrEqual(LIMIT + 2 * CHUNK); + }, + ); + + it.each([['declared', true], ['not declared', false]])( + 'rawBody() called twice answers the same bytes both times, length %s', + async (_label, declare) => { + const bytes = new Uint8Array(LIMIT * 4).fill(0x63); + const res = await serverWithRoutes().getRawApp().request('http://localhost/api/v1/bytes/f_1', { + method: 'PUT', + headers: { 'content-type': 'application/json', ...(declare ? { 'content-length': String(bytes.byteLength) } : {}) }, + body: declare + ? bytes + : new ReadableStream({ + start(controller) { + controller.enqueue(bytes); + controller.close(); + }, + }), + duplex: 'half', + } as RequestInit); + expect(res.status, await res.clone().text()).toBe(200); + expect(((await res.json()) as any).data).toEqual({ first: bytes.byteLength, second: bytes.byteLength, same: true }); + }, + ); +}); diff --git a/packages/plugins/plugin-hono-server/src/body-limit.ts b/packages/plugins/plugin-hono-server/src/body-limit.ts new file mode 100644 index 00000000000..fc9609b6005 --- /dev/null +++ b/packages/plugins/plugin-hono-server/src/body-limit.ts @@ -0,0 +1,339 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The request-body limit both Hono doors hold: one platform-wide bound, read + * nowhere past it, answered `413 PAYLOAD_TOO_LARGE`. + * + * `@objectstack/plugin-hono-server` installs it on its app at construction, + * and `@objectstack/hono`'s `createHonoApp` installs the same function on its + * own app, so the two doors bound a body by one rule + * (`hono-body-refusal.test.ts` drives both over one table). + * + * ## The rule + * + * - **The limit** is {@link DEFAULT_MAX_REQUEST_BODY_BYTES} (10 MiB) unless the + * operator sets another: the transport option (`HonoPluginOptions` + * `maxRequestBodyBytes`, `HonoHttpServer.setMaxRequestBodyBytes`, + * `createHonoApp`'s `maxRequestBodyBytes`), else + * {@link MAX_REQUEST_BODY_BYTES_ENV}. A value that is not a positive whole + * number of bytes is refused where it is configured, so a typo fails the + * boot instead of serving with no bound or the wrong one. + * - **A declared length over the limit is never read.** The guard replaces the + * request's body with one that refuses on its first read without touching + * the client's bytes. + * - **A body with no declared length is counted while it is read**, and the + * read stops once it passes the limit. Exactly the limit is read as before. + * - **Once a read is refused, the request answers 413**, whatever the code + * that read it answered: the body it acted on was never there. + * + * ## Why the guard wraps the body instead of answering before the route + * + * The transport cannot tell, before the route runs, whether the route is an + * upload door. A byte door (`service-storage`'s chunk, upload-link and local + * raw PUTs) takes a file of any media type and bounds it by its own + * `max_upload_mb`, which may be far above this limit. So the guard bounds what + * is READ: every reader of the request's body (the doors' own pre-reads, a + * raw-app route reading `c.req`, a request forwarded whole to the auth + * service or a domain) reads through it, and a route that never reads the + * body reads nothing. The byte doors read through `IHttpRequest.rawBody()`, + * which `plugin-hono-server` serves from the ORIGINAL body (see + * {@link RequestBodyGuard.readOriginal}), so they keep their own bound. + * + * Nothing here echoes the body. + */ + +import type { Context, Hono } from 'hono'; + +/** The default request-body limit: 10 MiB. */ +export const DEFAULT_MAX_REQUEST_BODY_BYTES = 10 * 1024 * 1024; + +/** The environment variable an operator sets the limit with, in bytes. */ +export const MAX_REQUEST_BODY_BYTES_ENV = 'OS_HTTP_MAX_BODY_BYTES'; + +/** The registered ADR-0112 code a body over the limit is answered with. */ +export const PAYLOAD_TOO_LARGE_CODE = 'PAYLOAD_TOO_LARGE'; + +function positiveWholeBytes(value: unknown): number | undefined { + return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? value : undefined; +} + +/** + * Judge a configured limit: a positive whole number of bytes, or a thrown + * `TypeError` naming where it was set. + */ +export function assertMaxRequestBodyBytes(value: unknown, where: string): number { + const bytes = positiveWholeBytes(value); + if (bytes === undefined) { + throw new TypeError( + `${where} must be a positive whole number of bytes (got ${JSON.stringify(value) ?? String(value)}). ` + + `Leave it unset for the default of ${DEFAULT_MAX_REQUEST_BODY_BYTES} bytes (10 MiB).`, + ); + } + return bytes; +} + +/** + * The limit a door serves under: the transport option when given, else + * {@link MAX_REQUEST_BODY_BYTES_ENV}, else the default. Either source holding + * something that is not a positive whole number of bytes throws. + */ +export function resolveMaxRequestBodyBytes( + option?: number, + env: Record = typeof process !== 'undefined' ? process.env : {}, +): number { + if (option !== undefined) return assertMaxRequestBodyBytes(option, 'maxRequestBodyBytes'); + const raw = env[MAX_REQUEST_BODY_BYTES_ENV]; + if (raw === undefined || raw.trim() === '') return DEFAULT_MAX_REQUEST_BODY_BYTES; + const parsed = /^\d+$/.test(raw.trim()) ? Number(raw.trim()) : Number.NaN; + return assertMaxRequestBodyBytes(Number.isNaN(parsed) ? raw : parsed, MAX_REQUEST_BODY_BYTES_ENV); +} + +/** + * The refusal of a body over the limit, as a declared throw: status `413` and + * the registered `PAYLOAD_TOO_LARGE`. `413` is not a status + * `HttpStatusErrorCodeMap` names, so both doors render it with + * {@link requestBodyTooLargeEnvelope} rather than through + * `declaredEnvelopeForThrow`. + */ +export class RequestBodyTooLarge extends Error { + readonly status = 413; + readonly statusCode = 413; + readonly code = PAYLOAD_TOO_LARGE_CODE; + + constructor(readonly limit: number) { + super( + `The request body is larger than this server accepts (${limit} bytes). It was refused, and not read ` + + 'past the limit: send a smaller body. An operator raises the limit with maxRequestBodyBytes or ' + + `${MAX_REQUEST_BODY_BYTES_ENV}.`, + ); + this.name = 'RequestBodyTooLarge'; + } +} + +/** The ADR-0112 envelope both doors answer a body over the limit with. */ +export function requestBodyTooLargeEnvelope(limit: number): { + status: 413; + body: { success: false; error: { code: typeof PAYLOAD_TOO_LARGE_CODE; message: string } }; +} { + return { + status: 413, + body: { success: false, error: { code: PAYLOAD_TOO_LARGE_CODE, message: new RequestBodyTooLarge(limit).message } }, + }; +} + +/** The envelope for `thrown` when it is a {@link RequestBodyTooLarge}; `undefined` otherwise. */ +export function requestBodyTooLargeAnswer(thrown: unknown): ReturnType | undefined { + return thrown instanceof RequestBodyTooLarge ? requestBodyTooLargeEnvelope(thrown.limit) : undefined; +} + +/** The `Content-Length` a request declares, as a number; `undefined` when it declares none. */ +function declaredLength(request: Request): number | undefined { + const value = request.headers.get('content-length'); + if (value === null || value.trim() === '') return undefined; + const length = Number(value.trim()); + return Number.isFinite(length) && length >= 0 ? length : undefined; +} + +/** + * The bytes of a body read up to a bound and KEPT, so that a reader which + * stopped at the bound can still hand the whole body to a byte door. + */ +export interface HeldRequestBody { + /** The bytes read, when the whole body fit within the bound. */ + readonly bytes: Uint8Array | undefined; + /** Whether the body passed the bound (and so `bytes` is undefined). */ + readonly overLimit: boolean; + /** Every byte of the body: those held, then the rest of the stream, unbounded. */ + readAll(): Promise; +} + +function concat(chunks: Uint8Array[]): Uint8Array { + let total = 0; + for (const chunk of chunks) total += chunk.byteLength; + const out = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + out.set(chunk, offset); + offset += chunk.byteLength; + } + return out; +} + +/** One request's guard state. */ +export interface RequestBodyGuard { + /** The limit this request is served under. */ + readonly limit: number; + /** The request as the client sent it, before the guard wrapped its body. */ + readonly original: Request; + /** Whether the request declares a `Content-Length` over the limit. */ + readonly declaredOverLimit: boolean; + /** Whether the request declares a `Content-Length` (within the limit or not). */ + readonly declaresLength: boolean; + /** Whether a read through the guard was refused for passing the limit. */ + tripped(): boolean; + /** Whether anything has read through the guard. */ + pulled(): boolean; + /** + * Read the ORIGINAL body up to the limit and keep what was read. For a door's + * own pre-read of a body with no declared length: the read stops past the + * limit, and the held bytes still reach a byte door through {@link readOriginal}. + */ + hold(): Promise; + /** + * Every byte of the ORIGINAL body, unbounded by this limit: the reader is a + * byte door that bounds the body by its own limit. `undefined` when the + * original can no longer be read here (something read through the guard). + */ + readOriginal(): Promise | undefined; + /** + * At the end of the request: a held body that passed the limit and that no + * byte door went on to read whole has its source cancelled, as a read + * refused through the guard has, so the rest of it is never read. + */ + release(): Promise; +} + +const guards = new WeakMap(); + +/** The guard {@link installRequestBodyLimit} put on this request; `undefined` on an app without one. */ +export function requestBodyGuardOf(c: Context): RequestBodyGuard | undefined { + return guards.get(c.req.raw); +} + +function guardRequest(original: Request, limit: number): { guard: RequestBodyGuard; guarded: Request | undefined } { + const declared = declaredLength(original); + const declaredOverLimit = original.body !== null && !original.bodyUsed && declared !== undefined && declared > limit; + let tripped = false; + let pulled = false; + let held: Promise | undefined; + let heldReader: ReadableStreamDefaultReader | undefined; + let heldOpen = false; + let sourceReader: ReadableStreamDefaultReader | undefined; + + const guard: RequestBodyGuard = { + limit, + original, + declaredOverLimit, + declaresLength: declared !== undefined, + tripped: () => tripped, + pulled: () => pulled, + hold() { + held ??= (async (): Promise => { + const reader = original.body!.getReader(); + heldReader = reader; + const chunks: Uint8Array[] = []; + let total = 0; + let done = false; + while (total <= limit) { + const next = await reader.read(); + if (next.done) { + done = true; + break; + } + chunks.push(next.value); + total += next.value.byteLength; + } + const overLimit = !done && total > limit; + heldOpen = !done; + return { + bytes: overLimit ? undefined : concat(chunks), + overLimit, + async readAll() { + // A byte door claimed the rest: `release` leaves it to this read. + heldOpen = false; + if (!done) { + for (;;) { + const next = await reader.read(); + if (next.done) break; + chunks.push(next.value); + } + done = true; + } + return concat(chunks); + }, + }; + })(); + return held; + }, + readOriginal() { + if (held) return held.then((h) => h.readAll()); + if (pulled || original.bodyUsed || original.body?.locked) return undefined; + return original.arrayBuffer().then((buffer) => new Uint8Array(buffer)); + }, + async release() { + if (!held) return; + const reading = await held.catch(() => undefined); + if (reading?.overLimit && heldOpen && heldReader) { + heldOpen = false; + await heldReader.cancel().catch(() => undefined); + } + }, + }; + + // No body, or one something upstream of this app already consumed (a host + // that mounts this app under its own and read the body first): there is + // nothing left here to bound, and Hono's body cache holds the only copy. + if (!original.body || original.bodyUsed || original.body.locked) return { guard, guarded: undefined }; + + const refusal = () => { + tripped = true; + return new RequestBodyTooLarge(limit); + }; + + // `highWaterMark: 0` so the stream pulls only when something reads it: a + // route that never reads the body reads nothing, and is not refused. + let count = 0; + const body = new ReadableStream({ + async pull(controller) { + pulled = true; + if (declaredOverLimit) { + controller.error(refusal()); + return; + } + sourceReader ??= original.body!.getReader(); + const next = await sourceReader.read(); + if (next.done) { + controller.close(); + return; + } + count += next.value.byteLength; + if (count > limit) { + controller.error(refusal()); + await sourceReader.cancel().catch(() => undefined); + return; + } + controller.enqueue(next.value); + }, + async cancel(reason) { + await sourceReader?.cancel(reason).catch(() => undefined); + }, + }, { highWaterMark: 0 }); + + const guarded = new Request(original, { body, duplex: 'half' } as RequestInit); + return { guard, guarded }; +} + +/** + * Install the limit on `app`, as early as possible so every route and every + * later middleware reads the body through it. `limit` is asked per request, so + * a host that changes it after construction is served the new value. + */ +export function installRequestBodyLimit(app: Hono, limit: () => number): void { + app.use('*', async (c, next) => { + const { guard, guarded } = guardRequest(c.req.raw, limit()); + guards.set(c.req.raw, guard); + if (guarded) { + c.req.raw = guarded; + guards.set(guarded, guard); + } + try { + await next(); + } finally { + await guard.release(); + } + if (guard.tripped()) { + const envelope = requestBodyTooLargeEnvelope(guard.limit); + c.res = c.json(envelope.body, envelope.status); + } + }); +} diff --git a/packages/plugins/plugin-hono-server/src/hono-plugin.ts b/packages/plugins/plugin-hono-server/src/hono-plugin.ts index a57e30290fc..36a7ad3a0c9 100644 --- a/packages/plugins/plugin-hono-server/src/hono-plugin.ts +++ b/packages/plugins/plugin-hono-server/src/hono-plugin.ts @@ -118,6 +118,19 @@ export interface HonoPluginOptions { */ serverTiming?: boolean; + /** + * The request-body limit, in bytes. A body over it is not read past the + * limit and is answered `413 PAYLOAD_TOO_LARGE`; a declared length over it + * is not read at all. Upload doors that read the raw bytes + * (`IHttpRequest.rawBody()`) keep their own bound, the storage + * `max_upload_mb`. + * + * Unset, the limit is `OS_HTTP_MAX_BODY_BYTES`, else 10 MiB. A value that + * is not a positive whole number of bytes fails the plugin's construction. + * @default 10485760 + */ + maxRequestBodyBytes?: number; + /** * Observability backends for the transport's own signals. * @@ -288,6 +301,9 @@ export class HonoServerPlugin implements Plugin { // adapter's own defaults — named positionally only because `tls` // follows them (#16804). this.server = new HonoHttpServer(this.options.port, undefined, undefined, this.options.tls); + if (this.options.maxRequestBodyBytes !== undefined) { + this.server.setMaxRequestBodyBytes(this.options.maxRequestBodyBytes); + } } /** diff --git a/packages/plugins/plugin-hono-server/src/index.ts b/packages/plugins/plugin-hono-server/src/index.ts index dafc8d2a414..09ad97b627d 100644 --- a/packages/plugins/plugin-hono-server/src/index.ts +++ b/packages/plugins/plugin-hono-server/src/index.ts @@ -6,4 +6,14 @@ export * from './adapter'; export * from './pattern-matcher'; export * from './cors-admission'; export * from './route-pattern'; - +export { + DEFAULT_MAX_REQUEST_BODY_BYTES, + MAX_REQUEST_BODY_BYTES_ENV, + RequestBodyTooLarge, + installRequestBodyLimit, + requestBodyGuardOf, + requestBodyTooLargeAnswer, + requestBodyTooLargeEnvelope, + resolveMaxRequestBodyBytes, + type RequestBodyGuard, +} from './body-limit'; diff --git a/packages/plugins/plugin-hono-server/src/request-body.ts b/packages/plugins/plugin-hono-server/src/request-body.ts index 492b8308266..3c8c86758ff 100644 --- a/packages/plugins/plugin-hono-server/src/request-body.ts +++ b/packages/plugins/plugin-hono-server/src/request-body.ts @@ -73,10 +73,22 @@ * non-GET/HEAD request a stream, an empty one included. An in-process * `Request` built without those headers is therefore read as having no body. * + * ## A body over the limit (`./body-limit.ts`) + * + * The transport's request-body limit is checked first: a declared length over + * it is never read, and reading `req.body` refuses with `413 + * PAYLOAD_TOO_LARGE`, on the same read-time path as the refusals above, so a + * byte door that reads `rawBody()` instead is untouched. A JSON or form body + * with no declared length is read up to the limit and kept; past it, reading + * `req.body` refuses with 413, and `rawBody()` still hands a byte door every + * byte. + * * The message names the failure and never echoes the body. */ import type { Context } from 'hono'; +import { parseBody } from 'hono/utils/body'; +import { RequestBodyTooLarge, requestBodyGuardOf } from './body-limit'; /** * The refusal, as a DECLARED ADR-0112 throw: `status` and a registered `code` @@ -95,7 +107,7 @@ export class RequestBodyRefusal extends Error { export type RequestBodyReading = | { readonly body: unknown; readonly refusal?: undefined } - | { readonly refusal: RequestBodyRefusal }; + | { readonly refusal: RequestBodyRefusal | RequestBodyTooLarge }; /** The refusal tail every message ends with: what the transport did NOT do. */ const NOT_EMPTY = 'It was refused rather than read as an empty body'; @@ -130,17 +142,59 @@ function declaresBody(c: Context): boolean { return c.req.header('transfer-encoding') !== undefined; } +/** + * A JSON or form body with no declared length, read up to the limit from the + * ORIGINAL body and kept (`./body-limit.ts`, `RequestBodyGuard.hold`), so a + * byte door that reads `rawBody()` afterwards still receives every byte. `null` + * when the reading is the plain `c.req` one: a declared length within the + * limit (the guard counts it, and it cannot pass the limit), a body something + * upstream already read, or an app with no guard. + */ +async function heldBody(c: Context): Promise<{ bytes: Uint8Array } | { tooLarge: RequestBodyTooLarge } | null> { + const guard = requestBodyGuardOf(c); + if (!guard || guard.declaresLength || guard.pulled() || c.req.raw.bodyUsed || !guard.original.body) return null; + const held = await guard.hold(); + return held.bytes ? { bytes: held.bytes } : { tooLarge: new RequestBodyTooLarge(guard.limit) }; +} + +/** The 413 refusal when the read that just failed was the guard refusing a body past the limit. */ +function tooLargeIfTripped(c: Context): RequestBodyTooLarge | undefined { + const guard = requestBodyGuardOf(c); + return guard?.tripped() ? new RequestBodyTooLarge(guard.limit) : undefined; +} + export async function readRequestBody(c: Context): Promise { const lowered = (c.req.header('content-type') ?? '').toLowerCase(); + // A declared length over the limit is never read: reading `req.body` + // refuses with 413, and `rawBody()` still serves a byte door, which bounds + // the body by its own limit (`./body-limit.ts`). + const guard = requestBodyGuardOf(c); + if (guard?.declaredOverLimit) return { refusal: new RequestBodyTooLarge(guard.limit) }; + + const mediaType = lowered.split(';')[0]!.trim(); + const isForm = mediaType === 'multipart/form-data' || mediaType === 'application/x-www-form-urlencoded'; + let heldBytes: Uint8Array | undefined; + if (lowered.includes('application/json') || isForm) { + let held: Awaited>; + try { + held = await heldBody(c); + } catch { + return { refusal: new RequestBodyRefusal(UNREADABLE_BODY_MESSAGE) }; + } + if (held && 'tooLarge' in held) return { refusal: held.tooLarge }; + heldBytes = held?.bytes; + } + if (lowered.includes('application/json')) { // `text()` fills the same Hono body cache `json()` did (`json()` is - // `text()` then `JSON.parse`), so `rawBody()` still reads the bytes. + // `text()` then `JSON.parse`), so `rawBody()` still reads the bytes; a + // held body is decoded the way `text()` decodes (UTF-8, a BOM dropped). let text: string; try { - text = await c.req.text(); + text = heldBytes ? new TextDecoder().decode(heldBytes) : await c.req.text(); } catch { - return { refusal: new RequestBodyRefusal(UNREADABLE_BODY_MESSAGE) }; + return { refusal: tooLargeIfTripped(c) ?? new RequestBodyRefusal(UNREADABLE_BODY_MESSAGE) }; } if (text.trim() === '') return { body: {} }; try { @@ -150,12 +204,17 @@ export async function readRequestBody(c: Context): Promise { } } - const mediaType = lowered.split(';')[0]!.trim(); - if (mediaType === 'multipart/form-data' || mediaType === 'application/x-www-form-urlencoded') { + if (isForm) { try { - return { body: await c.req.parseBody() }; + if (!heldBytes) return { body: await c.req.parseBody() }; + const request = new Request(c.req.url, { + method: 'POST', + headers: { 'content-type': c.req.header('content-type') ?? mediaType }, + body: heldBytes as BodyInit, + }); + return { body: await parseBody(request) }; } catch { - return { refusal: new RequestBodyRefusal(malformedFormMessage(mediaType)) }; + return { refusal: tooLargeIfTripped(c) ?? new RequestBodyRefusal(malformedFormMessage(mediaType)) }; } } diff --git a/packages/qa/dogfood/test/request-body-limit-upload-doors.dogfood.test.ts b/packages/qa/dogfood/test/request-body-limit-upload-doors.dogfood.test.ts new file mode 100644 index 00000000000..dfcc1523cea --- /dev/null +++ b/packages/qa/dogfood/test/request-body-limit-upload-doors.dogfood.test.ts @@ -0,0 +1,334 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// The transport's request-body limit (10 MiB by default, +// `@objectstack/plugin-hono-server` `src/body-limit.ts`) bounds what the +// HTTP door reads, not what an upload door accepts: each of the three storage +// byte doors reads `rawBody()` and bounds the file by its own `max_upload_mb`. +// Over a REAL boot under the default limit, a body over 10 MiB still lands +// through the presigned raw PUT, the chunk PUT and the upload-link PUT, while +// a JSON body of the same size to a data route is answered 413. The upload +// link's several-file form is bounded by that door's own form limit (each file +// within `max_upload_mb`, times the files the link takes, plus the form's +// framing), not by the transport's. +// +// Not eligible for the shared showcase project: it boots its own storage root. + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { mkdtempSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { bootStack, type VerifyStack } from '@objectstack/verify'; +import { StorageServicePlugin } from '@objectstack/service-storage'; +import { MCPServerPlugin } from '@objectstack/mcp'; +import { attachmentsFixtureStack, attachmentsFixtureSecurity } from './fixtures/attachments-fixture.js'; + +const MIB = 1024 * 1024; +/** `UPLOAD_LINK_MAX_FILES` in `@objectstack/service-storage`: what a multi-file field's link takes. */ +const LINK_MAX_FILES = 10; +/** The form framing a several-file submit may add beyond its files (`storage-routes.ts`). */ +const FORM_OVERHEAD = 64 * 1024; +/** Over the transport's 10 MiB default, and a whole chunk the chunked door accepts (its floor is 5 MiB). */ +const OVER_DEFAULT = 12 * MIB; + +describe('the request-body limit leaves each upload door its own bound, over a real boot', () => { + let stack: VerifyStack; + let token: string; + + const json = { 'Content-Type': 'application/json' }; + const auth = () => ({ Authorization: `Bearer ${token}` }); + const bytes = (byte: number) => new Uint8Array(OVER_DEFAULT).fill(byte); + const declared = { 'content-length': String(OVER_DEFAULT) }; + + beforeAll(async () => { + const rootDir = mkdtempSync(join(tmpdir(), 'body-limit-upload-doors-')); + stack = await bootStack(attachmentsFixtureStack as never, { + security: attachmentsFixtureSecurity(), + // `bindToSettings:false` keeps the constructor rootDir and leaves + // `max_upload_mb` unset, so each door's own bound is none at all: what + // is measured here is that the transport limit does not stand in for it. + extraPlugins: [ + new StorageServicePlugin({ adapter: 'local', local: { rootDir }, bindToSettings: false }), + new MCPServerPlugin(), + ], + }); + token = await stack.signIn(); + }, 120_000); + + afterAll(async () => { + await stack?.stop(); + }); + + it('CONTROL: a JSON body over the default limit to a data route is answered 413 PAYLOAD_TOO_LARGE', async () => { + const body = JSON.stringify({ name: 'x'.repeat(OVER_DEFAULT) }); + const res = await stack.api('/data/att_case', { + method: 'POST', + headers: { ...json, ...auth(), 'content-length': String(Buffer.byteLength(body)) }, + body, + }); + expect(res.status).toBe(413); + expect(((await res.json()) as any).error.code).toBe('PAYLOAD_TOO_LARGE'); + }); + + it('the presigned raw PUT receives a body over the default limit whole', async () => { + const presign = await stack.api('/storage/upload/presigned', { + method: 'POST', + headers: { ...json, ...auth() }, + body: JSON.stringify({ filename: 'large.bin', mimeType: 'application/octet-stream', size: OVER_DEFAULT, scope: 'attachments' }), + }); + expect(presign.status, await presign.clone().text()).toBe(200); + const { data } = (await presign.json()) as any; + const put = await stack.raw(String(data.uploadUrl).replace(/^https?:\/\/[^/]+/, ''), { + method: 'PUT', + headers: { ...(data.headers ?? { 'content-type': 'application/octet-stream' }), ...declared }, + body: bytes(0x61), + }); + expect(put.status, await put.clone().text()).toBeLessThan(300); + const complete = await stack.api('/storage/upload/complete', { + method: 'POST', + headers: { ...json, ...auth() }, + body: JSON.stringify({ fileId: data.fileId }), + }); + expect(complete.status, await complete.clone().text()).toBe(200); + expect(((await complete.json()) as any).data.size).toBe(OVER_DEFAULT); + }); + + it('the chunk PUT receives a chunk over the default limit whole', async () => { + const init = await stack.api('/storage/upload/chunked', { + method: 'POST', + headers: { ...json, ...auth() }, + body: JSON.stringify({ filename: 'large-chunk.bin', mimeType: 'application/octet-stream', totalSize: OVER_DEFAULT, chunkSize: OVER_DEFAULT }), + }); + expect(init.status, await init.clone().text()).toBe(200); + const { uploadId, resumeToken, totalChunks } = ((await init.json()) as any).data; + expect(totalChunks).toBe(1); + const put = await stack.api(`/storage/upload/chunked/${uploadId}/chunk/0`, { + method: 'PUT', + headers: { ...auth(), 'Content-Type': 'application/octet-stream', 'x-resume-token': resumeToken, ...declared }, + body: bytes(0x62), + }); + expect(put.status, await put.clone().text()).toBe(200); + const progress = await stack.api(`/storage/upload/chunked/${uploadId}/progress`, { headers: auth() }); + expect(progress.status).toBe(200); + expect(((await progress.json()) as any).data.uploadedSize).toBe(OVER_DEFAULT); + }); + + it('the upload-link PUT receives a body over the default limit whole', async () => { + const created = await stack.apiAs(token, 'POST', '/data/att_case', { name: 'body-limit case' }); + expect(created.status, await created.clone().text()).toBeLessThan(300); + const createdBody: any = await created.json(); + const caseId = String(createdBody?.id ?? createdBody?.record?.id ?? createdBody?.data?.id ?? ''); + expect(caseId).not.toBe(''); + const mcp = await stack.api('/mcp', { + method: 'POST', + headers: { ...json, Accept: 'application/json, text/event-stream', ...auth() }, + body: JSON.stringify({ + jsonrpc: '2.0', id: 1, method: 'tools/call', + params: { name: 'create_upload_link', arguments: { objectName: 'att_case', recordId: caseId, attachments: true } }, + }), + }); + expect(mcp.status).toBe(200); + const rpc: any = await mcp.json(); + const minted = JSON.parse(rpc.result?.content?.[0]?.text ?? 'null'); + expect(rpc.result?.isError, JSON.stringify(minted)).not.toBe(true); + const put = await stack.raw(String(minted.url).replace(/^https?:\/\/[^/]+/, ''), { + method: 'PUT', + headers: { 'content-type': 'application/octet-stream', 'x-file-name': 'large-link.bin', ...auth(), ...declared }, + body: bytes(0x63), + }); + const body: any = await put.json(); + expect(put.status, JSON.stringify(body)).toBe(200); + expect(body.data.size).toBe(OVER_DEFAULT); + }); +}); + +/** An object whose `scans` field takes several files, so its upload link takes the several-file form. */ +const SCAN_CLAIM = 'body_limit_scan_claim'; +const scanClaimApp = { + name: 'com.dogfood.body-limit-scan-claim', + type: 'standard' as const, + version: '0.0.0', + optionalDependencies: ['com.objectstack.engine.objectql'], + async init(ctx: any) { + ctx.getService('manifest').register({ + id: 'com.dogfood.body-limit-scan-claim', + name: 'Scan claim', + version: '0.0.0', + type: 'plugin', + scope: 'system', + objects: [{ + name: SCAN_CLAIM, + label: 'Scan Claim', + fields: { + name: { type: 'text', label: 'Name' }, + scans: { type: 'file', label: 'Scans', multiple: true }, + }, + }], + }); + }, + async start() {}, +}; + +/** A request body that counts the bytes the server pulled from it. */ +function countedBody(bytes: Uint8Array, chunk = 256 * 1024) { + const read = { bytes: 0 }; + let offset = 0; + const stream = new ReadableStream({ + pull(controller) { + if (offset >= bytes.byteLength) { + controller.close(); + return; + } + const next = bytes.subarray(offset, offset + chunk); + offset += next.byteLength; + read.bytes += next.byteLength; + controller.enqueue(next); + }, + }, { highWaterMark: 0 }); + return { stream, read }; +} + +describe('the upload link\'s several-file form is bounded by that door\'s own limit, not the request-body limit, over a real boot', () => { + let stack: VerifyStack; + let token: string; + /** `max_upload_mb` saved for this boot: each file within 2 MiB. */ + const MAX_UPLOAD = 2 * MIB; + const FORM_LIMIT = MAX_UPLOAD * LINK_MAX_FILES + FORM_OVERHEAD; + + const json = { 'Content-Type': 'application/json' }; + const auth = () => ({ Authorization: `Bearer ${token}` }); + + beforeAll(async () => { + const rootDir = mkdtempSync(join(tmpdir(), 'body-limit-link-form-')); + stack = await bootStack(attachmentsFixtureStack as never, { + security: attachmentsFixtureSecurity(), + // Bound to the `storage` settings namespace, so `max_upload_mb` is saved below. + extraPlugins: [new StorageServicePlugin({ adapter: 'local', local: { rootDir } }), new MCPServerPlugin(), scanClaimApp], + }); + token = await stack.signIn(); + const save = await stack.raw('/api/settings/storage', { + method: 'PUT', + headers: { ...json, ...auth() }, + body: JSON.stringify({ max_upload_mb: MAX_UPLOAD / MIB }), + }); + expect(save.status, await save.clone().text()).toBe(200); + // The plugin re-reads the namespace on `settings:changed`, after the PUT's answer. + const presign = (size: number) => stack.api('/storage/upload/presigned', { + method: 'POST', + headers: { ...json, ...auth() }, + body: JSON.stringify({ filename: 'probe.bin', mimeType: 'application/octet-stream', size, scope: 'user' }), + }); + let probe = await presign(MAX_UPLOAD + 1); + for (let i = 0; i < 40 && probe.status !== 413; i++) { + await new Promise((resolve) => setTimeout(resolve, 100)); + probe = await presign(MAX_UPLOAD + 1); + } + expect(probe.status, 'the saved max_upload_mb is in force').toBe(413); + }, 120_000); + + afterAll(async () => { + await stack?.stop(); + }); + + /** A link for a new claim's `scans`, as the path the page is served at. */ + async function linkPath(): Promise<{ path: string; claimId: string }> { + const created = await stack.apiAs(token, 'POST', `/data/${SCAN_CLAIM}`, { name: 'scan claim' }); + expect(created.status, await created.clone().text()).toBeLessThan(300); + const createdBody: any = await created.json(); + const claimId = String(createdBody?.id ?? createdBody?.record?.id ?? createdBody?.data?.id ?? ''); + expect(claimId).not.toBe(''); + const mcp = await stack.api('/mcp', { + method: 'POST', + headers: { ...json, Accept: 'application/json, text/event-stream', ...auth() }, + body: JSON.stringify({ + jsonrpc: '2.0', id: 1, method: 'tools/call', + params: { name: 'create_upload_link', arguments: { objectName: SCAN_CLAIM, recordId: claimId, field: 'scans' } }, + }), + }); + expect(mcp.status).toBe(200); + const rpc: any = await mcp.json(); + const minted = JSON.parse(rpc.result?.content?.[0]?.text ?? 'null'); + expect(rpc.result?.isError, JSON.stringify(minted)).not.toBe(true); + return { path: String(minted.url).replace(/^https?:\/\/[^/]+/, ''), claimId }; + } + + /** The page's several-file form, as its bytes and the content type that frames them. */ + async function formOf(sizes: number[]): Promise<{ bytes: Uint8Array; contentType: string }> { + const form = new FormData(); + form.append('count', String(sizes.length)); + sizes.forEach((size, i) => { + form.append(`file${i}`, new Blob([new Uint8Array(size).fill(0x41 + i)], { type: 'application/octet-stream' }), `scan-${i}.bin`); + }); + const encoded = new Response(form); + return { bytes: new Uint8Array(await encoded.arrayBuffer()), contentType: encoded.headers.get('content-type')! }; + } + + const putForm = (path: string, contentType: string, body: BodyInit, extra: Record = {}) => + stack.raw(path, { + method: 'PUT', + headers: { ...auth(), 'content-type': contentType, 'x-upload-link-form': 'several', ...extra }, + body, + duplex: 'half', + } as RequestInit); + + /** Six files of 1.9 MiB: each within `max_upload_mb`, the form over the 10 MiB request-body limit. */ + const OVER_TRANSPORT = Array.from({ length: 6 }, () => Math.floor(1.9 * MIB)); + + it.each([['declared', true], ['not declared', false]])( + 'a form over the request-body limit and within the door\'s own limit lands whole, its length %s', + async (_label, declare) => { + const { path } = await linkPath(); + const { bytes, contentType } = await formOf(OVER_TRANSPORT); + expect(bytes.byteLength).toBeGreaterThan(10 * MIB); + expect(bytes.byteLength).toBeLessThan(FORM_LIMIT); + const res = declare + ? await putForm(path, contentType, bytes, { 'content-length': String(bytes.byteLength) }) + : await putForm(path, contentType, countedBody(bytes).stream); + const body: any = await res.json(); + expect(res.status, JSON.stringify(body)).toBe(200); + expect(body.data.fileIds).toHaveLength(OVER_TRANSPORT.length); + expect(body.data.files.map((file: any) => file.size)).toEqual(OVER_TRANSPORT); + }, + ); + + it('a form that declares more than the door\'s own limit is answered 413 and not read', async () => { + const { path } = await linkPath(); + const declared = FORM_LIMIT + 1; + const { stream, read } = countedBody(new Uint8Array(declared)); + const res = await putForm(path, 'multipart/form-data; boundary=x', stream, { 'content-length': String(declared) }); + const body: any = await res.json(); + expect(res.status, JSON.stringify(body)).toBe(413); + expect(body.error.code).toBe('PAYLOAD_TOO_LARGE'); + expect(body.error.message).toContain(`over the ${FORM_LIMIT} bytes this link's upload can carry`); + expect(read.bytes).toBe(0); + }); + + it('a form with no declared length past the door\'s own limit is answered 413, and the link still takes a form that fits', async () => { + const { path, claimId } = await linkPath(); + const { bytes, contentType } = await formOf(Array.from({ length: 11 }, () => MAX_UPLOAD)); + expect(bytes.byteLength).toBeGreaterThan(FORM_LIMIT); + const res = await putForm(path, contentType, countedBody(bytes).stream); + const body: any = await res.json(); + expect(res.status, JSON.stringify(body)).toBe(413); + expect(body.error.code).toBe('PAYLOAD_TOO_LARGE'); + // Nothing was stored, and the link was not spent. + const fits = await formOf([MIB]); + const again = await putForm(path, fits.contentType, fits.bytes); + expect(again.status, await again.clone().text()).toBe(200); + const row: any = await stack.apiAs(token, 'GET', `/data/${SCAN_CLAIM}/${claimId}`).then((r) => r.json()); + const scans = row?.scans ?? row?.record?.scans ?? row?.data?.scans; + expect(Array.isArray(scans) ? scans : [scans]).toHaveLength(1); + }); + + it('a body that is not the form is still the one file on the same link, read through rawBody()', async () => { + const { path } = await linkPath(); + // A one-file body is any body that is not the form; one file is bounded by `max_upload_mb`. + const res = await stack.raw(path, { + method: 'PUT', + headers: { ...auth(), 'content-type': 'application/octet-stream', 'x-file-name': 'one.bin' }, + body: new Uint8Array(MAX_UPLOAD).fill(0x5a), + }); + const body: any = await res.json(); + expect(res.status, JSON.stringify(body)).toBe(200); + expect(body.data.size).toBe(MAX_UPLOAD); + }); +}); diff --git a/packages/services/service-storage/src/storage-routes.ts b/packages/services/service-storage/src/storage-routes.ts index 1a1ef946bcd..304c6b99771 100644 --- a/packages/services/service-storage/src/storage-routes.ts +++ b/packages/services/service-storage/src/storage-routes.ts @@ -1920,7 +1920,12 @@ export function registerStorageFamily( return; } if (linkFiles !== undefined) { - const uploads = await uploadLinkFormFiles(req.body, linkFiles); + const form = await uploadLinkFormBody(req, formLimit); + if (form.refused) { + sendError(res, UPLOAD_TOO_LARGE_STATUS, UPLOAD_TOO_LARGE_CODE, form.refused, { userMessage: copy.tooLarge }); + return; + } + const uploads = await uploadLinkFormFiles(form.body, linkFiles); if (!Array.isArray(uploads)) { sendError(res, uploads.status, uploads.code, uploads.message, { userMessage: copy.refused(uploads.message) }); return; @@ -2502,6 +2507,59 @@ function isUploadLinkForm(contentType: string | string[] | undefined, marker: st ); } +/** + * Whether a read of `req.body` was refused by the transport's request-body + * limit (`PAYLOAD_TOO_LARGE`), a limit that bounds what the HTTP door reads, not + * what this door accepts. + */ +function isTransportBodyTooLarge(err: unknown): boolean { + return !!err && typeof err === 'object' && (err as { code?: unknown }).code === 'PAYLOAD_TOO_LARGE'; +} + +/** + * The several-file form, bounded by this door's own form limit rather than the + * transport's request-body limit. The form the transport parsed when it fits + * within that limit; when the transport refused it for size, the form's bytes + * read through `rawBody()` (a declared length over this door's limit was + * already refused unread), judged against this door's limit, and parsed here. + * `refused` names why the bytes read are over this door's limit. + */ +async function uploadLinkFormBody( + req: IHttpRequest, + formLimit: number | undefined, +): Promise<{ body: unknown; refused?: undefined } | { body?: undefined; refused: string }> { + try { + return { body: req.body }; + } catch (err) { + if (!isTransportBodyTooLarge(err) || !req.rawBody) throw err; + } + const bytes = await req.rawBody(); + if (formLimit !== undefined && bytes.byteLength > formLimit) { + return { + refused: + `The upload body is ${bytes.byteLength} bytes, over the ${formLimit} bytes this link's upload can carry ` + + '(its files, each within the "Max upload size (MB)" storage setting).', + }; + } + const contentType = req.headers?.['content-type']; + let parsed: FormData; + try { + parsed = await new Response(new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength), { + headers: { 'content-type': String(Array.isArray(contentType) ? contentType[0] : contentType) }, + }).formData(); + } catch { + // Not a readable form: the form checks below refuse it as one that names no files. + return { body: {} }; + } + // A name sent twice is kept as a list, which the form checks refuse. + const body: Record = {}; + for (const [key, value] of parsed.entries()) { + const held = body[key]; + body[key] = held === undefined ? value : Array.isArray(held) ? [...held, value] : [held, value]; + } + return { body }; +} + /** [#32747] A form value that is a file: what a form parser hands for a file part. */ interface FormFilePart { name?: unknown; diff --git a/packages/spec/src/api/error-code-ledger.zod.ts b/packages/spec/src/api/error-code-ledger.zod.ts index 0322ee287ba..d66799ac36f 100644 --- a/packages/spec/src/api/error-code-ledger.zod.ts +++ b/packages/spec/src/api/error-code-ledger.zod.ts @@ -1282,6 +1282,17 @@ export const ERROR_CODE_LEDGER = { '@objectstack/hono': [ 'AUTH_CONFIG_ERROR', // auth service threw while the adapter mounted it ], + '@objectstack/plugin-hono-server': [ + // 413 from the transport's request-body limit (`src/body-limit.ts`): a body + // over the limit (10 MiB by default, `maxRequestBodyBytes` / + // `OS_HTTP_MAX_BODY_BYTES`) is not read past it, on the self-hosted server + // and on `@objectstack/hono`'s `createHonoApp`, which imports the + // refusal (`RequestBodyTooLarge`) and its answer + // (`requestBodyTooLargeAnswer`) from here. Third EMITTER of the code `@objectstack/rest` registers; one + // condition, the request carries more than the door accepts. Provenance, + // not identity (see above). + 'PAYLOAD_TOO_LARGE', + ], '@objectstack/service-messaging': [ 'DELIVERY_NEVER_SENT', // [#8069] terminal delivery row with 0 attempts — a PARKED record of a delivery that could never be prepared, not one that failed. Redelivering it would be a FIRST send, and the row carries no HMAC signature because the secret that would have produced one is exactly what went missing, so it would go out unsigned (#7799). Distinct from DELIVERY_NOT_ELIGIBLE: that one says "wrong state, try when it settles"; this one says "never, fix the configuration instead" // "this delivery row's state does not permit the requested operation" — diff --git a/scripts/check-route-envelope.mjs b/scripts/check-route-envelope.mjs index 9c519fe6db9..7709009b133 100644 --- a/scripts/check-route-envelope.mjs +++ b/scripts/check-route-envelope.mjs @@ -1422,6 +1422,9 @@ const PLUGIN_ROUTE_MODULES = { // `NodeHttpServer` mirrors these bodies byte-for-byte, locked cross-adapter // by `fallback-seam.conformance.test.ts`. 'packages/plugins/plugin-hono-server/src/adapter.ts': {}, + // The request-body limit's 413 answer: `requestBodyTooLargeEnvelope`, the + // declared envelope with the registered `PAYLOAD_TOO_LARGE` code. + 'packages/plugins/plugin-hono-server/src/body-limit.ts': {}, // Converted by #9364: `{ error: 'environment_not_found', message, hostname }` // became the declared envelope with `ENVIRONMENT_NOT_FOUND` in the semantic