fix(bot): reject oversized callback bodies

Reject declared oversized bot callbacks before reading their bodies.
This keeps unauthenticated requests from wasting worker resources.
This commit is contained in:
翅膀 committed 2026-10-23 23:21:15 +08:00
1 parent c641a8c1c5
commit 6535126ae0
4 files changed
+19 -3

No files matched your search

+13
View File
@@ -56,3 +56,16 @@ export function headersFrom(event: H3Event): Record<string, string> {
});
return out;
}
/** Largest body the bot callback routes read (each handler checks it again). */
export const MAX_CALLBACK_BODY = 1024 * 1024;
/**
* A body declared larger than `max` bytes: answered 413 before the route
* reads (and copies) it. Bodies without a declared length are still checked
* by the handler once read.
*/
export function declaresBodyOver(event: H3Event, max = MAX_CALLBACK_BODY): boolean {
const length = Number(event.headers.get("content-length"));
return Number.isFinite(length) && length > max;
}
+2 -1
View File
@@ -1,12 +1,13 @@
import { readRawBody } from "h3";
import { handleInteractionRequest } from "../../lib/drivers/discord/interactions";
import { cfEnv, rawRequest } from "../../lib/cf";
import { cfEnv, declaresBodyOver, rawRequest } from "../../lib/cf";
export default defineEventHandler(async (event) => {
// The raw Request is provided for headers/URL, but nitro consumes its body
// while buffering the payload — rebuild a fresh Request with the body from
// h3's internal buffers so the handler can read it (signature verification
// needs the exact raw bytes).
if (declaresBodyOver(event)) return new Response("Request too large", { status: 413 });
const source = rawRequest(event);
const body = await readRawBody(event, "utf8");
const request = new Request(source.url, {
+2 -1
View File
@@ -1,8 +1,9 @@
import { readRawBody } from "h3";
import { handleFeishuWebhookRequest } from "../../lib/drivers/feishu/updates";
import { cfEnv, rawRequest } from "../../lib/cf";
import { cfEnv, declaresBodyOver, rawRequest } from "../../lib/cf";
export default defineEventHandler(async (event) => {
if (declaresBodyOver(event)) return new Response("Request too large", { status: 413 });
const source = rawRequest(event);
const body = await readRawBody(event, "utf8");
const request = new Request(source.url, {
+2 -1
View File
@@ -1,8 +1,9 @@
import { readRawBody } from "h3";
import { handleTelegramWebhookRequest } from "../../lib/drivers/telegram/updates";
import { cfEnv, rawRequest } from "../../lib/cf";
import { cfEnv, declaresBodyOver, rawRequest } from "../../lib/cf";
export default defineEventHandler(async (event) => {
if (declaresBodyOver(event)) return new Response("Request too large", { status: 413 });
const source = rawRequest(event);
const body = await readRawBody(event, "utf8");
const request = new Request(source.url, {