Skip to content

Commit 799f8e1

Browse files
committed
Respect the max content length by getting the length of the body
1 parent 8503cea commit 799f8e1

File tree

1 file changed

+40
-1
lines changed

1 file changed

+40
-1
lines changed

apps/webapp/app/routes/api.v1.waitpoints.http-callback.$waitpointFriendlyId.callback.ts

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
import { WaitpointId } from "@trigger.dev/core/v3/isomorphic";
88
import { z } from "zod";
99
import { $replica } from "~/db.server";
10+
import { env } from "~/env.server";
1011
import { logger } from "~/services/logger.server";
1112
import { engine } from "~/v3/runEngine.server";
1213

@@ -19,6 +20,11 @@ export async function action({ request, params }: ActionFunctionArgs) {
1920
return json({ error: "Method not allowed" }, { status: 405, headers: { Allow: "POST" } });
2021
}
2122

23+
const contentLength = request.headers.get("content-length");
24+
if (contentLength && parseInt(contentLength) > env.TASK_PAYLOAD_MAXIMUM_SIZE) {
25+
return json({ error: "Request body too large" }, { status: 413 });
26+
}
27+
2228
const { waitpointFriendlyId } = paramsSchema.parse(params);
2329
const waitpointId = WaitpointId.toId(waitpointFriendlyId);
2430

@@ -40,7 +46,16 @@ export async function action({ request, params }: ActionFunctionArgs) {
4046
});
4147
}
4248

43-
const body = await request.json();
49+
let body;
50+
try {
51+
body = await readJsonWithLimit(request, env.TASK_PAYLOAD_MAXIMUM_SIZE);
52+
} catch (e) {
53+
return json({ error: "Request body too large" }, { status: 413 });
54+
}
55+
56+
if (!body) {
57+
body = {};
58+
}
4459

4560
const stringifiedData = await stringifyIO(body);
4661
const finalData = await conditionallyExportPacket(
@@ -66,3 +81,27 @@ export async function action({ request, params }: ActionFunctionArgs) {
6681
throw json({ error: "Failed to complete waitpoint token" }, { status: 500 });
6782
}
6883
}
84+
85+
async function readJsonWithLimit(request: Request, maxSize: number) {
86+
const reader = request.body?.getReader();
87+
if (!reader) throw new Error("No body");
88+
let received = 0;
89+
let chunks: Uint8Array[] = [];
90+
while (true) {
91+
const { done, value } = await reader.read();
92+
if (done) break;
93+
received += value.length;
94+
if (received > maxSize) {
95+
throw new Error("Request body too large");
96+
}
97+
chunks.push(value);
98+
}
99+
const full = new Uint8Array(received);
100+
let offset = 0;
101+
for (const chunk of chunks) {
102+
full.set(chunk, offset);
103+
offset += chunk.length;
104+
}
105+
const text = new TextDecoder().decode(full);
106+
return JSON.parse(text);
107+
}

0 commit comments

Comments
 (0)