The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Security: routes that take a file stop reading a body past their limit
Adarshfdcbbf2ab97e
diff --git a/src/app/api/assist/projects/[projectId]/sources/route.ts b/src/app/api/assist/projects/[projectId]/sources/route.tsindex 4ffd8bd7..4041d48f 100644--- a/src/app/api/assist/projects/[projectId]/sources/route.ts+++ b/src/app/api/assist/projects/[projectId]/sources/route.ts@@ -1,9 +1,11 @@import { z } from "zod";import { addSource, ProjectError } from "@/server/assist/projects";-import { gateAsProxy } from "@/server/direct-gate";+import { gateAsProxy, readBodyWithin, readFormWithin } from "@/server/direct-gate";import { contentTypeFor, deleteAsset, saveFile } from "@/server/storage";const MAX_BYTES = 25 * 1024 * 1024;+/** A source sent as JSON: a link, an element or a note of up to 20,000 characters (4 bytes each at most), with room to spare. */+const JSON_MAX_BYTES = 256 * 1024;/** Documents Assist can read (text, Markdown, PDF), plus media it can pass on as inputs. */const ALLOWED = /^(text\/[\w.+-]+|application\/(json|pdf|xml|x-subrip|x-yaml|yaml)|image\/(png|jpeg|webp|gif)|video\/(mp4|webm|quicktime)|audio\/(mpeg|wav|x-wav|ogg|flac|mp4|webm))$/;const TEXT_EXT: Record<string, string> = { md: "text/markdown", markdown: "text/markdown", txt: "text/plain", csv: "text/csv", srt: "application/x-subrip", vtt: "text/vtt", json: "application/json", yml: "application/x-yaml", yaml: "application/x-yaml", pdf: "application/pdf" };@@ -26,7 +28,8 @@ export async function POST(request: Request, ctx: RouteContext<"/api/assist/projconst { projectId } = await ctx.params;try {if ((request.headers.get("content-type") ?? "").startsWith("multipart/form-data")) {- const form = await request.formData().catch(() => null);+ const form = await readFormWithin(request, MAX_BYTES);+ if (form === "too-big") return Response.json({ error: "That file is over 25 MB" }, { status: 413 });const file = form?.get("file");if (!(file instanceof File)) return Response.json({ error: "No file" }, { status: 400 });if (file.size > MAX_BYTES) return Response.json({ error: "That file is over 25 MB" }, { status: 413 });@@ -45,7 +48,14 @@ export async function POST(request: Request, ctx: RouteContext<"/api/assist/projthrow e;}}- const parsed = Json.safeParse(await request.json().catch(() => null));+ // A link, an element or a note: words only (a note is at most 20,000 characters).+ const body = await readBodyWithin(request, JSON_MAX_BYTES);+ if (body === "too-big") return Response.json({ error: "That note is too long" }, { status: 413 });+ let json: unknown = null;+ try {+ json = body ? JSON.parse(body.toString("utf8")) : null;+ } catch {}+ const parsed = Json.safeParse(json);if (!parsed.success) return Response.json({ error: "Add a link, a file, an element or a note" }, { status: 400 });return Response.json(await addSource(projectId, parsed.data), { status: 201 });} catch (e) {diff --git a/src/app/api/assist/skills/upload/route.ts b/src/app/api/assist/skills/upload/route.tsindex e8d76908..1d5e8457 100644--- a/src/app/api/assist/skills/upload/route.ts+++ b/src/app/api/assist/skills/upload/route.ts@@ -1,4 +1,4 @@-import { gateAsProxy } from "@/server/direct-gate";+import { gateAsProxy, readFormWithin } from "@/server/direct-gate";import { importSkill, SkillError } from "@/server/skills";const MAX_BYTES = 5 * 1024 * 1024;@@ -8,10 +8,12 @@ export async function POST(request: Request) {// The proxy doesn't run on this route (a big form): its checks run here.const denied = gateAsProxy(request);if (denied) return denied;- const form = await request.formData().catch(() => null);+ const tooBig = () => Response.json({ error: "That file is over 5 MB — a skill is mostly text; leave large assets out" }, { status: 413 });+ const form = await readFormWithin(request, MAX_BYTES);+ if (form === "too-big") return tooBig();const file = form?.get("file");if (!(file instanceof File)) return Response.json({ error: "Choose a .zip, .skill or SKILL.md file" }, { status: 400 });- if (file.size > MAX_BYTES) return Response.json({ error: "That file is over 5 MB — a skill is mostly text; leave large assets out" }, { status: 413 });+ if (file.size > MAX_BYTES) return tooBig();try {const replace = new URL(request.url).searchParams.get("replace") === "1";const r = importSkill({ name: file.name, data: Buffer.from(await file.arrayBuffer()) }, { replace });diff --git a/src/app/api/explainer/document/route.ts b/src/app/api/explainer/document/route.tsindex b8c4b55b..acb7e437 100644--- a/src/app/api/explainer/document/route.ts+++ b/src/app/api/explainer/document/route.ts@@ -1,4 +1,4 @@-import { gateAsProxy } from "@/server/direct-gate";+import { gateAsProxy, readFormWithin } from "@/server/direct-gate";import { EngineSchema, FacelessError, handle, MAX_DOCUMENT_BYTES, readDocument } from "@/server/faceless";/**@@ -10,7 +10,8 @@ export async function POST(request: Request) {const denied = gateAsProxy(request);if (denied) return denied;return handle(async () => {- const form = await request.formData().catch(() => null);+ const form = await readFormWithin(request, MAX_DOCUMENT_BYTES);+ if (form === "too-big") throw new FacelessError(`That file is over ${MAX_DOCUMENT_BYTES / 1024 / 1024} MB — add the part that matters, or paste its text into the prompt`, 413);const file = form?.get("file");if (!(file instanceof File)) throw new FacelessError("Choose a PDF or a Word file (.docx)");if (file.size > MAX_DOCUMENT_BYTES) throw new FacelessError(`${file.name} is over ${MAX_DOCUMENT_BYTES / 1024 / 1024} MB — add the part that matters, or paste its text into the prompt`, 413);diff --git a/src/app/api/generations/[id]/finish/route.ts b/src/app/api/generations/[id]/finish/route.tsindex dfa612eb..370d1002 100644--- a/src/app/api/generations/[id]/finish/route.ts+++ b/src/app/api/generations/[id]/finish/route.ts@@ -1,8 +1,8 @@import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "@/server/account-files";import { requestAccount } from "@/server/auth";-import { gateAsProxy } from "@/server/direct-gate";+import { gateAsProxy, readFormWithin } from "@/server/direct-gate";import { FinishError, finishOutput } from "@/server/generations";-import { hit, unhit } from "@/server/rate";+import { enter, hit, unhit } from "@/server/rate";const MAX_BYTES = 64 * 1024 * 1024;/** An account's finished picture (its own result: the proxy checks): smaller. */@@ -22,12 +22,21 @@ export async function POST(request: Request, ctx: RouteContext<"/api/generationsconst { id } = await ctx.params;const account = requestAccount(request);const max = account ? ACCOUNT_MAX_BYTES : MAX_BYTES;- if (Number(request.headers.get("content-length") ?? 0) > max + 64 * 1024) return Response.json({ error: `That picture is too large (${max / 2 ** 20} MB max)` }, { status: 413 });- const form = await request.formData().catch(() => null);+ const tooLarge = () => Response.json({ error: `That picture is too large (${max / 2 ** 20} MB max)` }, { status: 413 });+ // An account's pictures are read two at a time at most, each never past its limit (a chunked body included).+ const reading = account ? enter(`finish-now:${account.id}`, 2) : () => {};+ if (!reading) return Response.json({ error: ACCOUNT_MESSAGES.finishBusy }, { status: 429, headers: { "Retry-After": "5", "Cache-Control": "no-store" } });+ let form: FormData | "too-big" | null;+ try {+ form = await readFormWithin(request, max);+ } finally {+ reading();+ }+ if (form === "too-big") return tooLarge();const file = form?.get("file");const index = Number(form?.get("index"));if (!(file instanceof File)) return Response.json({ error: "No file" }, { status: 400 });- if (file.size > max) return Response.json({ error: `That picture is too large (${max / 2 ** 20} MB max)` }, { status: 413 });+ if (file.size > max) return tooLarge();const data = Buffer.from(await file.arrayBuffer());if (file.type !== "image/png" || !data.subarray(0, 8).equals(PNG_MAGIC)) return Response.json({ error: "Finished pictures are PNG images" }, { status: 415 });if (account) {diff --git a/src/app/api/layers/renders/route.ts b/src/app/api/layers/renders/route.tsindex 0e9f66ee..bd7c6d87 100644--- a/src/app/api/layers/renders/route.ts+++ b/src/app/api/layers/renders/route.ts@@ -1,4 +1,4 @@-import { gateAsProxy } from "@/server/direct-gate";+import { gateAsProxy, readFormWithin } from "@/server/direct-gate";import { saveFile } from "@/server/storage";const MAX_BYTES = 64 * 1024 * 1024;@@ -13,7 +13,8 @@ export async function POST(request: Request) {// The proxy doesn't run on this route (a big form): its checks run here.const denied = gateAsProxy(request);if (denied) return denied;- const form = await request.formData().catch(() => null);+ const form = await readFormWithin(request, MAX_BYTES);+ if (form === "too-big") return Response.json({ error: "That render is too large (64 MB max)" }, { status: 413 });const file = form?.get("file");if (!(file instanceof File)) return Response.json({ error: "No file" }, { status: 400 });if (file.size > MAX_BYTES) return Response.json({ error: "That render is too large (64 MB max)" }, { status: 413 });diff --git a/src/server/account-files.ts b/src/server/account-files.tsindex 7eb0662e..41d19d1a 100644--- a/src/server/account-files.ts+++ b/src/server/account-files.ts@@ -69,10 +69,13 @@ export const ACCOUNT_MESSAGES = {uploadsFull: "Your uploads have reached 1 GB. Uploads are removed after 14 days.",filesFull: "Your files have reached 3 GB. Delete some runs to make room.",uploadRate: "That's a lot of uploads at once. Try again in a few minutes.",+ uploadsBusy: "The studio is busy with other uploads. Try again in a moment.",+ uploadStalled: "The upload stopped arriving. Check your connection, then try again.",diskLow: "The studio is short of space right now. Try again later.",activeRuns: "You have 4 runs going. Start the next one when one finishes.",runRate: "That's a lot of runs this hour. Try again later.",finishRate: "That's a lot of finished pictures this hour. Try again later.",+ finishBusy: "Your last pictures are still being saved. Try again in a moment.",outputsCapped: "Runs on your GPU make up to 4 at a time.",bodyTooBig: "That request is too large.",gpuChecks: "Too many checks. Wait a minute.",diff --git a/src/server/direct-gate.ts b/src/server/direct-gate.tsindex ed0cf0a1..487c4630 100644--- a/src/server/direct-gate.ts+++ b/src/server/direct-gate.ts@@ -20,6 +20,50 @@ export function gateAsProxy(request: Request): Response | null {return res.headers.get("x-middleware-next") === "1" ? null : res;}+/** Room for a form's own parts (boundaries, field names, small fields) on top of its file. */+const FORM_SLACK = 64 * 1024;++/**+ * A request body, read with a byte count, for the routes the proxy leaves out (so nothing else caps their bodies). Past+ * `max` bytes the read stops at once and the answer is "too-big": the rest is never held in memory. That holds with or+ * without Content-Length (a chunked body has none). Null when the body can't be read.+ */+export async function readBodyWithin(request: Request, max: number): Promise<Buffer | "too-big" | null> {+ const declared = request.headers.get("content-length");+ if (declared !== null && Number(declared) > max) return "too-big";+ const reader = request.body?.getReader();+ if (!reader) return Buffer.alloc(0);+ const chunks: Uint8Array[] = [];+ let total = 0;+ try {+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ total += value.byteLength;+ if (total > max) {+ reader.cancel().catch(() => {});+ return "too-big";+ }+ chunks.push(value);+ }+ } catch {+ return null;+ }+ return Buffer.concat(chunks, total);+}++/** {@link readBodyWithin} for a form with one file of at most `maxFile` bytes: the form, "too-big", or null (not a form). */+export async function readFormWithin(request: Request, maxFile: number): Promise<FormData | "too-big" | null> {+ const body = await readBodyWithin(request, maxFile + FORM_SLACK);+ if (body === null || body === "too-big") return body;+ try {+ // The bytes as they are (a Buffer is a Uint8Array), not another copy.+ return await new Response(body as unknown as BodyInit, { headers: { "content-type": request.headers.get("content-type") ?? "" } }).formData();+ } catch {+ return null;+ }+}+export function gateDirect(request: Request): { kind: "owner" } | { kind: "account"; account: Account } | Response {const url = new URL(request.url);const host = request.headers.get("host") ?? url.host;diff --git a/tests/account-finish-limits.test.ts b/tests/account-finish-limits.test.tsindex db8d8910..84707bd7 100644--- a/tests/account-finish-limits.test.ts+++ b/tests/account-finish-limits.test.ts@@ -90,6 +90,47 @@ describe("M-5: an account's finished pictures count like its other files", () =>}});+ it("reads at most two of an account's pictures at once", async () => {+ const { enter } = await import("@/server/rate");+ const held = [enter(`finish-now:${a}`, 2), enter(`finish-now:${a}`, 2)];+ try {+ const r = await post(soulRun(a), cookie);+ expect(r.status).toBe(429);+ expect(r.headers.get("retry-after")).toBeTruthy();+ } finally {+ for (const release of held) release?.();+ }+ expect((await post(soulRun(a), cookie)).status).toBe(200);+ });++ it("stops reading an account's chunked picture soon after 32 MB", async () => {+ const chunk = new Uint8Array(2 ** 20);+ const enc = new TextEncoder();+ let pulled = 0;+ let started = false;+ const body = new ReadableStream<Uint8Array>({+ pull(c) {+ if (!started) {+ started = true;+ return c.enqueue(enc.encode('--x\r\nContent-Disposition: form-data; name="file"; filename="big.png"\r\nContent-Type: image/png\r\n\r\n'));+ }+ if (pulled >= 100 * 2 ** 20) {+ c.enqueue(enc.encode("\r\n--x--\r\n"));+ return c.close();+ }+ pulled += chunk.length;+ c.enqueue(chunk);+ },+ });+ const id = soulRun(a);+ const r = await finish.POST(+ new Request(`http://localhost:3000/api/generations/${id}/finish`, { method: "POST", headers: { cookie: `${auth.SESSION_COOKIE}=${cookie}`, "content-type": "multipart/form-data; boundary=x" }, body, duplex: "half" } as RequestInit),+ { params: Promise.resolve({ id }) } as never,+ );+ expect(r.status).toBe(413);+ expect(pulled).toBeLessThanOrEqual(34 * 2 ** 20);+ });+it("has an hourly limit", async () => {for (let i = 0; i < ACCOUNT_LIMITS.finishesPerHour; i++) hit(`finish:${a}`, ACCOUNT_LIMITS.finishesPerHour, 60 * 60_000);const r = await post(soulRun(a), cookie);diff --git a/tests/request-body-limits.test.ts b/tests/request-body-limits.test.tsindex 7aedbfc9..0b3e058f 100644--- a/tests/request-body-limits.test.ts+++ b/tests/request-body-limits.test.ts@@ -85,6 +85,34 @@ describe("M-3: the proxy holds at most a few MB of any request body", () => {for (const r of BIG) expect([400, 404, 413, 415, 422], `${r.name}: owner`).toContain((await r.call(form(r.path, { cookie: owner }))).status);});+ it("each stops reading a body without a length (chunked) once it passes the route's limit", async () => {+ // A real form with one 120 MB file, sent 1 MB at a time as it is asked for: the route must stop asking soon after its own limit.+ const chunk = new Uint8Array(MB);+ const enc = new TextEncoder();+ for (const r of BIG) {+ let pulled = 0;+ let state = 0;+ const body = new ReadableStream<Uint8Array>({+ pull(c) {+ if (state === 0) {+ state = 1;+ return c.enqueue(enc.encode('--x\r\nContent-Disposition: form-data; name="file"; filename="big.png"\r\nContent-Type: image/png\r\n\r\n'));+ }+ if (pulled >= 120 * MB) {+ c.enqueue(enc.encode("\r\n--x--\r\n"));+ return c.close();+ }+ pulled += chunk.length;+ c.enqueue(chunk);+ },+ });+ const headers = { cookie: `${auth.SESSION_COOKIE}=${owner}`, "content-type": "multipart/form-data; boundary=x" };+ const res = await r.call(new Request(`http://localhost:3000${r.path}`, { method: "POST", headers, body, duplex: "half" } as RequestInit));+ expect(res.status, `${r.name}: status`).toBe(413);+ expect(pulled, `${r.name}: bytes read`).toBeLessThanOrEqual(66 * MB);+ }+ });+it("a run request cut short at the proxy's limit says it is too large", async () => {const r = await generations.POST(new Request("http://localhost:3000/api/generations", {