Files
platform/src/servers/_middlewares/body-parser.ts
T
brunorezioandClaude Opus 5 c13875cef8 return 400 for an unparseable body, and cover origin validation
bodyParser caught parse failures and did nothing — the throw was commented out
and `body` was never set, so handlers destructured undefined and the client got
a 500 for a malformed request. Throw BAD_REQUEST instead.

Also adds the regression tests for the Host suffix match fixed in 2ca850c.

Verified against a running server: malformed JSON now 400, valid credentials
path still 401, spoofed Host still 403.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 23:30:20 +01:00

35 lines
1.2 KiB
TypeScript

import type { MiddlewareHandler } from 'hono';
import * as errors from '../custom-errors';
export const bodyParser: () => MiddlewareHandler = () => async (ctx, next) => {
if (!['POST', 'PUT', 'PATCH'].includes(ctx.req.method.toUpperCase())) {
ctx.set('body', {});
return next();
}
const contentType = ctx.req.header('Content-Type') || '';
try {
if (contentType.includes('application/json')) {
const text = await ctx.req.text();
const body = text ? JSON.parse(text) : {};
ctx.set('body', body);
} else if (contentType.includes('application/x-www-form-urlencoded')) {
const body = await ctx.req.parseBody();
ctx.set('body', body);
} else if (contentType.includes('multipart/form-data')) {
const body = await ctx.req.parseBody({ all: true });
ctx.set('body', body);
} else {
// No recognized content type, set empty body
ctx.set('body', {});
}
} catch {
// Previously swallowed, which left `body` unset — handlers then destructured undefined and the
// client got a 500 for what is squarely a malformed request.
throw errors.BAD_REQUEST('Invalid request body');
}
return next();
};