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
Worker results: keep SVG and splat files, check whole files before saving
Adarshef11b0454d0f
diff --git a/src/app/api/gpu/computer/tasks/[id]/outputs/[n]/route.ts b/src/app/api/gpu/computer/tasks/[id]/outputs/[n]/route.tsindex b262ba3b..76a97f29 100644--- a/src/app/api/gpu/computer/tasks/[id]/outputs/[n]/route.ts+++ b/src/app/api/gpu/computer/tasks/[id]/outputs/[n]/route.ts@@ -2,9 +2,9 @@ import fs from "node:fs";import { connection } from "next/server";import { RELAY_LIMITS } from "@/lib/relay";import { gateAsProxy } from "@/server/direct-gate";-import { callerKey, isUtf8File, outputType, principalOf, rateOf, relayAnswer } from "@/server/computer/http";+import { callerKey, checkWholeOutput, outputType, principalOf, rateOf, relayAnswer } from "@/server/computer/http";import { glbFileSelfContained } from "@/server/computer/finish";-import { failTask, getTask, leased, outputFile, outputStatus, receivePart, RelayError, SNIFF_BYTES, wantedOf, type TaskRow } from "@/server/computer/tasks";+import { failTask, getTask, leased, outputStatus, receivePart, RelayError, SNIFF_BYTES, type TaskRow } from "@/server/computer/tasks";import { enter } from "@/server/rate";/** Nothing arriving for this long ends a part. */@@ -91,21 +91,16 @@ export async function PUT(request: Request, ctx: RouteContext<"/api/gpu/computertry {const owner = t.principal === "owner";// An account's 3D model on the workers (its GPU job's model, or a finishing job's web GLB, src/lib/finish-ticket.ts):- // a binary glTF only, whose every buffer and picture is inside the file.+ // a binary glTF whose every buffer and picture is inside the file, or a splat.const glb = !owner && !!t.pools;- const r = await receivePart(t, n, { offset, total, length }, (file, append) => writeBody(request, file, append, length), (head, w) => outputType(head, w, owner, { glb }));- // A text result is UTF-8 through to its end.- const w = wantedOf(t).find((x) => x.n === n);- if (r.done && glb && w?.kind === "model3d" && !glbFileSelfContained(outputFile(t.id, n))) {- fs.rmSync(outputFile(t.id, n), { force: true });- failTask(getTask(principal, t.id) ?? t, "Couldn't save a result from your ComfyUI: it isn't a 3D model.");- return no(415, "That isn't a 3D model.");- }- if (r.done && w?.kind === "text" && !isUtf8File(outputFile(t.id, n))) {- fs.rmSync(outputFile(t.id, n), { force: true });- failTask(getTask(principal, t.id) ?? t, "Couldn't save a result from your ComfyUI: it isn't text.");- return no(415, "That isn't text.");- }+ const r = await receivePart(+ t,+ n,+ { offset, total, length },+ (file, append) => writeBody(request, file, append, length),+ (head, w) => outputType(head, w, owner, { glb }),+ (file, w, type) => checkWholeOutput(file, w, type, glb ? glbFileSelfContained : undefined),+ );return Response.json({ received: r.bytes, total: r.total, done: r.done }, { headers: { "Cache-Control": "no-store" } });} catch (e) {if (e instanceof RelayError && e.extra.fail) {diff --git a/src/server/computer/http.ts b/src/server/computer/http.tsindex c6d49d4c..2c14ab22 100644--- a/src/server/computer/http.ts+++ b/src/server/computer/http.ts@@ -1,5 +1,6 @@import "server-only";import fs from "node:fs";+import zlib from "node:zlib";import { CONNECT_GPU_HEADER, CONNECT_GPU_MESSAGE, GUEST_HEADER, GUEST_RUN_MESSAGE } from "@/lib/guest-access";import type { WantedFile } from "@/lib/relay";import { sniffMedia } from "@/lib/sniff";@@ -102,20 +103,32 @@ export function relayAnswer(e: unknown): Response {const KIND_WORDS: Record<WantedFile["kind"], string> = { image: "a picture", video: "a clip", audio: "sound", text: "text", model3d: "a 3D model", frame: "an EXR frame" };+const notWhatWasAsked = (w: WantedFile) => `Couldn't save a result from your ComfyUI: it isn't ${KIND_WORDS[w.kind] ?? "what this run makes"}.`;++/** An SVG's first bytes: a byte order mark and white space, then its XML declaration, a comment or its <svg> tag. */+const SVG_HEAD = /^?\s*(<\?xml[\s?]|<!--|<svg[\s>/])/;+/** What a kept SVG never holds: scripts, event handlers, a page inside it, entities. */+const SVG_ACTIVE = /<script\b|<foreignObject\b|<!ENTITY|\son[a-z]+\s*=|javascript:/i;+const SVG_MAX_BYTES = 64 * 2 ** 20;+/** A Niantic splat's header, inside its gzip: "NGSP" (little-endian). */+const SPZ_MAGIC = 0x5053474e;+/** A text result's type, by its name. */const textType = (name: string, owner: boolean) => (/\.srt$/i.test(name) ? "application/x-subrip" : /\.vtt$/i.test(name) ? "text/vtt" : owner && /\.json$/i.test(name) ? "application/json" : "text/plain");/*** What a result from someone's ComfyUI is, from its first bytes (as an upload's type is: lib/sniff.ts), and whether it* is what the server asked for. Never a page or a script: a picture that is really HTML is refused. Throws the words.- * A 3D model comes only from the owner's own jobs, or as a binary glTF when `o.glb` (a run on the workers whose 3D- * finish runs on a worker: the route checks the whole file's parts once it has arrived).+ * A 3D model comes only from the owner's own jobs, or as a binary glTF or a splat (.spz) when `o.glb` (an account's+ * run on the workers). An SVG or a splat is taken only where the server asked for one by name, and checkWholeOutput+ * reads the whole file once it has arrived.*/export function outputType(head: Buffer, w: WantedFile, owner: boolean, o: { glb?: boolean } = {}): string {const s = head.length >= 4 ? sniffMedia(head, undefined, { gif: true }) : null;switch (w.kind) {case "image":if (s?.kind === "image") return s.contentType;+ if (/\.svg$/i.test(w.filename) && !head.includes(0) && SVG_HEAD.test(head.toString("utf8"))) return "image/svg+xml";break;case "video":// VideoHelperSuite also saves animations as GIF or WebP.@@ -135,9 +148,63 @@ export function outputType(head: Buffer, w: WantedFile, owner: boolean, o: { glbcase "model3d":if ((owner || o.glb) && head.subarray(0, 4).toString("latin1") === "glTF") return "model/gltf-binary";if (owner && /^ply\r?\n/.test(head.subarray(0, 8).toString("latin1"))) return "model/ply";+ if ((owner || o.glb) && /\.spz$/i.test(w.filename) && head[0] === 0x1f && head[1] === 0x8b && head[2] === 8) return "model/x-spz";break;}- throw new Error(`Couldn't save a result from your ComfyUI: it isn't ${KIND_WORDS[w.kind] ?? "what this run makes"}.`);+ throw new Error(notWhatWasAsked(w));+}++/**+ * A whole result, once it has all arrived (outputType read only its first bytes): text is UTF-8 to its end, an SVG and+ * a splat are real ones, and a binary glTF passes `glb` when given. Throws the words.+ */+export function checkWholeOutput(file: string, w: WantedFile, contentType: string | undefined, glb?: (file: string) => boolean): void {+ const ok =+ w.kind === "text"+ ? isUtf8File(file)+ : contentType === "image/svg+xml"+ ? isSvgFile(file)+ : contentType === "model/x-spz"+ ? isSpzFile(file)+ : contentType === "model/gltf-binary" && glb+ ? glb(file)+ : true;+ if (!ok) throw new Error(notWhatWasAsked(w));+}++/**+ * A real SVG: UTF-8, its root an <svg> in the SVG namespace after at most an XML declaration, comments and a DOCTYPE+ * with no internal subset, closed at its end, with nothing active in it (SVG_ACTIVE).+ */+export function isSvgFile(file: string): boolean {+ try {+ if (fs.statSync(file).size > SVG_MAX_BYTES) return false;+ const text = new TextDecoder("utf-8", { fatal: true }).decode(fs.readFileSync(file));+ const body = text.replace(/^(?:\s|<\?xml[^>]*\?>|<!--[\s\S]*?-->|<!DOCTYPE\s+svg\b[^[>]*>)*/, "");+ const root = /^<svg\b[^>]*>/.exec(body)?.[0];+ return !!root && /\sxmlns\s*=\s*["']http:\/\/www\.w3\.org\/2000\/svg["']/.test(root) && /<\/svg\s*>\s*$/.test(body) && !SVG_ACTIVE.test(body);+ } catch {+ return false;+ }+}++/** A real splat (.spz): gzip, and inside it the header: "NGSP", version 1 to 3, at least one point, SH degree 0 to 3. */+export function isSpzFile(file: string): boolean {+ let fd: number | null = null;+ try {+ fd = fs.openSync(file, "r");+ const start = Buffer.alloc(4096);+ const got = fs.readSync(fd, start, 0, start.length, 0);+ // The first part of the stream is enough for the header (the rest may not have been read).+ const raw = zlib.gunzipSync(start.subarray(0, got), { finishFlush: zlib.constants.Z_SYNC_FLUSH, maxOutputLength: 8 * 2 ** 20 });+ if (raw.length < 16 || raw.readUInt32LE(0) !== SPZ_MAGIC) return false;+ const version = raw.readUInt32LE(4);+ return version >= 1 && version <= 3 && raw.readUInt32LE(8) > 0 && raw[12] <= 3;+ } catch {+ return false;+ } finally {+ if (fd !== null) fs.closeSync(fd);+ }}/** A whole text result is UTF-8 (checked once it has all arrived). */diff --git a/src/server/computer/tasks.ts b/src/server/computer/tasks.tsindex 3fdfce5d..338b5792 100644--- a/src/server/computer/tasks.ts+++ b/src/server/computer/tasks.ts@@ -994,7 +994,8 @@ export const SNIFF_BYTES = 64;/*** Take part of a wanted output: only while collecting, only a file the server asked for, at exactly the offset already* received, never past its size limit, and only once (a finished file can't be sent again). `check` reads the first part- * and says what the file is (or throws); `write` appends the part.+ * and says what the file is (or throws); `whole` reads the whole file once it has arrived, before it counts as saved+ * (or throws); `write` appends the part.*/export async function receivePart(t: TaskRow,@@ -1002,6 +1003,7 @@ export async function receivePart(o: { offset: number; total: number; length: number },write: (file: string, append: boolean) => Promise<{ bytes: number; head: Buffer }>,check: (head: Buffer, w: WantedFile, total: number) => string,+ whole?: (file: string, w: WantedFile, contentType: string | undefined) => void,): Promise<Received> {if (t.state !== "collecting") throw new RelayError(409, "This run isn't saving results now");const wanted = json<WantedFile[]>(t.wanted_json, []).find((w) => w.n === n);@@ -1040,7 +1042,15 @@ export async function receivePart(}const bytes = o.offset + got.bytes;const done = bytes === o.total;- if (done) fs.renameSync(part, file);+ if (done) {+ try {+ whole?.(part, wanted, contentType);+ } catch (e) {+ fs.rmSync(part, { force: true });+ throw new RelayError(415, (e as Error).message, { fail: true });+ }+ fs.renameSync(part, file);+ }const fresh = taskById(t.id);const list = json<Received[]>(fresh?.received_json ?? null, all).map((r) => (r.n === n ? { n, bytes, total: o.total, done, ...(contentType && { contentType }) } : r));setTask(t.id, { received_json: JSON.stringify(list), device_seen_at: Date.now() });diff --git a/tests/computer-security.test.ts b/tests/computer-security.test.tsindex 8eb9ac59..73ea5262 100644--- a/tests/computer-security.test.ts+++ b/tests/computer-security.test.ts@@ -1,5 +1,6 @@import fs from "node:fs";import path from "node:path";+import zlib from "node:zlib";import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import { FAKE_PNG } from "./helpers/fake-local-comfy";import { loadRoutes, type ComputerRoutes } from "./helpers/computer-tab";@@ -123,13 +124,13 @@ async function claimed(who: "a" | "b" | "owner", device = DEVICE): Promise<{ id:return { id: task.id, lease: task.lease, promptId: task.promptId };}-/** A claimed job of A's that ComfyUI finished with these outputs: what the server now wants uploaded. */-async function collecting(outputs: Record<string, unknown>, graph = SAVE) {- const t = waitingTask(`acct:${a}`, graph);- const c = await claimed("a");+/** A claimed job of A's (or the owner's) that ComfyUI finished with these outputs: what the server now wants uploaded. */+async function collecting(outputs: Record<string, unknown>, graph = SAVE, who: "a" | "owner" = "a") {+ const t = waitingTask(who === "owner" ? "owner" : `acct:${a}`, graph);+ const c = await claimed(who);expect(c.id).toBe(t.id);- expect((await call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, { headers: { "x-fuobe-lease": c.lease }, body: { event: "sent", promptId: c.promptId } })).status).toBe(200);- const fin = await call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, {+ expect((await call(who, "POST", `/api/gpu/computer/tasks/${c.id}/report`, { headers: { "x-fuobe-lease": c.lease }, body: { event: "sent", promptId: c.promptId } })).status).toBe(200);+ const fin = await call(who, "POST", `/api/gpu/computer/tasks/${c.id}/report`, {headers: { "x-fuobe-lease": c.lease },body: { event: "finished", entry: { status: { status_str: "success", completed: true }, outputs } },});@@ -137,6 +138,22 @@ async function collecting(outputs: Record<string, unknown>, graph = SAVE) {return { ...c, generationId: t.generationId, answer: (await fin.json()) as { wanted?: { n: number; kind: string; maxBytes: number }[]; state?: string } };}+/** An SVG as VTracer writes it (what ComfyUI's SVG save node keeps, its <metadata> taken out by the worker). */+const VTRACER_SVG = Buffer.from(+ `<?xml version="1.0" encoding="UTF-8"?>\n<!-- Generator: visioncortex VTracer 0.6.4 -->\n<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="4" height="4">\n<path d="M0 0 C1 1 2 2 4 4 Z" fill="#336699" transform="translate(0,0)"/>\n</svg>\n`,+);+const PLY = "ply\nformat binary_little_endian 1.0\n";++/** A Niantic splat (.spz) as ComfyUI writes it: gzip, its header "NGSP", version 2, the points, then their arrays. */+function spz(version = 2, points = 3): Buffer {+ const head = Buffer.alloc(16);+ head.writeUInt32LE(0x5053474e, 0);+ head.writeUInt32LE(version, 4);+ head.writeUInt32LE(points, 8);+ head[13] = 12;+ return zlib.gzipSync(Buffer.concat([head, Buffer.alloc(points * 20, 7)]));+}+const ONE_PNG = { "9": { images: [{ filename: "x_00001_.png", subfolder: "fuobe", type: "output" }] } };const put = (who: Who, id: string, n: number, lease: string, data: Buffer, offset = 0, total = data.length, headers: Record<string, string> = {}) =>call(who, "PUT", `/api/gpu/computer/tasks/${id}/outputs/${n}?offset=${offset}&total=${total}`, { raw: data, headers: { "x-fuobe-lease": lease, ...headers } });@@ -562,6 +579,58 @@ describe("results are checked like uploads", () => {expect(state(c.id)).toBe("failed");});+ it("a last result that turns out wrong once it has all arrived fails the run, not a run done without it", async () => {+ const c = await collecting({ "9": { text_files: [{ filename: "x_00001_.txt", subfolder: "fuobe", type: "output" }] } }, { "9": { class_type: "SaveText|pysssss", inputs: { filename_prefix: "fuobe/x" } } } as never);+ const res = await put("a", c.id, 0, c.lease, Buffer.concat([Buffer.from("hello ".repeat(20)), Buffer.from([0xff, 0xfe])]));+ expect(res.status).toBe(415);+ expect(state(c.id)).toBe("failed");+ expect(tasks.receivedFile(`acct:${a}`, c.id, 0)).toBeNull();+ });++ it("an SVG and a splat from the owner's ComfyUI are kept as what their bytes say", async () => {+ setSetting("comfyWhere", "computer");+ const c = await collecting({ "4": { images: [{ filename: "v_00001_.svg", subfolder: "fuobe", type: "output" }] }, "51": { "3d": [{ filename: "m_00001_.spz", subfolder: "fuobe", type: "output" }] } }, SAVE, "owner");+ expect(c.answer.wanted).toEqual([expect.objectContaining({ kind: "image" }), expect.objectContaining({ kind: "model3d" })]);+ expect((await put("owner", c.id, 0, c.lease, VTRACER_SVG)).status).toBe(200);+ expect((await put("owner", c.id, 1, c.lease, spz())).status).toBe(200);+ expect(state(c.id)).toBe("done");+ expect(tasks.receivedFile("owner", c.id, 0)?.contentType).toBe("image/svg+xml");+ expect(tasks.receivedFile("owner", c.id, 1)?.contentType).toBe("model/x-spz");+ });++ it("an SVG or a splat that isn't one is refused, and the run fails", async () => {+ setSetting("comfyWhere", "computer");+ const svgRun = { "4": { images: [{ filename: "v_00001_.svg", subfolder: "fuobe", type: "output" }] } };+ const spzRun = { "51": { "3d": [{ filename: "m_00001_.spz", subfolder: "fuobe", type: "output" }] } };+ const svgPage = (body: string) => Buffer.from(`<?xml version="1.0" encoding="UTF-8"?>\n<!-- Generator: visioncortex VTracer -->\n${body}`);+ for (const bad of [+ Buffer.from("<!doctype html><html><body>hi</body></html>"),+ svgPage(`<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="4" height="4" onload="alert(1)"><path d="M0 0"/></svg>`),+ svgPage(`<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="4" height="4"><script>alert(1)</script></svg>`),+ svgPage(`<html xmlns="http://www.w3.org/1999/xhtml"><body>hi</body></html>`),+ svgPage(`<svg version="1.1" width="4" height="4"><path d="M0 0"/></svg>`),+ svgPage(`<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="4" height="4"><path d="M0 0"/>`),+ ]) {+ const c = await collecting(svgRun, SAVE, "owner");+ expect((await put("owner", c.id, 0, c.lease, bad)).status, bad.toString().slice(-60)).toBe(415);+ expect(state(c.id)).toBe("failed");+ }+ for (const bad of [zlib.gzipSync(Buffer.from("not a splat at all, just words")), spz(9), spz(2, 0), FAKE_PNG]) {+ const c = await collecting(spzRun, SAVE, "owner");+ expect((await put("owner", c.id, 0, c.lease, bad)).status).toBe(415);+ expect(state(c.id)).toBe("failed");+ }+ });++ it("an account's splat is kept only from the workers, and never a PLY", async () => {+ const { outputType } = await import("@/server/computer/http");+ const want = { n: 0, filename: "m_00001_.spz", subfolder: "", type: "output" as const, kind: "model3d" as const, maxBytes: 1e6 };+ expect(outputType(spz(), want, false, { glb: true })).toBe("model/x-spz");+ expect(() => outputType(spz(), want, false)).toThrow(/3D model/);+ expect(() => outputType(spz(), { ...want, filename: "m_00001_.glb" }, false, { glb: true })).toThrow(/3D model/);+ expect(() => outputType(Buffer.from(PLY), { ...want, filename: "m_00001_.ply" }, false, { glb: true })).toThrow(/3D model/);+ });+it("past a file's limit, or past the room the account's files have, is refused and the run fails", async () => {const c = await collecting(ONE_PNG);const limit = c.answer.wanted![0].maxBytes;