74 lines
2.3 KiB
TypeScript
74 lines
2.3 KiB
TypeScript
import type { MiddlewareHandler } from "hono";
|
|
import { apiError, type ApiErrorEnv } from "./error-envelope.js";
|
|
|
|
export const DEFAULT_JSON_BODY_LIMIT_BYTES = 1_048_576;
|
|
export const DEFAULT_UPLOAD_BODY_LIMIT_BYTES = 10_485_760;
|
|
export const BODY_LIMIT_HEADER = "x-api-body-limit";
|
|
|
|
const WRITE_METHODS = new Set(["POST", "PUT", "PATCH"]);
|
|
|
|
type BodyLimitRule = {
|
|
limitBytes: number;
|
|
pathPrefix?: string;
|
|
};
|
|
|
|
type BodyLimitMiddlewareOptions = {
|
|
jsonLimitBytes?: number;
|
|
uploadLimitBytes?: number;
|
|
uploadPathPrefix?: string;
|
|
};
|
|
|
|
export function createBodyLimitMiddleware(options: BodyLimitMiddlewareOptions = {}): MiddlewareHandler<ApiErrorEnv> {
|
|
const jsonLimitBytes = options.jsonLimitBytes ?? DEFAULT_JSON_BODY_LIMIT_BYTES;
|
|
const uploadLimitBytes = options.uploadLimitBytes ?? DEFAULT_UPLOAD_BODY_LIMIT_BYTES;
|
|
const uploadPathPrefix = options.uploadPathPrefix ?? "/v1/ai/upload";
|
|
|
|
return async (c, next) => {
|
|
const method = c.req.method.toUpperCase();
|
|
if (!WRITE_METHODS.has(method)) {
|
|
await next();
|
|
return;
|
|
}
|
|
|
|
const rule = getBodyLimitRule(c.req.path, { jsonLimitBytes, uploadLimitBytes, uploadPathPrefix });
|
|
const contentLength = parseContentLength(c.req.header("content-length"));
|
|
c.header(BODY_LIMIT_HEADER, String(rule.limitBytes));
|
|
|
|
if (contentLength === null && requestHasBody(c.req.raw)) {
|
|
return apiError(c, 411, "content_length_required", "Write requests with a body require a valid Content-Length header.");
|
|
}
|
|
|
|
if (contentLength !== null && contentLength > rule.limitBytes) {
|
|
return apiError(c, 413, "body_too_large", "Request body is too large.");
|
|
}
|
|
|
|
await next();
|
|
};
|
|
}
|
|
|
|
function getBodyLimitRule(path: string, options: Required<BodyLimitMiddlewareOptions>): BodyLimitRule {
|
|
if (path === options.uploadPathPrefix || path.startsWith(`${options.uploadPathPrefix}/`)) {
|
|
return { limitBytes: options.uploadLimitBytes, pathPrefix: options.uploadPathPrefix };
|
|
}
|
|
|
|
return { limitBytes: options.jsonLimitBytes };
|
|
}
|
|
|
|
function parseContentLength(value: string | undefined): number | null {
|
|
if (!value) {
|
|
return null;
|
|
}
|
|
|
|
const normalized = value.trim();
|
|
if (!/^\d+$/.test(normalized)) {
|
|
return null;
|
|
}
|
|
|
|
const parsed = Number(normalized);
|
|
return Number.isSafeInteger(parsed) ? parsed : null;
|
|
}
|
|
|
|
function requestHasBody(request: Request) {
|
|
return request.body !== null;
|
|
}
|