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: the sign-in proxy holds at most 4 MB of a request body
Adarsh60d67c53e467
diff --git a/next.config.ts b/next.config.tsindex f8f8845d..6c4fdae6 100644--- a/next.config.ts+++ b/next.config.ts@@ -5,10 +5,12 @@ const nextConfig: NextConfig = {cacheComponents: true,partialPrefetching: true,experimental: {- // The sign-in proxy buffers request bodies (10 MB by default). Uploads skip it (src/proxy.ts matcher), so this is- // the largest other body: a Soul finish or a Layers render (64 MB) plus the form overhead. A body over it reaches- // the route cut short, with no error.- proxyClientMaxBodySize: "66mb",+ // The sign-in proxy holds every request body it sees in memory, up to this size, even one it refuses: a small limit+ // keeps many open requests from filling the server's memory. The routes that take a file in a form (uploads, a Soul+ // finish, a Layers render, a skill, an Assist source, an explainer document) skip the proxy and check the asker+ // themselves (src/proxy.ts matcher). Everything else sends JSON: Evolution's 2 MB frame is the largest. A body over+ // the limit reaches the route cut short, with no error (POST /api/generations then says it is too large).+ proxyClientMaxBodySize: "4mb",},async headers() {return [diff --git a/src/app/api/assist/projects/[projectId]/sources/route.ts b/src/app/api/assist/projects/[projectId]/sources/route.tsindex 1b3580b9..4ffd8bd7 100644--- a/src/app/api/assist/projects/[projectId]/sources/route.ts+++ b/src/app/api/assist/projects/[projectId]/sources/route.ts@@ -1,5 +1,6 @@import { z } from "zod";import { addSource, ProjectError } from "@/server/assist/projects";+import { gateAsProxy } from "@/server/direct-gate";import { contentTypeFor, deleteAsset, saveFile } from "@/server/storage";const MAX_BYTES = 25 * 1024 * 1024;@@ -19,6 +20,9 @@ const Json = z.discriminatedUnion("kind", [* (documents and media are stored like uploads). Links are fetched through the guarded fetcher.*/export async function POST(request: Request, ctx: RouteContext<"/api/assist/projects/[projectId]/sources">) {+ // The proxy doesn't run on this route (a big form): its checks run here.+ const denied = gateAsProxy(request);+ if (denied) return denied;const { projectId } = await ctx.params;try {if ((request.headers.get("content-type") ?? "").startsWith("multipart/form-data")) {diff --git a/src/app/api/assist/skills/upload/route.ts b/src/app/api/assist/skills/upload/route.tsindex 796ce3e4..e8d76908 100644--- a/src/app/api/assist/skills/upload/route.ts+++ b/src/app/api/assist/skills/upload/route.ts@@ -1,9 +1,13 @@+import { gateAsProxy } from "@/server/direct-gate";import { importSkill, SkillError } from "@/server/skills";const MAX_BYTES = 5 * 1024 * 1024;/** Add a skill from a .zip / .skill archive or a SKILL.md (multipart "file"; `?replace=1` overwrites your skill of the same name). */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 file = form?.get("file");if (!(file instanceof File)) return Response.json({ error: "Choose a .zip, .skill or SKILL.md file" }, { status: 400 });diff --git a/src/app/api/explainer/document/route.ts b/src/app/api/explainer/document/route.tsindex 76dd637a..b8c4b55b 100644--- a/src/app/api/explainer/document/route.ts+++ b/src/app/api/explainer/document/route.ts@@ -1,3 +1,4 @@+import { gateAsProxy } from "@/server/direct-gate";import { EngineSchema, FacelessError, handle, MAX_DOCUMENT_BYTES, readDocument } from "@/server/faceless";/**@@ -5,6 +6,9 @@ import { EngineSchema, FacelessError, handle, MAX_DOCUMENT_BYTES, readDocument }* document is longer than the script writer reads, summarised. The file itself isn't kept.*/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;return handle(async () => {const form = await request.formData().catch(() => null);const file = form?.get("file");diff --git a/src/app/api/generations/[id]/finish/route.ts b/src/app/api/generations/[id]/finish/route.tsindex 00f3b1b5..42a7bcfb 100644--- a/src/app/api/generations/[id]/finish/route.ts+++ b/src/app/api/generations/[id]/finish/route.ts@@ -1,4 +1,5 @@import { requestAccount } from "@/server/auth";+import { gateAsProxy } from "@/server/direct-gate";import { FinishError, finishOutput } from "@/server/generations";const MAX_BYTES = 64 * 1024 * 1024;@@ -12,6 +13,9 @@ const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);* its own (through the generation).*/export async function POST(request: Request, ctx: RouteContext<"/api/generations/[id]/finish">) {+ // The proxy doesn't run on this route (a big form): its checks run here (an account: only its own run).+ const denied = gateAsProxy(request);+ if (denied) return denied;const { id } = await ctx.params;const max = requestAccount(request) ? 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 });diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.tsindex 0f60ef9b..67847c72 100644--- a/src/app/api/generations/route.ts+++ b/src/app/api/generations/route.ts@@ -38,6 +38,10 @@ function activeRuns(accountId: string): number {return r.n;}+/** What the sign-in proxy passes on of a request body (next.config.ts proxyClientMaxBodySize). */+const PROXY_BODY_BYTES = 4 * 1024 * 1024;+const BODY_TOO_BIG = "That request is over 4 MB. Upload pictures and clips first (POST /api/uploads), then send their /api/files/ paths.";+const refuse = (status: number, error: string, extra: Record<string, unknown> = {}, headers: Record<string, string> = {}) =>Response.json({ error, ...extra }, { status, headers: { "Cache-Control": "no-store", ...headers } });@@ -56,7 +60,10 @@ export async function POST(request: Request) {let body: unknown = null;try {body = JSON.parse(text);- } catch {}+ } catch {+ // The sign-in proxy passes on the first 4 MB of a body (next.config.ts): a bigger one arrives cut short.+ if (Number(request.headers.get("content-length") ?? 0) > PROXY_BODY_BYTES) return refuse(413, BODY_TOO_BIG);+ }const parsed = GenerationRequestSchema.safeParse(body);if (!parsed.success) {return Response.json({ error: parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ") }, { status: 400 });diff --git a/src/app/api/layers/renders/route.ts b/src/app/api/layers/renders/route.tsindex 84fa6f31..0e9f66ee 100644--- a/src/app/api/layers/renders/route.ts+++ b/src/app/api/layers/renders/route.ts@@ -1,3 +1,4 @@+import { gateAsProxy } from "@/server/direct-gate";import { saveFile } from "@/server/storage";const MAX_BYTES = 64 * 1024 * 1024;@@ -9,6 +10,9 @@ const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);* stays out of the Library's Uploads and the pickers; projects that use it keep it (ASSET_REFS).*/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 file = form?.get("file");if (!(file instanceof File)) return Response.json({ error: "No file" }, { status: 400 });diff --git a/src/proxy.ts b/src/proxy.tsindex 4fedea36..502485ef 100644--- a/src/proxy.ts+++ b/src/proxy.ts@@ -219,7 +219,10 @@ export function proxy(request: NextRequest) {export const config = {// Everything except build assets and the public folder's own files: the favicon and app icons,// the demo samples, the preset covers, vendored scripts (the 3D viewer's meshopt decoder) and the- // SVGs at the root. Generated SVGs under /api/files stay behind sign-in. /api/uploads makes the same- // checks itself (src/server/direct-gate.ts): the proxy would hold the whole file in memory first.- matcher: ["/((?!_next/static|_next/image|favicon\\.ico$|apple-icon\\.png$|samples/|previews/|vendor/|api/uploads$|[^/]+\\.svg$).*)"],+ // SVGs at the root. Generated SVGs under /api/files stay behind sign-in. The routes that take a file in a form+ // (/api/uploads, a Soul finish, a Layers render, a skill upload, an Assist source, an explainer document) make the+ // same checks themselves (src/server/direct-gate.ts): the proxy would hold the whole file in memory first.+ matcher: [+ "/((?!_next/static|_next/image|favicon\\.ico$|apple-icon\\.png$|samples/|previews/|vendor/|api/uploads$|api/generations/[^/]+/finish$|api/layers/renders$|api/assist/skills/upload$|api/assist/projects/[^/]+/sources$|api/explainer/document$|[^/]+\\.svg$).*)",+ ],};diff --git a/src/server/direct-gate.ts b/src/server/direct-gate.tsindex 4f4d87a3..ed0cf0a1 100644--- a/src/server/direct-gate.ts+++ b/src/server/direct-gate.ts@@ -1,5 +1,7 @@import "server-only";+import { NextRequest } from "next/server";import { GUEST_HEADER, GUEST_RUN_MESSAGE } from "@/lib/guest-access";+import { proxy } from "@/proxy";import { authEnabled, crossSite, hostAllowed, publicSignup, requestViewer, type Account } from "./auth";/**@@ -8,6 +10,16 @@ import { authEnabled, crossSite, hostAllowed, publicSignup, requestViewer, type* install answers (without a password), a request from this site, then who is asking. Returns the viewer, or the* answer the proxy would have given.*/+/**+ * The proxy's whole answer, for a route the proxy's matcher leaves out because it takes a file in a form (src/proxy.ts+ * config): the proxy runs here on the request's address, method and headers (never its body), so every rule it has+ * applies, the same way. Null when the proxy would let the request through; else its answer.+ */+export function gateAsProxy(request: Request): Response | null {+ const res = proxy(new NextRequest(request.url, { method: request.method, headers: request.headers }));+ return res.headers.get("x-middleware-next") === "1" ? null : res;+}+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/request-body-limits.test.ts b/tests/request-body-limits.test.tsnew file mode 100644index 00000000..7aedbfc9--- /dev/null+++ b/tests/request-body-limits.test.ts@@ -0,0 +1,99 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-bodies-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9";+process.env.FUOBE_PUBLIC_SIGNUP = "1";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_TRUST_PROXY;++const auth = await import("@/server/auth");+const { config } = await import("@/proxy");+const nextConfig = (await import("../next.config")).default;+const finish = await import("@/app/api/generations/[id]/finish/route");+const renders = await import("@/app/api/layers/renders/route");+const skillsUpload = await import("@/app/api/assist/skills/upload/route");+const sources = await import("@/app/api/assist/projects/[projectId]/sources/route");+const explainerDoc = await import("@/app/api/explainer/document/route");+const generations = await import("@/app/api/generations/route");++let owner = "";+let account = "";+beforeAll(() => {+ auth.setPassword("install password");+ owner = auth.createSession().value;+ account = auth.createSession(auth.createAccount("[email protected]", "long enough").id).value;+});+afterEach(() => delete process.env.FUOBE_ALLOWED_ORIGINS);+afterAll(() => {+ try {+ fs.rmSync(dir, { recursive: true, force: true });+ } catch {}+});++const MB = 2 ** 20;+const bytes = (v: string | number | undefined) => {+ const m = /^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb)$/i.exec(String(v ?? "10mb"));+ if (!m) return Number(v);+ return Number(m[1]) * { b: 1, kb: 2 ** 10, mb: MB, gb: 2 ** 30 }[m[2].toLowerCase() as "b" | "kb" | "mb" | "gb"];+};++/** The routes that take a big body (a file in a form): the proxy leaves them out and they check the asker themselves. */+const BIG = [+ { name: "finish", path: "/api/generations/g1/finish", call: (r: Request) => finish.POST(r, { params: Promise.resolve({ id: "g1" }) } as never) },+ { name: "layer renders", path: "/api/layers/renders", call: (r: Request) => renders.POST(r) },+ { name: "skill upload", path: "/api/assist/skills/upload", call: (r: Request) => skillsUpload.POST(r) },+ { name: "Assist sources", path: "/api/assist/projects/p1/sources", call: (r: Request) => sources.POST(r, { params: Promise.resolve({ projectId: "p1" }) } as never) },+ { name: "explainer document", path: "/api/explainer/document", call: (r: Request) => explainerDoc.POST(r) },+];++function form(pathname: string, init: { cookie?: string; headers?: Record<string, string> } = {}) {+ const body = new FormData();+ body.set("file", new File([Buffer.from("not a png")], "x.png", { type: "image/png" }));+ return new Request(`http://localhost:3000${pathname}`, { method: "POST", headers: { ...(init.cookie && { cookie: `${auth.SESSION_COOKIE}=${init.cookie}` }), ...init.headers }, body });+}++describe("M-3: the proxy holds at most a few MB of any request body", () => {+ it("buffers 4 MB at most", () => {+ expect(bytes(nextConfig.experimental?.proxyClientMaxBodySize)).toBeLessThanOrEqual(4 * MB);+ // Still more than the largest JSON body a page sends (Evolution's 2 MB frame).+ expect(bytes(nextConfig.experimental?.proxyClientMaxBodySize)).toBeGreaterThan(2 * MB + 64 * 1024);+ });++ it("leaves out only the routes that take a file in a form", () => {+ const matches = (p: string) => new RegExp(`^${config.matcher[0]}$`).test(p);+ for (const r of BIG) expect(matches(r.path), r.path).toBe(false);+ for (const p of ["/api/generations", "/api/generations/g1", "/api/generations/g1/cancel", "/api/layers", "/api/layers/abc", "/api/assist/skills", "/api/assist/projects/p1", "/api/assist/projects/p1/sources/s1", "/api/explainer"]) {+ expect(matches(p), p).toBe(true);+ }+ });++ it("each of those routes refuses a guest, an account and another website as the proxy would", async () => {+ for (const r of BIG) {+ expect((await r.call(form(r.path))).status, `${r.name}: guest`).toBe(401);+ expect((await r.call(form(r.path, { cookie: owner, headers: { origin: "http://evil.example" } }))).status, `${r.name}: cross-site`).toBe(403);+ }+ // An account: only its own run's finish passes the proxy's rules, and "g1" isn't its own.+ for (const r of BIG) expect((await r.call(form(r.path, { cookie: account }))).status, `${r.name}: account`).toBe(403);+ });++ it("each lets the owner through to the route's own checks", async () => {+ 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("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", {+ method: "POST",+ headers: { cookie: `${auth.SESSION_COOKIE}=${owner}`, "content-type": "application/json", "content-length": String(5 * MB) },+ body: `{"modelId":"oss-z-image-turbo","prompt":"x","inputs":{"images":["data:image/png;base64,AAAA`,+ }),+ );+ expect(r.status).toBe(413);+ expect((await r.json()).error).toMatch(/upload/i);+ });+});