fix(commandboard): add body size limit and handle JSON parse errors (fixes #61) (#62)

This commit is contained in:
FuturMix 2026-06-14 13:51:09 +08:00 committed by GitHub
parent 5cfece3b84
commit 9d2c485071
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -261,7 +261,13 @@ async function route(request: IncomingMessage, response: ServerResponse) {
} }
if (request.method === "POST" && url.pathname === "/api/plugins/c0mpute/jobs/dispatch") { if (request.method === "POST" && url.pathname === "/api/plugins/c0mpute/jobs/dispatch") {
const body = await readJson(request); let body: unknown;
try {
body = await readJson(request);
} catch {
json(response, 400, { error: "Invalid JSON body" });
return;
}
if (!isRecord(body) || typeof body.job_id !== "string") { if (!isRecord(body) || typeof body.job_id !== "string") {
json(response, 422, { error: "Expected job_id" }); json(response, 422, { error: "Expected job_id" });
return; return;
@ -277,7 +283,13 @@ async function route(request: IncomingMessage, response: ServerResponse) {
} }
if (request.method === "POST" && url.pathname === "/api/plugins/c0mpute/quotes") { if (request.method === "POST" && url.pathname === "/api/plugins/c0mpute/quotes") {
const body = await readJson(request); let body: unknown;
try {
body = await readJson(request);
} catch {
json(response, 400, { error: "Invalid JSON body" });
return;
}
if (!isRecord(body) || typeof body.workload !== "string") { if (!isRecord(body) || typeof body.workload !== "string") {
json(response, 422, { error: "Expected workload" }); json(response, 422, { error: "Expected workload" });
return; return;
@ -311,9 +323,16 @@ function text(response: ServerResponse, status: number, contentType: string, bod
response.end(body); response.end(body);
} }
const MAX_BODY_BYTES = 1_048_576; // 1 MB
async function readJson(request: IncomingMessage) { async function readJson(request: IncomingMessage) {
const chunks: Buffer[] = []; const chunks: Buffer[] = [];
let total = 0;
for await (const chunk of request) { for await (const chunk of request) {
total += chunk.length;
if (total > MAX_BODY_BYTES) {
throw new Error("Request body too large");
}
chunks.push(Buffer.from(chunk)); chunks.push(Buffer.from(chunk));
} }