Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

Your GPU: fixes from the review of account uploads and runs

Adarshb5ca7287c913
diff --git a/docs/public-signup.md b/docs/public-signup.md
index 20a3a3b1..bf298137 100644
--- a/docs/public-signup.md
+++ b/docs/public-signup.md
@@ -111,16 +111,18 @@ cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188
with the open-source engine: the Image, Video and Audio studios (their input modes too: edit,
inpaint, extend, lipsync, reframe, upscale, image to video…), every camera motion and effect,
and the apps that take a picture, a clip or a sound. Their chained steps (multi-shot films,
- Frames mode, Extend, text to 3D, relit effects) run there too, as the account's own. Polls,
+ Frames mode, Extend, relit effects) run there too, as the account's own. Polls,
uploads, outputs and cancels go there, and nothing falls back to the studio's own providers. If
the account's ComfyUI can't be reached, the run fails and says so. A cloud model, an AI helper or
the studio's local LLM is refused; "Enhance prompt" uses Fuobe's offline wording. Other tools
(Canvas, Cinema, Shorts, Assist, Marketing…) answer 403 with `code: "own-gpu-tool"`, because they
- plan with the studio's own AI helpers or keep projects of their own.
+ plan with the studio's own AI helpers or keep projects of their own. Image to 3D and text to 3D
+ answer the same for now: a 3D model is finished on the server.
- **Files a run takes.** A run on your GPU takes only files you uploaded here, or your own results.
A link or a `data:` URI answers 400 with `code: "input-not-allowed"`, someone else's file 403
(`input-not-yours`), and a file that has expired 404 (`input-gone`, "That file has expired.
- Upload it again."). The server never fetches a link for an account.
+ Upload it again."). A file bigger than an upload of its kind may be (one of your own results,
+ too) answers 413 (`input-too-big`). The server never fetches a link for an account.
- **LoRAs and model files.** The server never downloads anything onto your machine. A LoRA a run
adds (a camera motion's, an effect's, a look's) must already be in your ComfyUI's `models/loras`
folder. When one is missing, the run answers 409 with `code: "comfy_missing_model"` and a `fix`
@@ -130,8 +132,13 @@ cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188
checkpoint or encoder your ComfyUI lacks is named by ComfyUI's own answer.
- **Limits.** Up to 4 runs at once and 60 an hour; a run makes up to 4 results. A run waits up to
30 minutes in your ComfyUI's queue and may run for 45. Your ComfyUI's answers have a deadline and
- a size cap (a result up to 1 GB in 15 minutes; 16 results a job at most). Image to 3D gets the
- web model, without the server's turntable: the 3D page records one in your browser.
+ a size cap (a result up to 1 GB in 15 minutes, and no more than your files have room for; 16
+ results a job at most). Each account sends one file to its ComfyUI at a time, and the accounts
+ take turns. The clip check (`POST /api/media/probe`) allows 60 a minute and 2 at once.
+- **Disk space.** Accounts can't upload or run when the server's data disk is short of space
+ (503): it keeps 20 GB free, or a tenth of a smaller disk, and at least 2 GB.
+ `FUOBE_ACCOUNT_DISK_FREE_GB` sets another amount, and the server log says when accounts are
+ refused for space.
- **What a visitor sees.** For a guest or an account, `GET /api/status` describes its own GPU
(`viewer`), with the open engine and no Demo mode. It says nothing about the studio's own
ComfyUI, providers, keys or local AI servers. The sidebar shows **Your GPU · Connect** (a guest
diff --git a/scripts/model3d/finish-glb.mjs b/scripts/model3d/finish-glb.mjs
index c2dea108..c6a8e90c 100644
--- a/scripts/model3d/finish-glb.mjs
+++ b/scripts/model3d/finish-glb.mjs
@@ -2,7 +2,10 @@
// Finish an image-to-3D GLB from ComfyUI (Pixal3D, TRELLIS.2, Hunyuan3D) for the web. The Fuobe server runs
// this in a child process after the job (src/server/model3d-finish.ts); it also works by hand:
//
-// node scripts/model3d/finish-glb.mjs --in raw.glb --out web.glb [--material auto|matte|metal|mixed] [--texture-size 2048]
+// node scripts/model3d/finish-glb.mjs --in raw.glb --out web.glb [--material auto|matte|metal|mixed] [--texture-size 2048] [--limits account]
+//
+// --limits account (a model made on an account's own ComfyUI): one CPU thread for the pictures, at most 32 textures,
+// none over 4096 x 4096 and 64 megapixels in all, checked from the pictures' headers before any is decoded (exit 3).
//
// 1. Material: "auto" reads the baked metallic channel (B of the metallicRoughness texture). Mostly metal
// (>= 25 % of texels at metallic >= 0.5) -> "metal"; almost none (< 2 % and mean < 0.05) -> "matte";
@@ -34,8 +37,16 @@ const { values: a } = parseArgs({
out: { type: "string" },
material: { type: "string", default: "auto" },
"texture-size": { type: "string", default: "2048" },
+ limits: { type: "string" },
},
});
+const ACCOUNT = a.limits === "account";
+/** --limits account: per picture, all pictures, and how many. */
+const LIMITS = { texels: 4096 * 4096, total: 64_000_000, textures: 32 };
+if (ACCOUNT) sharp.concurrency(1);
+/** sharp, kept to the account limits when they apply (every picture this script and textureCompress decode). */
+const pic = (input, options = {}) => sharp(input, ACCOUNT ? { ...options, limitInputPixels: LIMITS.texels } : options);
+Object.assign(pic, sharp);
if (!a.in || !a.out) {
console.error("usage: finish-glb.mjs --in raw.glb --out web.glb [--material auto|matte|metal|mixed] [--texture-size 2048]");
process.exit(2);
@@ -87,6 +98,27 @@ const doc = await io.readBinary(new Uint8Array(input.buffer, input.byteOffset, i
doc.setLogger(new Logger(Logger.Verbosity.ERROR));
const root = doc.getRoot();
+// ---- 0. a model from an account's ComfyUI: its pictures' sizes from their headers, before anything is decoded
+if (ACCOUNT) {
+ const textures = root.listTextures();
+ if (textures.length > LIMITS.textures) refuse(`too many textures (${textures.length}; at most ${LIMITS.textures})`);
+ let total = 0;
+ for (const tex of textures) {
+ const image = tex.getImage();
+ if (!image) continue;
+ let size;
+ try {
+ size = await sharp(Buffer.from(image), { limitInputPixels: false }).metadata();
+ } catch {
+ refuse("a texture that can't be read");
+ }
+ const texels = (size.width ?? 0) * (size.height ?? 0);
+ if (!texels || texels > LIMITS.texels) refuse(`a texture over 4096 x 4096 (${size.width} x ${size.height})`);
+ total += texels;
+ if (total > LIMITS.total) refuse("textures over 64 megapixels in all");
+ }
+}
+
// ---- 1. material class from the metallic channel
const mrTextures = [...new Set(root.listMaterials().map((m) => m.getMetallicRoughnessTexture()).filter(Boolean))];
const decoded = new Map();
@@ -95,7 +127,7 @@ let metalSum = 0;
let texels = 0;
for (const tex of mrTextures) {
// 8-bit sRGB (a grey or 16-bit PNG too), stepped by the decoded pixels' own channel count (alpha or not).
- const { data: raw, info } = await sharp(Buffer.from(tex.getImage())).toColourspace("srgb").raw().toBuffer({ resolveWithObject: true });
+ const { data: raw, info } = await pic(Buffer.from(tex.getImage())).toColourspace("srgb").raw().toBuffer({ resolveWithObject: true });
const { width, height, channels } = info;
decoded.set(tex, { raw, width, height, channels });
for (let i = 0; i < raw.length; i += channels) {
@@ -140,7 +172,7 @@ if (rule.roughFloor > 0 || rule.noMetal) {
if (rule.floorMetalTexels || !metal) raw[i + 1] = Math.max(raw[i + 1], floor);
if (rule.noMetal) raw[i + 2] = 0;
}
- const png = await sharp(raw, { raw: { width, height, channels } }).png({ compressionLevel: 6 }).toBuffer();
+ const png = await pic(raw, { raw: { width, height, channels } }).png({ compressionLevel: 6 }).toBuffer();
tex.setImage(new Uint8Array(png)).setMimeType("image/png");
}
}
@@ -157,7 +189,7 @@ await doc.transform(
weld(),
prune({ keepAttributes: true, keepIndices: false, keepLeaves: false, keepSolidTextures: true }),
sparse(),
- textureCompress({ encoder: sharp, targetFormat: "webp", resize: [size, size] }),
+ textureCompress({ encoder: pic, targetFormat: "webp", resize: [size, size] }),
meshopt({ encoder: MeshoptEncoder, level: "high" }),
);
diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.ts
index f79ed846..619b2151 100644
--- a/src/app/api/generations/route.ts
+++ b/src/app/api/generations/route.ts
@@ -1,14 +1,12 @@
import { connection } from "next/server";
import { CONNECT_GPU_HEADER, OWN_GPU_TOOL_MESSAGE } from "@/lib/guest-access";
-import { graphLoras } from "@/lib/catalog/character-swap";
import { missingFilesMessage } from "@/lib/missing-files";
import { accountGpu, requestAccount, requestViewer } from "@/server/auth";
import { OPERATION_LABELS } from "@/lib/catalog/types";
import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountUsage, diskHasRoom } from "@/server/account-files";
import { accountInputProblem } from "@/server/account-inputs";
-import { checkAccountLoras } from "@/server/account-loras";
import { db } from "@/server/db";
-import { accountRun, asVisitor, createGenerations, listGenerations, outputKind, previewGeneration } from "@/server/generations";
+import { accountLoraFix, accountRun, asVisitor, createGenerations, listGenerations, outputKind, previewGeneration } from "@/server/generations";
import { ensureTrashPurge, listOptionsFrom } from "@/server/library";
import { hit, unhit } from "@/server/rate";
import { GenerationRequestSchema } from "@/server/request-schema";
@@ -123,12 +121,9 @@ export async function POST(request: Request) {
}
}
if (account) {
- // The LoRAs this run adds must be on the account's ComfyUI: say which to download before anything is queued.
- const fix = await onOwn(async () => {
- const p = previewGeneration(req);
- if (p.route.provider !== "comfyui") return null;
- return checkAccountLoras([...p.loras.applied, ...graphLoras(p.route.endpoint, req.params?.extra)], p.route.endpoint);
- });
+ // The LoRAs this run adds (and its start frame's step, for an effect that makes one) must be on the account's
+ // ComfyUI: say which to download before anything is queued.
+ const fix = await onOwn(() => accountLoraFix(req));
if (fix) {
unhit(`run:${account.id}`);
return refuse(409, missingFilesMessage(fix), { code: "comfy_missing_model", fix });
diff --git a/src/app/api/media/probe/route.ts b/src/app/api/media/probe/route.ts
index 965852d6..b4cecb78 100644
--- a/src/app/api/media/probe/route.ts
+++ b/src/app/api/media/probe/route.ts
@@ -1,5 +1,7 @@
import { z } from "zod";
+import { ACCOUNT_MESSAGES } from "@/server/account-files";
import { requestAccount } from "@/server/auth";
+import { enter, hit } from "@/server/rate";
import { probeSource } from "@/server/shorts";
import { body, handle } from "@/server/shorts-schemas";
import { runAsTenant } from "@/server/tenant";
@@ -7,13 +9,29 @@ import { runAsTenant } from "@/server/tenant";
/**
* An uploaded clip's length, size, frame rate and whether it has sound, from its header (MP4 / MOV, WebM).
* The composer prices clip-length tools with it and says what comes out (Upscale hub: "24 → 60 fps").
- * An account reads only its own files: another's answers like one that is gone.
+ * An account reads only its own files (another's answers like one that is gone), no bigger than its uploads may be, 60
+ * a minute and 2 at once (6 at once for all accounts together).
*/
export async function POST(request: Request) {
return handle(async () => {
const { url } = await body(request, z.object({ url: z.string().startsWith("/api/files/").max(500) }), "Upload the clip first");
const account = requestAccount(request);
- const info = account ? await runAsTenant({ kind: "account", id: account.id }, () => probeSource(url)) : await probeSource(url);
- return Response.json(info);
+ if (!account) return Response.json(await probeSource(url));
+ const busy = () => Response.json({ error: ACCOUNT_MESSAGES.probeRate }, { status: 429, headers: { "Retry-After": "10", "Cache-Control": "no-store" } });
+ if (!hit(`probe:${account.id}`, 60, 60_000).ok) return busy();
+ const release = enter(`probe:${account.id}`, 2);
+ if (!release) return busy();
+ // And a few at once across every account: each check reads its clip (95 MB at most) into memory.
+ const releaseAll = enter("probe:accounts", 6);
+ if (!releaseAll) {
+ release();
+ return busy();
+ }
+ try {
+ return Response.json(await runAsTenant({ kind: "account", id: account.id }, () => probeSource(url)));
+ } finally {
+ releaseAll();
+ release();
+ }
});
}
diff --git a/src/proxy.ts b/src/proxy.ts
index d6c07d33..04fc22c3 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -209,5 +209,5 @@ export const config = {
// 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$).*)"],
+ matcher: ["/((?!_next/static|_next/image|favicon\\.ico$|apple-icon\\.png$|samples/|previews/|vendor/|api/uploads$|[^/]+\\.svg$).*)"],
};
diff --git a/src/server/account-files.ts b/src/server/account-files.ts
index ce945953..4d1936c9 100644
--- a/src/server/account-files.ts
+++ b/src/server/account-files.ts
@@ -32,7 +32,7 @@ export const ACCOUNT_LIMITS = {
/** Retention: uploads (even when a run still names them), and runs with their files. */
uploadDays: 14,
runDays: 30,
- /** The disk space the server keeps free: below it, no account uploads or runs. */
+ /** The disk space the server keeps free, at most (a tenth of a smaller disk; diskFloorBytes): below it, no account uploads or runs. */
diskFreeBytes: 20 * GB,
/** Runs: at once (queued or running), per hour, and outputs per run. */
activeRuns: 4,
@@ -40,8 +40,9 @@ export const ACCOUNT_LIMITS = {
outputsPerRun: 4,
/** What one run request may weigh (inputs are uploaded first, so a request is only words and file paths). */
runBodyBytes: 1 * MB,
- /** Outputs kept from one job on the account's ComfyUI. */
+ /** Outputs kept from one job on the account's ComfyUI, and EXR frames zipped from one export. */
outputsPerJob: 16,
+ framesPerJob: 1800,
/** How long a job may wait in the account's ComfyUI's queue. */
queueMs: 30 * 60_000,
/** GPU address checks and saves, per minute. */
@@ -55,6 +56,7 @@ export const ACCOUNT_MESSAGES = {
imageTooManyPixels: "That picture is over 40 megapixels. Save it smaller, then try again.",
audioTooBig: "That sound file is over 50 MB. Trim it, then try again.",
videoTooBig: "That clip is over 95 MB. Trim it or lower its quality, then try again.",
+ fileTooBig: "That file is over 95 MB. Make it smaller, then try again.",
wrongType: "Fuobe takes PNG, JPEG or WebP pictures, MP4, MOV, WebM, MKV or AVI clips, and MP3, WAV, OGG, FLAC or M4A sound.",
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.",
@@ -65,6 +67,7 @@ export const ACCOUNT_MESSAGES = {
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.",
+ probeRate: "Too many clip checks at once. Wait a moment, then try again.",
reloadToUpload: "Reload the page, then upload again.",
lengthNeeded: "Send the file with its size (Content-Length).",
} as const;
@@ -81,24 +84,61 @@ export function accountUsage(id: string): { total: number; uploads: number; uplo
}
declare global {
- /** Tests only: the free disk space to report. */
+ /** Tests only: the free disk space and the disk's size to report. */
var __fuobeTestDiskFree: number | undefined;
+ var __fuobeTestDiskSize: number | undefined;
+ /** When the owner was last told that accounts are refused for space. */
+ var __fuobeDiskLowWarned: number | undefined;
}
-/** Free space on the disk that holds the data folder (Infinity when it can't be read: the check never blocks by mistake). */
-export function diskFreeBytes(): number {
- if (process.env.VITEST === "true" && typeof globalThis.__fuobeTestDiskFree === "number") return globalThis.__fuobeTestDiskFree;
+/** The data disk's free space and size (Infinity when they can't be read: the check never blocks by mistake). */
+function diskSpace(): { free: number; size: number } {
+ if (process.env.VITEST === "true" && typeof globalThis.__fuobeTestDiskFree === "number") return { free: globalThis.__fuobeTestDiskFree, size: globalThis.__fuobeTestDiskSize ?? Infinity };
try {
fs.mkdirSync(DATA_DIR, { recursive: true });
const s = fs.statfsSync(DATA_DIR);
- return Number(s.bavail) * Number(s.bsize);
+ return { free: Number(s.bavail) * Number(s.bsize), size: Number(s.blocks) * Number(s.bsize) };
} catch {
- return Infinity;
+ return { free: Infinity, size: Infinity };
}
}
-/** Whether the server has room for an account's upload or run. */
-export const diskHasRoom = () => diskFreeBytes() >= ACCOUNT_LIMITS.diskFreeBytes;
+/** Free space on the disk that holds the data folder. */
+export const diskFreeBytes = (): number => diskSpace().free;
+
+/**
+ * The free space accounts never use: FUOBE_ACCOUNT_DISK_FREE_GB when it is set, else 20 GB or a tenth of the disk,
+ * whichever is less, and at least 2 GB (a small server keeps a share of its own disk, not a fixed 20 GB).
+ */
+export function diskFloorBytes(size = diskSpace().size): number {
+ const set = process.env.FUOBE_ACCOUNT_DISK_FREE_GB?.trim();
+ if (set && Number.isFinite(Number(set)) && Number(set) >= 0) return Number(set) * GB;
+ return Math.max(2 * GB, Math.min(ACCOUNT_LIMITS.diskFreeBytes, size / 10));
+}
+
+/** Whether the server has room for an account's upload or run. When it hasn't, the server log says so once an hour. */
+export function diskHasRoom(): boolean {
+ const { free, size } = diskSpace();
+ const floor = diskFloorBytes(size);
+ if (free >= floor) return true;
+ if (Date.now() - (globalThis.__fuobeDiskLowWarned ?? 0) > 60 * 60_000) {
+ globalThis.__fuobeDiskLowWarned = Date.now();
+ console.warn(`[fuobe] Accounts can't upload or run now: the data disk has ${(free / GB).toFixed(1)} GB free, and ${(floor / GB).toFixed(1)} GB is kept free (FUOBE_ACCOUNT_DISK_FREE_GB sets it).`);
+ }
+ return false;
+}
+
+/**
+ * The most a run on an account's GPU sends of one stored file (its own results too): what an upload of its kind may
+ * be (a picture 25 MB, sound 50 MB, a clip 95 MB; anything else as a clip). Each file sent is held in memory a few times.
+ */
+export function accountInputLimit(contentType: string): { bytes: number; message: string } {
+ const t = contentType.split(";")[0].trim().toLowerCase();
+ if (t.startsWith("image/")) return { bytes: ACCOUNT_LIMITS.imageBytes, message: ACCOUNT_MESSAGES.imageTooBig };
+ if (t.startsWith("audio/")) return { bytes: ACCOUNT_LIMITS.audioBytes, message: ACCOUNT_MESSAGES.audioTooBig };
+ if (t.startsWith("video/")) return { bytes: ACCOUNT_LIMITS.videoBytes, message: ACCOUNT_MESSAGES.videoTooBig };
+ return { bytes: ACCOUNT_LIMITS.videoBytes, message: ACCOUNT_MESSAGES.fileTooBig };
+}
// ---------------------------------------------------------------------------
// When an account is deleted
diff --git a/src/server/account-inputs.ts b/src/server/account-inputs.ts
index eb53038c..fc58d725 100644
--- a/src/server/account-inputs.ts
+++ b/src/server/account-inputs.ts
@@ -2,7 +2,8 @@ import "server-only";
import fs from "node:fs";
import type { GenerationRequest } from "@/lib/catalog/types";
import { fileAccount } from "./account-library";
-import { absolutePath, GONE_MESSAGE, NOT_YOURS_MESSAGE } from "./storage";
+import { accountInputLimit } from "./account-files";
+import { absolutePath, contentTypeFor, filesRel, GONE_MESSAGE, NOT_YOURS_MESSAGE } from "./storage";
/**
* The files an account's run names (public sign-up, "Your GPU"): only files it uploaded here, or its own results. No
@@ -11,7 +12,7 @@ import { absolutePath, GONE_MESSAGE, NOT_YOURS_MESSAGE } from "./storage";
* a step reads its inputs. None of these answers is a GPU setup problem.
*/
-export type InputProblem = { status: 400 | 403 | 404; code: "input-not-allowed" | "input-not-yours" | "input-gone"; error: string };
+export type InputProblem = { status: 400 | 403 | 404 | 413; code: "input-not-allowed" | "input-not-yours" | "input-gone" | "input-too-big"; error: string };
export const INPUT_NOT_ALLOWED = "Upload the file here first. Runs on your GPU use files you uploaded.";
@@ -20,23 +21,26 @@ const notAllowed: InputProblem = { status: 400, code: "input-not-allowed", error
/** A string in params.extra that names a file (the slots there take a stored file, a link or a data: URI). */
const looksLikeFile = (v: string) => /^(data:|https?:\/\/|\/api\/files\/)/i.test(v.trim());
-/** One stored file named by an account's run: fine (null), gone, or someone else's. */
+/** One stored file named by an account's run: fine (null), not a stored file's path, gone, someone else's, or too big. */
function checkFile(ref: string, accountId: string): InputProblem | null {
if (!ref.startsWith("/api/files/")) return notAllowed;
- let rel: string;
- try {
- rel = decodeURIComponent(ref.slice("/api/files/".length).split("?")[0]);
- } catch {
- return { status: 404, code: "input-gone", error: GONE_MESSAGE };
- }
+ // The path a step reads, parsed as the step parses it (storage.ts filesRel): one that steps out of its folder is refused.
+ const rel = filesRel(ref);
+ if (rel === null) return notAllowed;
const owner = fileAccount(rel);
if (owner === undefined) return { status: 404, code: "input-gone", error: GONE_MESSAGE };
if (owner !== accountId) return { status: 403, code: "input-not-yours", error: NOT_YOURS_MESSAGE };
+ let size: number;
try {
- if (!fs.statSync(absolutePath(rel)).isFile()) return { status: 404, code: "input-gone", error: GONE_MESSAGE };
+ const st = fs.statSync(absolutePath(rel));
+ if (!st.isFile()) return { status: 404, code: "input-gone", error: GONE_MESSAGE };
+ size = st.size;
} catch {
return { status: 404, code: "input-gone", error: GONE_MESSAGE };
}
+ // Its own results too: no bigger than an upload of its kind may be (each file sent is held in memory a few times).
+ const limit = accountInputLimit(contentTypeFor(rel));
+ if (size > limit.bytes) return { status: 413, code: "input-too-big", error: limit.message };
return null;
}
@@ -59,7 +63,8 @@ export function accountInputProblem(req: Pick<GenerationRequest, "inputs" | "par
refs.push(...list.filter(looksLikeFile));
}
for (const ref of refs) {
- const problem = checkFile(ref.trim(), accountId);
+ // As the step will read it: " /api/files/…" is no stored file's path.
+ const problem = checkFile(ref, accountId);
if (problem) return problem;
}
return null;
diff --git a/src/server/account-send.ts b/src/server/account-send.ts
new file mode 100644
index 00000000..87c222d8
--- /dev/null
+++ b/src/server/account-send.ts
@@ -0,0 +1,98 @@
+import "server-only";
+
+/**
+ * Work for accounts ("Your GPU") that the whole server shares a few slots for: the files an account's runs send to its
+ * own ComfyUI (each held in memory a few times while it goes, and a slow tunnel can take minutes), and the 3D finish
+ * of an account's model. One account holds one slot at a time, and a free slot goes to the next account in turn
+ * (round-robin: an account that just had one goes to the back of the line), so one slow or busy account never holds
+ * up the others.
+ */
+
+/** Files sent at once across the server. */
+export const ACCOUNT_SENDS = 2;
+
+interface Line {
+ slots: number;
+ /** Slots in use, by account. */
+ busy: Map<string, number>;
+ total: number;
+ /** Who waits, by account, in turn order (a Map keeps the order its keys were set in). */
+ waiting: Map<string, (() => void)[]>;
+}
+
+declare global {
+ var __fuobeAccountLines: Map<string, Line> | undefined;
+}
+
+function line(name: string, slots: number): Line {
+ const all = (globalThis.__fuobeAccountLines ??= new Map());
+ let l = all.get(name);
+ if (!l) all.set(name, (l = { slots, busy: new Map(), total: 0, waiting: new Map() }));
+ return l;
+}
+
+function take(l: Line, account: string): void {
+ l.total++;
+ l.busy.set(account, (l.busy.get(account) ?? 0) + 1);
+}
+
+/** Hand free slots to the accounts waiting, in turn, skipping one that holds a slot already. */
+function handOn(l: Line): void {
+ while (l.total < l.slots) {
+ let next: string | undefined;
+ for (const account of l.waiting.keys()) {
+ if (!l.busy.get(account)) {
+ next = account;
+ break;
+ }
+ }
+ if (next === undefined) return;
+ const list = l.waiting.get(next)!;
+ const go = list.shift()!;
+ // To the back of the line with what it still has waiting.
+ l.waiting.delete(next);
+ if (list.length) l.waiting.set(next, list);
+ take(l, next);
+ go();
+ }
+}
+
+/** Run `fn` when the account's turn comes in the line `name` (`slots` at once across the server, one per account). */
+export async function inTurn<T>(name: string, slots: number, account: string, fn: () => Promise<T>): Promise<T> {
+ const l = line(name, slots);
+ if (l.total < l.slots && !l.busy.get(account)) take(l, account);
+ else
+ await new Promise<void>((go) => {
+ const list = l.waiting.get(account);
+ if (list) list.push(go);
+ else l.waiting.set(account, [go]);
+ });
+ try {
+ return await fn();
+ } finally {
+ l.total--;
+ const left = (l.busy.get(account) ?? 1) - 1;
+ if (left > 0) l.busy.set(account, left);
+ else l.busy.delete(account);
+ // It just had its turn: the others go first.
+ const own = l.waiting.get(account);
+ if (own) {
+ l.waiting.delete(account);
+ l.waiting.set(account, own);
+ }
+ handOn(l);
+ }
+}
+
+/** Run `fn` (read one file and send it to the account's ComfyUI) when the account may send. */
+export const accountSend = <T,>(account: string, fn: () => Promise<T>): Promise<T> => inTurn("send", ACCOUNT_SENDS, account, fn);
+
+/** Tests: how many run now in a line, for whom, and who waits (in turn order). */
+export function lineState(name: string): { total: number; busy: Record<string, number>; waiting: string[] } {
+ const l = globalThis.__fuobeAccountLines?.get(name);
+ if (!l) return { total: 0, busy: {}, waiting: [] };
+ return { total: l.total, busy: Object.fromEntries(l.busy), waiting: [...l.waiting].flatMap(([a, list]) => list.map(() => a)) };
+}
+
+/** Tests: the file sends. */
+export const accountSends = () => lineState("send");
diff --git a/src/server/account-sweep.ts b/src/server/account-sweep.ts
index d3134b5a..a8fd7365 100644
--- a/src/server/account-sweep.ts
+++ b/src/server/account-sweep.ts
@@ -3,7 +3,7 @@ import fs from "node:fs";
import path from "node:path";
import { RETENTION_MS, runAccountDeletedHooks } from "./account-files";
import { clearAccountLoras } from "./account-loras";
-import { listAccounts } from "./auth";
+import { readAccountIds } from "./auth";
import { db } from "./db";
import { deleteForever } from "./library";
import { deleteAsset, scratchDir } from "./storage";
@@ -17,6 +17,8 @@ import { deleteAsset, scratchDir } from "./storage";
const DAY = 24 * 60 * 60_000;
/** An upload's temp file left behind (the server stopped mid-upload). */
const STALE_UPLOAD_MS = 60 * 60_000;
+/** Any other scratch file left behind: a result's download, a frames zip. */
+const STALE_SCRATCH_MS = 6 * 60 * 60_000;
/** Every account that owns a run or a file here. */
function owners(): string[] {
@@ -64,18 +66,31 @@ export async function sweepAccountFiles(now = Date.now()): Promise<{ uploads: nu
)
.all(now - RETENTION_MS.run) as { id: string }[];
for (const o of orphans) deleteAsset(o.id);
- // Accounts that are gone.
- const live = new Set(listAccounts().map((a) => a.id));
- const gone = owners().filter((id) => !live.has(id));
+ // Accounts that are gone (deleting one purges it at once: this only catches what that missed). Only when the auth
+ // file was read whole, and not when it lists no account at all while accounts own files: a file that failed to read,
+ // or one put back from before the sign-ups, must never wipe everyone's work.
+ let gone: string[] = [];
+ const owning = owners();
+ // No account owns anything here (a new install has no auth file yet): nothing to check.
+ if (owning.length) {
+ try {
+ const live = readAccountIds();
+ if (live.size) gone = owning.filter((id) => !live.has(id));
+ else console.warn(`[fuobe] account sweep: the auth file lists no accounts, but ${owning.length} own files here; nothing removed`);
+ } catch (e) {
+ console.warn(`[fuobe] account sweep: skipped removing deleted accounts' files (${(e as Error).message})`);
+ }
+ }
for (const id of gone) await purgeAccount(id);
- // Upload temp files the server left behind.
+ // Temp files the server left behind (it stopped mid-upload, mid-download or mid-zip): an upload's after an hour,
+ // anything else in the scratch folder after six hours untouched (a download or zip in progress writes to it all along).
try {
const dir = scratchDir();
for (const f of fs.readdirSync(dir)) {
- if (!f.startsWith("up-")) continue;
const file = path.join(dir, f);
try {
- if (now - fs.statSync(file).mtimeMs > STALE_UPLOAD_MS) fs.rmSync(file, { force: true });
+ const st = fs.statSync(file);
+ if (st.isFile() && now - st.mtimeMs > (f.startsWith("up-") ? STALE_UPLOAD_MS : STALE_SCRATCH_MS)) fs.rmSync(file, { force: true });
} catch {}
}
} catch {}
diff --git a/src/server/auth.ts b/src/server/auth.ts
index 3af31d67..d3a30649 100644
--- a/src/server/auth.ts
+++ b/src/server/auth.ts
@@ -240,6 +240,19 @@ export function listAccounts(): AccountInfo[] {
.sort((a, b) => b.createdAt - a.createdAt);
}
+/**
+ * The ids of the accounts, read from the auth file itself: throws when it can't be read or parsed, or has no secret
+ * (every auth file that ever held an account has one). The account sweep removes the files of accounts missing from
+ * it, so a read that failed for a moment must never look like "no accounts".
+ */
+export function readAccountIds(): Set<string> {
+ const data = JSON.parse(fs.readFileSync(FILE, "utf8")) as Partial<AuthFile> | null;
+ if (!data || typeof data !== "object" || typeof data.secret !== "string" || !data.secret || (data.accounts !== undefined && !Array.isArray(data.accounts))) {
+ throw new Error("The auth file can't be read");
+ }
+ return new Set((data.accounts ?? []).map((a) => a?.id).filter((id): id is string => typeof id === "string" && !!id));
+}
+
/** Switch an account off (it is signed out at once) or on again. */
export function setAccountDisabled(id: string, disabled: boolean): void {
const d = read();
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 1484c246..9578b2c4 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -51,14 +51,14 @@ import { createExtendChain, createKeyframeFilm, createMosaicRun, createRelitClip
import { enhancePrompt, enhanceSoulWords } from "./enhance";
import { setResolver, watchGenerations, type LiveEvent } from "./live";
import { provider, PROVIDERS, RETIRED_PROVIDER_ERROR } from "./providers";
-import { comfyLoraFiles, onOwnGpu, outputFetch, outsideOwnGpu, ownGpu, probeComfy } from "./providers/comfyui";
+import { comfyLoraFiles, onOwnGpu, outputFetch, outsideOwnGpu, OWN_OUTPUT_LIMITS, ownGpu, probeComfy } from "./providers/comfyui";
import { accountGpu } from "./auth";
import { CONNECT_GPU_MESSAGE, GUEST_RUN_MESSAGE, OWN_GPU_TOOL_MESSAGE } from "@/lib/guest-access";
import { outsideTenant, runAsTenant, tenant, tenantAccount } from "./tenant";
import { generationAccount } from "./account-library";
-import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountUsage } from "./account-files";
+import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountUsage, diskHasRoom } from "./account-files";
import { checkAccountLoras } from "./account-loras";
-import { missingFilesMessage } from "@/lib/missing-files";
+import { missingFilesMessage, type MissingFiles } from "@/lib/missing-files";
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";
import { graphLoras } from "@/lib/catalog/character-swap";
@@ -71,7 +71,8 @@ import { mediaFacts } from "./media-facts";
import { modelToFinish, startModelFinish, startTurntable, stopModelFinish, type OutputStore } from "./model3d-finish";
import { convertMask, decodePng, encodePng } from "./png";
import { engineMode, getSetting, withCandidates, withoutCandidates } from "./settings";
-import { blockedForAccounts, fetchRemoteToFile } from "./remote-fetch";
+import { blockedForAccounts, discardBody, fetchRemoteToFile, RemoteFetchError } from "./remote-fetch";
+import { accountSend } from "./account-send";
import { absolutePath, adoptFile, contentTypeFor, deleteAsset, localHead, readRef, saveFile, scratchDir } from "./storage";
interface Row {
@@ -1219,6 +1220,46 @@ export function accountRun(accountId: string, providerId: string): { run: <T>(fn
return { run: (fn) => runAsTenant({ kind: "account", id: accountId }, () => onOwnGpu(gpu, () => withCandidates({ engineMode: "open", demoMode: "off" }, fn))) };
}
+/**
+ * The LoRA files an account's run needs that its own ComfyUI doesn't have (call it inside accountRun): the run's own,
+ * and those of the step that makes its start frame first (a Fuobe DoP relight or Mixed Media effect, which
+ * createRelitClip queues as a step of its own). Null when nothing is missing, or the list couldn't be read.
+ */
+export async function accountLoraFix(req: GenerationRequest): Promise<MissingFiles | null> {
+ const p = previewGeneration(req);
+ const asks: { loras: LoraRef[]; endpoint: string }[] = [];
+ if (p.route.provider === "comfyui") asks.push({ loras: [...p.loras.applied, ...graphLoras(p.route.endpoint, req.params?.extra)], endpoint: p.route.endpoint });
+ const pre = relightStep(req, p.model);
+ if (pre) {
+ try {
+ const { step } = pre;
+ const s = previewGeneration({
+ feature: req.feature,
+ account: req.account,
+ engine: pre.engine,
+ modelId: step.modelId,
+ op: step.op,
+ prompt: step.prompt,
+ inputs: { images: (req.inputs?.images ?? []).slice(0, 1) },
+ ...(step.loras?.length && { loras: step.loras }),
+ ...(step.params && { params: step.params }),
+ });
+ if (s.route.provider === "comfyui") asks.push({ loras: [...s.loras.applied, ...graphLoras(s.route.endpoint, step.params?.extra)], endpoint: s.route.endpoint });
+ } catch {
+ // The step says what's wrong when it is created.
+ }
+ }
+ const items: MissingFiles["items"] = [];
+ let workflowId: string | undefined;
+ for (const a of asks) {
+ const f = await checkAccountLoras(a.loras, a.endpoint);
+ if (!f) continue;
+ workflowId ??= f.workflowId;
+ for (const i of f.items) if (!items.some((x) => x.file === i.file)) items.push(i);
+ }
+ return items.length ? { code: "comfy_missing_model", ...(workflowId && { workflowId }), items } : null;
+}
+
/**
* Plan (and price) as a visitor's run would go: as that visitor (an account, or a guest), on its own ComfyUI (none
* yet: an empty address that reaches nothing), the open engine, no demo outputs. For previews; a run goes through
@@ -1230,28 +1271,6 @@ export function asVisitor<T>(gpu: { url: string; token?: string } | null, fn: ()
);
}
-/** How many files an account's runs send to ComfyUIs at once, across the server (each holds the file about 3 times in memory). */
-const ACCOUNT_SENDS = 2;
-
-declare global {
- var __fuobeAccountSends: { busy: number; waiting: (() => void)[] } | undefined;
-}
-
-/** Send an account's file when a slot is free (ACCOUNT_SENDS at once). */
-async function accountSend<T>(fn: () => Promise<T>): Promise<T> {
- const s = (globalThis.__fuobeAccountSends ??= { busy: 0, waiting: [] });
- // A finished send hands its slot straight to the next one waiting.
- if (s.busy >= ACCOUNT_SENDS) await new Promise<void>((resolve) => s.waiting.push(resolve));
- else s.busy++;
- try {
- return await fn();
- } finally {
- const next = s.waiting.shift();
- if (next) next();
- else s.busy--;
- }
-}
-
const accountOf = (r: Pick<Row, "request_json">): string | undefined => {
try {
return (JSON.parse(r.request_json) as GenerationRequest).account;
@@ -1280,14 +1299,29 @@ async function submitNow(
): Promise<void> {
const adapter = provider(providerId);
submitting().add(id);
+ /** Why the run failed, once it has: its files still waiting to be sent are not sent. */
+ let failed: { error: unknown } | undefined;
try {
// An account's run on its own ComfyUI: every LoRA it adds must be there first (nothing is sent before this check).
if (req.account && providerId === "comfyui") {
const fix = await checkAccountLoras([...plan.loras, ...graphLoras(route.endpoint, plan.params.extra)], route.endpoint, route);
if (fix) throw Object.assign(new Error(missingFilesMessage(fix)), { fix });
}
- // An account's files go to its ComfyUI a few at a time across the server (accountSend).
- const gate = <T,>(fn: () => Promise<T>): Promise<T> => (req.account ? accountSend(fn) : fn());
+ // An account's files go to its ComfyUI one at a time, a few across the server (account-send.ts). A file whose turn
+ // comes after another input failed, or after a cancel, isn't read or sent.
+ const gate = <T,>(fn: () => Promise<T>): Promise<T> => {
+ if (!req.account) return fn();
+ return accountSend(req.account, async () => {
+ if (failed) throw failed.error;
+ if (statusOf(id) === "canceled") throw new Error("Stopped");
+ try {
+ return await fn();
+ } catch (e) {
+ failed ??= { error: e };
+ throw e;
+ }
+ });
+ };
const prep = async (ref?: string) => {
if (!ref) return undefined;
return gate(async () => {
@@ -1414,6 +1448,7 @@ async function submitNow(
recordSubmission(id, now);
})();
} catch (e) {
+ failed ??= { error: e };
// A cancel during the hand-over stays a cancel. What the GPU was missing (a model, a node class) is kept, so the
// tile offers "Fix it", and the account's GPU check counts as stale.
const fix = (e as { fix?: GenerationFix }).fix;
@@ -1908,18 +1943,33 @@ function roomFor(account: string, bytes: number, file?: string): void {
}
/**
- * An account's result from its own ComfyUI: streamed to disk (1 GB at most, outputFetch), checked against its storage,
- * stored as a type from the allowlist. A download that fails leaves no file behind.
+ * An account's result from its own ComfyUI: streamed to disk (1 GB at most, outputFetch, and never more than its files
+ * have room for), checked against its storage, stored as a type from the allowlist. Nothing is fetched while the
+ * server is short of space. A download that fails leaves no file behind.
*/
async function persistAccountOutput(o: RichOutput, generationId: string, account: string, linked: Record<string, unknown> | undefined): Promise<OutputFile> {
- const res = await outputFetch(o.url, { headers: o.headers });
- if (!res.ok || !res.body) throw new Error(`download ${res.status}`);
+ const left = ACCOUNT_LIMITS.totalBytes - accountUsage(account).total;
+ if (left <= 0) throw new AccountFilesFull(ACCOUNT_MESSAGES.filesFull);
+ if (!diskHasRoom()) throw new Error(ACCOUNT_MESSAGES.diskLow);
+ const quotaCapped = left < OWN_OUTPUT_LIMITS.maxBytes;
+ // A result over what the account has room for says so, not the size of one answer.
+ const full = (e: unknown) => (quotaCapped && e instanceof RemoteFetchError && /^The answer was over/.test(e.message) ? new AccountFilesFull(ACCOUNT_MESSAGES.filesFull) : e);
+ let res: Response;
+ try {
+ res = await outputFetch(o.url, { headers: o.headers }, { maxBytes: left });
+ } catch (e) {
+ throw full(e);
+ }
+ if (!res.ok || !res.body) {
+ discardBody(res);
+ throw new Error(`download ${res.status}`);
+ }
const dest = path.join(scratchDir(), `${generationId}-out-${nanoid(8)}`);
try {
await pipeline(Readable.fromWeb(res.body as import("node:stream/web").ReadableStream<Uint8Array>), fs.createWriteStream(dest));
} catch (e) {
fs.rmSync(dest, { force: true });
- throw e;
+ throw full(e);
}
roomFor(account, fs.statSync(dest).size, dest);
const header = res.headers.get("content-type")?.split(";")[0];
diff --git a/src/server/model3d-finish.ts b/src/server/model3d-finish.ts
index dc33cd43..1f8503cc 100644
--- a/src/server/model3d-finish.ts
+++ b/src/server/model3d-finish.ts
@@ -5,6 +5,7 @@ import os from "node:os";
import path from "node:path";
import type { OutputFile } from "@/lib/catalog/types";
import { absolutePath, deleteAsset, getAsset, saveFile } from "./storage";
+import { inTurn } from "./account-send";
/**
* The finish every image-to-3D GLB from ComfyUI gets on this server, in two steps:
@@ -162,7 +163,6 @@ const removeDir = (dir: string) => fs.promises.rm(dir, { recursive: true, force:
declare global {
var __fuobeModelFinish: Map<string, AbortController> | undefined;
var __fuobeTurntableQueue: Promise<unknown> | undefined;
- var __fuobeAccountFinishQueue: Promise<unknown> | undefined;
}
const running = () => (globalThis.__fuobeModelFinish ??= new Map());
@@ -175,12 +175,9 @@ function oneAtATime<T>(fn: () => Promise<T>): Promise<T> {
}
// One finish for accounts (public sign-up) at a time across the server: a model from someone else's ComfyUI waits its
-// turn, so many accounts can't keep every CPU core busy at once.
-function oneAccountAtATime<T>(fn: () => Promise<T>): Promise<T> {
- const next = (globalThis.__fuobeAccountFinishQueue ?? Promise.resolve()).then(fn, fn);
- globalThis.__fuobeAccountFinishQueue = next.catch(() => {});
- return next;
-}
+// turn, so many accounts can't keep every CPU core busy at once. The accounts take turns (account-send.ts), so one
+// with many models waiting never holds up another's.
+const oneAccountAtATime = <T,>(account: string, fn: () => Promise<T>): Promise<T> => inTurn("finish", 1, account, fn);
/** An account's raw GLB over this is kept as it is, with no finish. */
export const ACCOUNT_FINISH_MAX_BYTES = 300 * 2 ** 20;
@@ -216,7 +213,13 @@ export async function finishModel(
const webFile = path.join(tmp, "web.glb");
let stats: FinishStats | null = null;
try {
- const run = await runScript("finish-glb.mjs", ["--in", raw, "--out", webFile], { timeoutMs: FINISH_TIMEOUT_MS, signal, cwd: tmp });
+ // An account's model: below the server's own work, one thread for its pictures, their sizes checked first.
+ const run = await runScript("finish-glb.mjs", ["--in", raw, "--out", webFile, ...(o.account ? ["--limits", "account"] : [])], {
+ timeoutMs: FINISH_TIMEOUT_MS,
+ signal,
+ cwd: tmp,
+ lowPriority: !!o.account,
+ });
stats = run.code === 0 && fs.existsSync(webFile) ? lastJsonLine<FinishStats>(run.stdout) : null;
if (!stats) finish.error = `web GLB: ${tail(run.stderr) || `exit ${run.code}`}`;
} catch (e) {
@@ -254,7 +257,7 @@ export function startModelFinish(
running().set(generationId, ctl);
const run = () => (ctl.signal.aborted ? Promise.reject(new Error("Stopped")) : finishModel(generationId, outputs, { ...o, signal: ctl.signal }));
// An account's finish waits for the one before it (oneAccountAtATime).
- void (o.account ? oneAccountAtATime(run) : run())
+ void (o.account ? oneAccountAtATime(o.account, run) : run())
.catch((e) => {
if (ctl.signal.aborted) return null;
console.warn(`[fuobe] 3D finish for ${generationId} failed: ${(e as Error).message}`);
diff --git a/src/server/png.ts b/src/server/png.ts
index a027ffd8..b9eb618b 100644
--- a/src/server/png.ts
+++ b/src/server/png.ts
@@ -1,5 +1,6 @@
import "server-only";
import zlib from "node:zlib";
+import { tenant } from "./tenant";
/**
* Minimal 8-bit PNG decode/encode, enough to convert the masks Fuobe's own editor exports
@@ -12,8 +13,13 @@ export type MaskFormat = "white" | "black" | "alpha";
const SIG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
const CHANNELS: Record<number, number> = { 0: 1, 2: 3, 4: 2, 6: 4 };
-/** The largest picture decodePng takes (40 megapixels: 160 MB of RGBA). */
+/** The largest picture decodePng takes in an account's work (40 megapixels: 160 MB of RGBA). */
export const MAX_PNG_PIXELS = 40_000_000;
+/** The owner's own pictures: far more (a 48 MP photo's mask, a large face mosaic), still a bound (2 GB of RGBA). */
+export const OWNER_MAX_PNG_PIXELS = 500_000_000;
+
+/** The pixel limit for the work in hand: an account's or a visitor's (tenant.ts), or the owner's. */
+export const pngPixelLimit = (): number => (tenant() ? MAX_PNG_PIXELS : OWNER_MAX_PNG_PIXELS);
interface Decoded {
width: number;
@@ -22,7 +28,7 @@ interface Decoded {
data: Buffer;
}
-export function decodePng(buf: Buffer): Decoded {
+export function decodePng(buf: Buffer, maxPixels = pngPixelLimit()): Decoded {
if (!buf.subarray(0, 8).equals(SIG)) throw new Error("Not a PNG");
let off = 8;
let width = 0;
@@ -48,7 +54,7 @@ export function decodePng(buf: Buffer): Decoded {
const ch = CHANNELS[type];
if (depth !== 8 || !ch || interlace) throw new Error("Unsupported PNG (need 8-bit, non-interlaced, no palette)");
// Refused before anything is inflated: a few kilobytes can claim gigabytes of pixels.
- if (!width || !height || width * height > MAX_PNG_PIXELS) throw new Error(`That picture is over ${MAX_PNG_PIXELS / 1e6} megapixels`);
+ if (!width || !height || width * height > maxPixels) throw new Error(`That picture is over ${Math.round(maxPixels / 1e6)} megapixels`);
// Never more than the picture needs (a row of filter byte + pixels, per row).
const raw = zlib.inflateSync(Buffer.concat(idat), { maxOutputLength: height * (width * ch + 1) });
const stride = width * ch;
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index f8d8ff05..3ce9bbc6 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -61,8 +61,11 @@ import { probeAvi } from "../avi-probe";
import { probeWebm } from "../webm-probe";
import { adoptFile, readRef, scratchDir } from "../storage";
import { CONNECT_GPU_MESSAGE } from "@/lib/guest-access";
-import { fetchPublic } from "../remote-fetch";
+import { discardBody, fetchPublic, RemoteFetchError } from "../remote-fetch";
import { zipToFile } from "../zip";
+import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountUsage, diskHasRoom } from "../account-files";
+import { accountSend } from "../account-send";
+import { tenantAccount } from "../tenant";
import { ask, checkReach, reachSync, sharedCheck, type Reach } from "./reach";
import { ProviderError, type ProviderAdapter, type RemoteOutput } from "./types";
@@ -127,11 +130,17 @@ export const outsideOwnGpu = <T,>(fn: () => T): T => ownGpuStore.exit(fn);
/** The most an account's ComfyUI may send back for one output file, and how long it may take. */
export const OWN_OUTPUT_LIMITS = { maxBytes: 2 ** 30, deadlineMs: 15 * 60_000 };
-/** fetch() for a provider's file: through fetchPublic on an account's own ComfyUI (1 GB and 15 minutes at most). */
-export function outputFetch(url: string, init: RequestInit = {}): Promise<Response> {
- return ownGpu() ? fetchPublic(url, init, { timeoutMs: 120_000, ...OWN_OUTPUT_LIMITS }) : fetch(url, init);
+/** fetch() for a provider's file: through fetchPublic on an account's own ComfyUI (1 GB and 15 minutes at most, or less). */
+export function outputFetch(url: string, init: RequestInit = {}, o: { maxBytes?: number } = {}): Promise<Response> {
+ if (!ownGpu()) return fetch(url, init);
+ const maxBytes = Math.max(1, Math.min(OWN_OUTPUT_LIMITS.maxBytes, o.maxBytes ?? Infinity));
+ return fetchPublic(url, init, { timeoutMs: 120_000, ...OWN_OUTPUT_LIMITS, maxBytes });
}
+/** An account's ComfyUI: a layer read for its box (one at a time), and one EXR frame, at most. */
+export const OWN_LAYER_MAX_BYTES = 32 * 2 ** 20;
+export const OWN_FRAME_MAX_BYTES = 100 * 2 ** 20;
+
/**
* What an account's ComfyUI may answer, by path: a file (/view) up to 1 GB in 15 minutes; an upload's answer 1 MB, in
* 5 minutes (the time covers sending the file); the node list (/object_info) 64 MB in 2 minutes; anything else 8 MB in
@@ -223,7 +232,10 @@ const reasonOf = (text: string) => (/^\s*</.test(text) ? "" : text.trim().slice(
async function comfyJson<T>(p: string, worker: ComfyWorker = "main"): Promise<T> {
const res = await comfyFetch(p, {}, worker);
const path = p.split("?")[0];
- if (!res.ok) throw worker === "isolated" ? isolatedAnswer(path, res.status) : new ProviderError(`ComfyUI ${path} answered HTTP ${res.status}`, res.status);
+ if (!res.ok) {
+ discardBody(res);
+ throw worker === "isolated" ? isolatedAnswer(path, res.status) : new ProviderError(`ComfyUI ${path} answered HTTP ${res.status}`, res.status);
+ }
try {
return (await res.json()) as T;
} catch {
@@ -449,23 +461,35 @@ function ocrOutput(answer: string, frame: OcrFrame | undefined): ComfyOutput {
return { url: dataUrl(Buffer.from(text), "text/plain"), kind: "text", contentType: "text/plain", text, meta: { lines, ...(size ? { size } : {}), ...(ok ? {} : { unreadable: true }) } };
}
-/** Layers: download each RGBA layer once, add its bounding box (from alpha) and hand the bytes on as a data URL. */
+/**
+ * Layers: download each RGBA layer once, add its bounding box (from alpha) and hand the bytes on as a data URL. On an
+ * account's ComfyUI: only as many layers as the run keeps (16), one at a time, 32 MB each at most, and the layer stays a
+ * link (saved later straight to disk), so a long list of layers can't fill the server's memory.
+ */
async function withLayerBoxes(outputs: ComfyOutput[]): Promise<ComfyOutput[]> {
- return Promise.all(
- outputs.map(async (o) => {
- if (o.kind !== "image" || typeof o.meta?.z !== "number" || o.url.startsWith("data:")) return o;
- try {
- const res = await outputFetch(o.url, { headers: o.headers });
- if (!res.ok) return o;
- const data = Buffer.from(await res.arrayBuffer());
- const png = decodePng(data);
- const bbox = alphaBBox(png.data, png.width, png.height);
- return { ...o, url: dataUrl(data, "image/png"), contentType: "image/png", headers: undefined, meta: { ...o.meta, bbox: bbox ?? [0, 0, 0, 0], width: png.width, height: png.height } };
- } catch {
- return o; // keep the layer without a box rather than failing the job
+ const own = !!ownGpu();
+ const isLayer = (o: ComfyOutput) => o.kind === "image" && typeof o.meta?.z === "number" && !o.url.startsWith("data:");
+ const box = async (o: ComfyOutput): Promise<ComfyOutput> => {
+ try {
+ const res = await outputFetch(o.url, { headers: o.headers }, own ? { maxBytes: OWN_LAYER_MAX_BYTES } : {});
+ if (!res.ok) {
+ discardBody(res);
+ return o;
}
- }),
- );
+ const data = Buffer.from(await res.arrayBuffer());
+ const png = decodePng(data);
+ const bbox = alphaBBox(png.data, png.width, png.height);
+ const meta = { ...o.meta, bbox: bbox ?? [0, 0, 0, 0], width: png.width, height: png.height };
+ return own ? { ...o, contentType: "image/png", meta } : { ...o, url: dataUrl(data, "image/png"), contentType: "image/png", headers: undefined, meta };
+ } catch {
+ return o; // keep the layer without a box rather than failing the job
+ }
+ };
+ if (!own) return Promise.all(outputs.map((o) => (isLayer(o) ? box(o) : o)));
+ const out: ComfyOutput[] = [];
+ let layers = 0;
+ for (const o of outputs) out.push(isLayer(o) && layers++ < ACCOUNT_LIMITS.outputsPerJob ? await box(o) : o);
+ return out;
}
/**
@@ -479,15 +503,43 @@ async function bundleFrames(outputs: ComfyOutput[], generationId: string): Promi
const rest = outputs.filter((o) => o.meta?.role !== "frames");
const preview = rest.find((o) => o.kind === "video");
if (!preview) throw new ProviderError("The EXR export finished without its preview clip");
+ // An account's ComfyUI: a frame count that fits a clip, room on the server, 100 MB a frame, and no more in all than
+ // the account's files have room for (3 GB).
+ const account = ownGpu() ? tenantAccount() : undefined;
+ let budget = Infinity;
+ if (account) {
+ if (frames.length > ACCOUNT_LIMITS.framesPerJob) throw new ProviderError(`Your ComfyUI made ${frames.length} EXR frames. A run on your GPU keeps up to ${ACCOUNT_LIMITS.framesPerJob}: export a shorter clip.`);
+ if (!diskHasRoom()) throw new ProviderError(ACCOUNT_MESSAGES.diskLow);
+ budget = ACCOUNT_LIMITS.totalBytes - accountUsage(account).total;
+ if (budget <= 0) throw new ProviderError(ACCOUNT_MESSAGES.filesFull);
+ }
const dest = path.join(scratchDir(), `${generationId || nanoid(8)}-${nanoid(6)}.zip`);
+ let total = 0;
+ // Past what the account's files have room for: say that, not the size of one answer.
+ const full = (e: unknown) => (account && budget - total < OWN_FRAME_MAX_BYTES && e instanceof RemoteFetchError && /^The answer was over/.test(e.message) ? new ProviderError(ACCOUNT_MESSAGES.filesFull) : e);
async function* files() {
for (const [i, f] of frames.entries()) {
- const res = await outputFetch(f.url, { headers: f.headers });
- if (!res.ok) throw new ProviderError(`ComfyUI answered HTTP ${res.status} for EXR frame ${i + 1}`);
- yield { name: `frame_${String(i + 1).padStart(5, "0")}.exr`, data: Buffer.from(await res.arrayBuffer()) };
+ let data: Buffer;
+ try {
+ const res = await outputFetch(f.url, { headers: f.headers }, account ? { maxBytes: Math.min(OWN_FRAME_MAX_BYTES, budget - total) } : {});
+ if (!res.ok) {
+ discardBody(res);
+ throw new ProviderError(`ComfyUI answered HTTP ${res.status} for EXR frame ${i + 1}`);
+ }
+ data = Buffer.from(await res.arrayBuffer());
+ } catch (e) {
+ throw full(e);
+ }
+ total += data.length;
+ yield { name: `frame_${String(i + 1).padStart(5, "0")}.exr`, data };
}
}
- await zipToFile(files(), dest);
+ try {
+ await zipToFile(files(), dest);
+ } catch (e) {
+ fs.rmSync(dest, { force: true });
+ throw e;
+ }
const zip = adoptFile({ from: dest, contentType: "application/zip", name: "exr-frames.zip", source: "generation", generationId: generationId || undefined });
return rest.map((o) => (o === preview ? { ...o, meta: { ...o.meta, artifacts: { exr: zip.url }, frames: frames.length } } : o));
}
@@ -798,8 +850,13 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,
// Media refs in params.extra (e.g. a background stem for "audio2") are uploaded like regular inputs.
for (const [k, v] of Object.entries(extra)) {
if (!isMediaRef(v)) continue;
- const f = await readRef(v);
- extra[k] = await ctx.upload(f.data, f.contentType, f.name);
+ // An account's file is read and sent when it may send (account-send.ts), as the run's other inputs are.
+ const send = async () => {
+ const f = await readRef(v);
+ return ctx.upload(f.data, f.contentType, f.name);
+ };
+ const account = ownGpu() ? tenantAccount() : undefined;
+ extra[k] = await (account ? accountSend(account, send) : send());
}
// The variant this request runs (one graph per clip count, the single-track soundtrack, EXR frames, a Fun Camera pose,
// the product shot): src/lib/comfy-variants.ts, which the GPU pre-flight's gate reads too. A LoRA mixed into a pose is
@@ -1356,6 +1413,7 @@ async function uploadTo(worker: ComfyWorker, data: Buffer, contentType: string,
form.append("overwrite", "true");
const res = await comfyFetch("/upload/image", { method: "POST", body: form }, worker);
if (res.status === 413) {
+ discardBody(res);
// ComfyUI's own limit (--max-upload-size, 100 MB unless it was started with more).
const mb = Math.ceil(data.length / 2 ** 20);
throw new ProviderError(`ComfyUI refused a ${mb} MB upload as too large (its --max-upload-size, 100 MB unless set) — start ComfyUI with a higher --max-upload-size, or send a smaller file`);
@@ -1557,7 +1615,10 @@ export const comfyProvider: ProviderAdapter = {
async test(opts) {
const describe = async (worker: ComfyWorker) => {
const res = await comfyFetch("/system_stats", {}, worker);
- if (!res.ok) throw new ProviderError(`HTTP ${res.status}`);
+ if (!res.ok) {
+ discardBody(res);
+ throw new ProviderError(`HTTP ${res.status}`);
+ }
const s = (await res.json()) as { system?: { comfyui_version?: string }; devices?: { name?: string; vram_total?: number }[] };
const dev = s.devices?.[0];
return `ComfyUI ${s.system?.comfyui_version ?? ""} · ${dev?.name ?? "unknown device"}${dev?.vram_total ? ` · ${(dev.vram_total / 2 ** 30).toFixed(0)} GB` : ""}`;
@@ -1593,6 +1654,7 @@ export const comfyProvider: ProviderAdapter = {
export async function comfyLoraFiles(route?: ModelRoute): Promise<string[] | null> {
try {
const res = await comfyFetch("/models/loras", {}, workerFor(route?.endpoint));
+ if (!res.ok) discardBody(res);
return res.ok ? ((await res.json()) as string[]) : null;
} catch {
return null;
diff --git a/src/server/remote-fetch.ts b/src/server/remote-fetch.ts
index 5c1b9400..bdee2886 100644
--- a/src/server/remote-fetch.ts
+++ b/src/server/remote-fetch.ts
@@ -337,6 +337,11 @@ export interface PublicFetchOptions extends Pick<RemoteFetchOptions, "resolve" |
export const PUBLIC_FETCH_MAX_BYTES = 8 * 2 ** 20;
+/** Let go of an answer whose body won't be read (an error status): its connection closes now (fetchPublic). */
+export function discardBody(res: Response): void {
+ if (res.body && !res.bodyUsed) res.body.cancel().catch(() => {});
+}
+
const mbOf = (n: number) => (n >= 2 ** 30 ? `${Math.round(n / 2 ** 30)} GB` : `${Math.max(1, Math.round(n / 2 ** 20))} MB`);
export async function fetchPublic(url: string, init: RequestInit = {}, o: PublicFetchOptions = {}): Promise<Response> {
@@ -416,7 +421,12 @@ export async function fetchPublic(url: string, init: RequestInit = {}, o: Public
const stream = counted;
res.on("error", (e) => stream.destroy(e));
res.on("aborted", () => stream.destroy(new RemoteFetchError(`${target.host} stopped answering`)));
- stream.on("close", () => clearTimeout(deadline));
+ // Read to its end, failed, or let go by the caller (discardBody): the connection closes at once, never held
+ // open until the deadline.
+ stream.on("close", () => {
+ clearTimeout(deadline);
+ if (!res.complete) res.destroy();
+ });
res.pipe(stream);
settle(undefined, new Response(Readable.toWeb(stream) as ReadableStream<Uint8Array>, { status, statusText: res.statusMessage, headers: out }));
});
diff --git a/src/server/shorts.ts b/src/server/shorts.ts
index 8ca9f550..81c360a3 100644
--- a/src/server/shorts.ts
+++ b/src/server/shorts.ts
@@ -41,7 +41,7 @@ import { getGeneration, previewChained } from "./generations";
import { trashGenerations } from "./library";
import { firstOn } from "./model-access";
import { engineMode } from "./settings";
-import { readRef } from "./storage";
+import { readRef, RefError } from "./storage";
import { mediaFacts, type SourceInfo } from "./media-facts";
/**
@@ -78,7 +78,9 @@ export async function probeSource(url: string): Promise<SourceInfo> {
let data: Buffer;
try {
data = (await readRef(url)).data;
- } catch {
+ } catch (e) {
+ // An account's clip over an upload's size says so; another's file answers like one that is gone.
+ if (e instanceof RefError && e.status === 413) throw new ShortsError(e.message, 413);
throw new ShortsError("That clip is gone — upload it again", 404);
}
return sourceInfo(data);
diff --git a/src/server/storage.ts b/src/server/storage.ts
index a5000561..00fa2656 100644
--- a/src/server/storage.ts
+++ b/src/server/storage.ts
@@ -6,6 +6,7 @@ import { DATA_DIR, db } from "./db";
import type { MediaKind } from "@/lib/catalog/types";
import { fetchRemote } from "./remote-fetch";
import { tenant, tenantAccount } from "./tenant";
+import { accountInputLimit } from "./account-files";
import { assetAccount, fileAccount, generationAccount } from "./account-library";
export const FILES_DIR = path.join(DATA_DIR, "files");
@@ -152,15 +153,15 @@ function ownerOf(opts: NewAsset): string | null {
/**
* Store a file under files/<outputs|uploads>/<day>/<id>.<ext>: `put` writes it there, then its row is added. The
- * extension comes from the type. A type Fuobe doesn't know is stored as .bin, except the owner's provider files with a
- * plain extension of their own (a rig's .fbx): an upload's or an account's file name never picks it.
+ * extension comes from the type. A type Fuobe doesn't know keeps the plain extension of the owner's file name (a rig's
+ * .fbx, an Assist source's .pdf or .md), never a page or script one (.html, .svg, .js), and an account's file name never
+ * picks it: those are stored as .bin.
*/
function addAsset(opts: NewAsset, put: (abs: string) => void): Asset {
const id = nanoid(12);
const account = ownerOf(opts);
const named = opts.name?.includes(".") ? opts.name.split(".").pop()?.toLowerCase() : undefined;
- const fromName =
- opts.source !== "upload" && !account && named && /^[a-z0-9]{1,8}$/.test(named) && !/^(html?|xht|xhtml|xml|svgz?|js|mjs)$/.test(named) ? named : undefined;
+ const fromName = !account && named && /^[a-z0-9]{1,8}$/.test(named) && !/^(html?|xht|xhtml|xml|svgz?|js|mjs)$/.test(named) ? named : undefined;
const ext = EXT_BY_TYPE[opts.contentType.split(";")[0].trim()] ?? fromName ?? "bin";
const day = new Date().toISOString().slice(0, 10);
const relPath = path.join(/*turbopackIgnore: true*/ opts.source === "generation" ? "outputs" : "uploads", day, `${id}.${ext}`);
@@ -253,7 +254,7 @@ export function absolutePath(relPath: string): string {
*/
export function localHead(ref: string, maxBytes = 512 * 1024): Buffer | null {
try {
- const rel = ref.startsWith("/api/files/") ? decodeURIComponent(ref.slice("/api/files/".length).split("?")[0]) : /^[\w-]{6,40}$/.test(ref) ? getAsset(ref)?.relPath : undefined;
+ const rel = ref.startsWith("/api/files/") ? filesRel(ref) : /^[\w-]{6,40}$/.test(ref) ? getAsset(ref)?.relPath : undefined;
if (!rel) return null;
// A visitor's price check or an account's run: only its own files, and no word on whether another one exists.
if (tenant() && !ownsRef(ref, rel)) return null;
@@ -275,8 +276,16 @@ export function localHead(ref: string, maxBytes = 512 * 1024): Buffer | null {
* to bytes + content type.
*/
export async function readRef(ref: string): Promise<{ data: Buffer; contentType: string; name: string }> {
- // An account's run (or a visitor's price check): only its own files (guardRef).
+ // An account's run (or a visitor's price check): only its own files (guardRef), and none bigger than an upload may be.
if (tenant()) guardRef(ref);
+ const read = async (abs: string, contentType: string) => {
+ if (tenant()) {
+ const limit = accountInputLimit(contentType);
+ if ((await fs.promises.stat(abs)).size > limit.bytes) throw new RefError(limit.message, 413);
+ }
+ // Read without holding up the server.
+ return fs.promises.readFile(abs);
+ };
if (ref.startsWith("data:")) {
const m = /^data:([^;,]+)?(;base64)?,(.*)$/s.exec(ref);
if (!m) throw new Error("Malformed data URI");
@@ -285,9 +294,12 @@ export async function readRef(ref: string): Promise<{ data: Buffer; contentType:
return { data, contentType, name: `input.${EXT_BY_TYPE[contentType] ?? "bin"}` };
}
if (ref.startsWith("/api/files/")) {
- const rel = decodeURIComponent(ref.slice("/api/files/".length));
+ // The same path guardRef checked: the query left out, decoded once, never a step out of its folder.
+ const rel = filesRel(ref);
+ if (rel === null) throw new Error("Invalid path");
const abs = absolutePath(rel);
- return { data: fs.readFileSync(abs), contentType: contentTypeFor(abs), name: path.basename(abs) };
+ const contentType = contentTypeFor(abs);
+ return { data: await read(abs, contentType), contentType, name: path.basename(abs) };
}
if (/^https?:\/\//.test(ref)) {
// Public links only: never this machine or its private network (see remote-fetch.ts).
@@ -299,7 +311,7 @@ export async function readRef(ref: string): Promise<{ data: Buffer; contentType:
const asset = getAsset(ref);
if (!asset) throw new Error(`Unknown asset ${ref}`);
return {
- data: fs.readFileSync(absolutePath(asset.relPath)),
+ data: await read(absolutePath(asset.relPath), asset.contentType),
contentType: asset.contentType,
name: asset.name ?? path.basename(asset.relPath),
};
@@ -308,11 +320,11 @@ export async function readRef(ref: string): Promise<{ data: Buffer; contentType:
// ---------------------------------------------------------------------------
// Public sign-up: an account's run reads only its own files
-/** A file a run may not read: `status` is the HTTP answer a route gives (403, or 404 for one that is gone). */
+/** A file a run may not read: `status` is the HTTP answer a route gives (403; 404 for one that is gone; 413 too big). */
export class RefError extends Error {
constructor(
message: string,
- readonly status: 403 | 404,
+ readonly status: 403 | 404 | 413,
) {
super(message);
}
@@ -322,14 +334,20 @@ export const LINK_INPUT_MESSAGE = "Upload the file first. Runs on your GPU can't
export const NOT_YOURS_MESSAGE = "That file isn't yours. Upload your own.";
export const GONE_MESSAGE = "That file has expired. Upload it again.";
-/** A stored file's path under the files folder, from an /api/files/… reference (null: not one, or not decodable). */
-function filesRel(ref: string): string | null {
+/**
+ * A stored file's path under the files folder, from an /api/files/… reference: the query and fragment left out, then
+ * decoded once. Null when it isn't one, doesn't decode, or a part of it is empty, "." or "..", or holds a backslash, a
+ * colon or a NUL. Every check and every read goes by it, so the path a check looks up is always the path that is read.
+ */
+export function filesRel(ref: string): string | null {
if (!ref.startsWith("/api/files/")) return null;
+ let rel: string;
try {
- return decodeURIComponent(ref.slice("/api/files/".length).split("?")[0]);
+ rel = decodeURIComponent(ref.slice("/api/files/".length).split(/[?#]/)[0]);
} catch {
return null;
}
+ return rel.split("/").every((p) => p && p !== "." && p !== ".." && !/[\\:\0]/.test(p)) ? rel : null;
}
/** Whether the tenant owns this file (an account: its own; a guest: none). */
diff --git a/tests/account-review-fixes.test.ts b/tests/account-review-fixes.test.ts
new file mode 100644
index 00000000..91ded560
--- /dev/null
+++ b/tests/account-review-fixes.test.ts
@@ -0,0 +1,416 @@
+import fs from "node:fs";
+import http from "node:http";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";
+
+/**
+ * The review of "Your GPU" tools (public sign-up): each test here shows one problem the review found, and stays as the
+ * guard against it coming back.
+ */
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-account-review-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_ALLOW_PRIVATE_URLS;
+delete process.env.FUOBE_ACCOUNT_DISK_FREE_GB;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const realFetch = globalThis.fetch;
+globalThis.fetch = (async () => new Response("not stubbed", { status: 599 })) as typeof fetch;
+
+const auth = await import("@/server/auth");
+const generationsRoute = await import("@/app/api/generations/route");
+const probeRoute = await import("@/app/api/media/probe/route");
+const { accountLoraFix, accountRun, getGeneration } = await import("@/server/generations");
+const { comfyProvider } = await import("@/server/providers/comfyui");
+const { saveFile, readRef, scratchDir, filesRel, absolutePath } = await import("@/server/storage");
+const { accountInputProblem } = await import("@/server/account-inputs");
+const { ACCOUNT_LIMITS, accountUsage, diskFloorBytes } = await import("@/server/account-files");
+const { accountSend, accountSends, inTurn } = await import("@/server/account-send");
+const { sweepAccountFiles } = await import("@/server/account-sweep");
+const { decodePng, pngPixelLimit, MAX_PNG_PIXELS } = await import("@/server/png");
+const { runAsTenant } = await import("@/server/tenant");
+const { discardBody, fetchPublic } = await import("@/server/remote-fetch");
+const { PRESETS } = await import("@/lib/catalog");
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const { clearAccountLoras } = await import("@/server/account-loras");
+
+let fake: FakeComfy;
+let a = "";
+let b = "";
+let cookie = "";
+beforeAll(async () => {
+ fake = await startFakeComfy({ loras: [], delayMs: 0 });
+ globalThis.__fuobeTestGpuPort = fake.port;
+ auth.setPassword("install password");
+ a = auth.createAccount("[email protected]", "long enough").id;
+ b = auth.createAccount("[email protected]", "long enough").id;
+ auth.setAccountGpu(a, { url: fake.url });
+ cookie = `${auth.SESSION_COOKIE}=${auth.createSession(a).value}`;
+});
+afterAll(async () => {
+ globalThis.fetch = realFetch;
+ globalThis.__fuobeTestGpuPort = undefined;
+ globalThis.__fuobeTestDiskFree = undefined;
+ globalThis.__fuobeTestDiskSize = undefined;
+ await fake.close();
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+beforeEach(() => {
+ resetRates();
+ clearAccountLoras(a);
+ Object.assign(fake.opts, { loras: [], delayMs: 0, drip: false, huge: false, promptId: undefined, missing: undefined, output: "video", layers: undefined, frames: undefined, historyError: undefined, uploadStatus: undefined });
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running') AND json_extract(request_json, '$.account') IS NOT NULL").run();
+});
+
+const json = (url: string, body: unknown) => {
+ const text = JSON.stringify(body);
+ return new Request(`http://localhost:3000${url}`, { method: "POST", headers: { cookie, host: "localhost:3000", "content-type": "application/json", "content-length": String(Buffer.byteLength(text)) }, body: text });
+};
+
+/** A PNG the owner made (no account), and one account A uploaded. */
+const OWNER_PNG = Buffer.concat([TINY_PNG, Buffer.from("OWNER-SECRET-PIXELS")]);
+const ownerFile = () => saveFile({ data: OWNER_PNG, contentType: "image/png", source: "generation" });
+const mine = (account = a) => saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload", accountId: account });
+/** "/api/files/uploads/<day>/<mine>.png?/../../../outputs/<day>/<target>.png": one path to check, another to read. */
+const crafted = (own: { url: string }, target: { relPath: string }) => `${own.url}?/../../../${target.relPath.split(path.sep).join("/")}`;
+const asA = <T,>(fn: () => T): T => {
+ const own = accountRun(a, "comfyui");
+ if (!("run" in own)) throw new Error(own.error);
+ return own.run(fn);
+};
+
+async function settle(id: string, ms = 15_000) {
+ const end = Date.now() + ms;
+ for (;;) {
+ await globalThis.__fuobeRunner?.tick();
+ const g = getGeneration(id, { includeDeleted: true });
+ if (!g || (g.status !== "queued" && g.status !== "running") || Date.now() > end) return g;
+ await new Promise((r) => setTimeout(r, 150));
+ }
+}
+
+describe("a '?' in a file reference can't reach another file", () => {
+ it("reads the file the check looked up, never the one after '?/../'", async () => {
+ const target = ownerFile();
+ const own = mine();
+ const ref = crafted(own, target);
+ // The check and the read take the same path.
+ expect(filesRel(ref)).toBe(own.relPath.split(path.sep).join("/"));
+ expect(accountInputProblem({ inputs: { images: [ref] } }, a)).toBeNull();
+ const read = await asA(() => readRef(ref));
+ expect(read.data.equals(TINY_PNG)).toBe(true);
+ expect(read.data.includes(Buffer.from("OWNER-SECRET-PIXELS"))).toBe(false);
+ });
+
+ it("refuses a reference that steps out of its folder", () => {
+ const own = mine();
+ const day = path.dirname(own.relPath).split(path.sep).join("/");
+ for (const ref of [`/api/files/${day}/../${path.basename(own.relPath)}`, `/api/files/${day}/%2e%2e/x.png`, `/api/files/${day}\\..\\x.png`, `/api/files/${day}//x.png`]) {
+ expect(filesRel(ref), ref).toBeNull();
+ expect(accountInputProblem({ inputs: { images: [ref] } }, a)?.code, ref).toBe("input-not-allowed");
+ }
+ });
+
+ it("sends the account's own picture to its ComfyUI, not the owner's, for a run named with '?/../'", async () => {
+ const target = ownerFile();
+ const own = mine();
+ fake.log.length = 0;
+ const r = await generationsRoute.POST(json("/api/generations", { feature: "video", modelId: "fuobe-dop", presetId: "motion-zoom-in", prompt: "", inputs: { images: [crafted(own, target)] } }));
+ expect(r.status).toBe(201);
+ const g = await settle((await r.json()).items[0].id);
+ expect(g?.status, g?.error ?? "").toBe("succeeded");
+ const up = fake.log.filter((e) => e.path === "/upload/image");
+ expect(up.length).toBeGreaterThan(0);
+ for (const e of up) expect(e.upload?.includes(Buffer.from("OWNER-SECRET-PIXELS"))).toBe(false);
+ });
+
+ it("reads params.extra and a clip check the same way", async () => {
+ const target = ownerFile();
+ const own = mine();
+ const ref = crafted(own, target);
+ expect(accountInputProblem({ params: { extra: { audio2: ref } } }, a)).toBeNull();
+ const { probeSource } = await import("@/server/shorts");
+ // The probe reads the account's own picture (not a clip: no facts), never the owner's file.
+ await expect(runAsTenant({ kind: "account", id: a }, () => probeSource(ref))).resolves.toEqual({});
+ });
+});
+
+describe("an account's big files stay out of its runs", () => {
+ it("refuses its own result over an upload's size as a run's input, at the route and when a step reads it", async () => {
+ const big = saveFile({ data: Buffer.alloc(ACCOUNT_LIMITS.imageBytes + 1, 1), contentType: "image/png", source: "generation", accountId: a });
+ expect(accountInputProblem({ inputs: { images: [big.url] } }, a)).toMatchObject({ status: 413, code: "input-too-big" });
+ await expect(asA(() => readRef(big.url))).rejects.toMatchObject({ status: 413, message: expect.stringMatching(/over 25 MB/) });
+ // The owner's own reads are as before.
+ await expect(readRef(big.url)).resolves.toBeTruthy();
+ const r = await generationsRoute.POST(json("/api/generations", { feature: "video", modelId: "fuobe-dop", presetId: "motion-zoom-in", prompt: "", inputs: { images: [big.url] } }));
+ expect(r.status).toBe(413);
+ expect((await r.json()).code).toBe("input-too-big");
+ });
+});
+
+describe("the clip check has limits for accounts", () => {
+ it("allows 60 a minute, then answers 429", async () => {
+ const own = mine();
+ const ask = () => probeRoute.POST(json("/api/media/probe", { url: own.url }));
+ for (let i = 0; i < 60; i++) expect((await ask()).status).toBe(200);
+ const r = await ask();
+ expect(r.status).toBe(429);
+ expect((await r.json()).error).toMatch(/Wait a moment/);
+ });
+
+ it("says a clip is too big rather than reading it", async () => {
+ const big = saveFile({ data: Buffer.alloc(ACCOUNT_LIMITS.videoBytes + 1, 1), contentType: "video/mp4", source: "generation", accountId: a });
+ const r = await probeRoute.POST(json("/api/media/probe", { url: big.url }));
+ expect(r.status).toBe(413);
+ expect((await r.json()).error).toMatch(/over 95 MB/);
+ });
+});
+
+describe("an account's ComfyUI can't make the server download without end", () => {
+ async function pollAs(workflowId: string) {
+ fake.opts.promptId = `job-${workflowId}-${Date.now()}`;
+ await realFetch(`${fake.url}/prompt`, { method: "POST", body: JSON.stringify({ prompt: {} }) });
+ const externalId = fake.opts.promptId;
+ fake.log.length = 0;
+ return asA(() => comfyProvider.poll({ externalId, meta: { workflowId, generationId: `g-${workflowId}` } } as never));
+ }
+
+ it("reads at most 16 layers, one at a time", async () => {
+ fake.opts.layers = 300;
+ const res = await pollAs("layers-qwen-image-layered");
+ expect(res.state).toBe("succeeded");
+ expect(fake.log.filter((e) => e.path.startsWith("/view")).length).toBeLessThanOrEqual(ACCOUNT_LIMITS.outputsPerJob);
+ // The boxed layers stay links (saved later, straight to disk), never data held in memory.
+ const outs = (res as { outputs: { url: string; meta?: { bbox?: unknown } }[] }).outputs;
+ expect(outs.filter((o) => o.meta?.bbox).length).toBe(ACCOUNT_LIMITS.outputsPerJob);
+ expect(outs.some((o) => o.url.startsWith("data:"))).toBe(false);
+ });
+
+ it("refuses an EXR export with more frames than a clip has, before downloading any", async () => {
+ fake.opts.frames = ACCOUNT_LIMITS.framesPerJob + 1;
+ const res = await pollAs("video-export-exr");
+ expect(res).toMatchObject({ state: "failed", error: expect.stringMatching(/EXR frames.*export a shorter clip/) });
+ expect(fake.log.filter((e) => e.path.startsWith("/view")).length).toBe(0);
+ });
+
+ it("stops the frames at what the account's files have room for, and leaves no zip", async () => {
+ fake.opts.frames = 3;
+ const filler = saveFile({ data: Buffer.alloc(16), contentType: "image/png", source: "generation", accountId: a });
+ // 6 bytes left: the first frame (4 bytes) fits, the second doesn't.
+ db().prepare("UPDATE assets SET size = ? WHERE id = ?").run(ACCOUNT_LIMITS.totalBytes - 6 - (accountUsage(a).total - 16), filler.id);
+ try {
+ const before = fs.readdirSync(scratchDir()).filter((f) => f.endsWith(".zip")).length;
+ const res = await pollAs("video-export-exr");
+ expect(res).toMatchObject({ state: "failed", error: expect.stringMatching(/reached 3 GB/) });
+ expect(fs.readdirSync(scratchDir()).filter((f) => f.endsWith(".zip")).length).toBe(before);
+ } finally {
+ db().prepare("DELETE FROM assets WHERE id = ?").run(filler.id);
+ }
+ });
+
+ it("saves a result only up to what the account's files have room for", async () => {
+ fake.opts.huge = true;
+ const filler = saveFile({ data: Buffer.alloc(16), contentType: "image/png", source: "generation", accountId: a });
+ // 1 MB left: the result streams without end.
+ db().prepare("UPDATE assets SET size = ? WHERE id = ?").run(ACCOUNT_LIMITS.totalBytes - 2 ** 20 - (accountUsage(a).total - 16), filler.id);
+ try {
+ const own = mine();
+ const r = await generationsRoute.POST(json("/api/generations", { feature: "video", modelId: "fuobe-dop", presetId: "motion-zoom-in", prompt: "", inputs: { images: [own.url] } }));
+ expect(r.status).toBe(201);
+ const id = (await r.json()).items[0].id as string;
+ const g = await settle(id);
+ expect(g?.status).toBe("failed");
+ expect(g?.error).toMatch(/reached 3 GB/);
+ expect(fs.readdirSync(scratchDir()).filter((f) => f.startsWith(`${id}-out-`))).toEqual([]);
+ } finally {
+ db().prepare("DELETE FROM assets WHERE id = ?").run(filler.id);
+ }
+ });
+});
+
+describe("an answer that won't be read lets its connection go", () => {
+ it("closes the socket of an error answer at once (fetchPublic + discardBody, and the ComfyUI poll)", async () => {
+ let closed = 0;
+ const server = http.createServer((_req, res) => {
+ res.writeHead(500, { "content-type": "text/plain" });
+ res.write("x");
+ res.on("close", () => closed++);
+ });
+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", () => r()));
+ const port = (server.address() as { port: number }).port;
+ const was = globalThis.__fuobeTestGpuPort;
+ globalThis.__fuobeTestGpuPort = port;
+ try {
+ const res = await fetchPublic(`http://127.0.0.1:${port}/history/x`, {}, { deadlineMs: 60_000 });
+ expect(res.status).toBe(500);
+ discardBody(res);
+ await new Promise((r) => setTimeout(r, 300));
+ expect(closed).toBe(1);
+ // A poll against a ComfyUI that answers /history with an error and then nothing.
+ const run = accountRun(a, "comfyui");
+ if (!("run" in run)) throw new Error(run.error);
+ auth.setAccountGpu(a, { url: `http://127.0.0.1:${port}` });
+ const own = accountRun(a, "comfyui");
+ if (!("run" in own)) throw new Error(own.error);
+ await expect(own.run(() => comfyProvider.poll({ externalId: "abc", meta: {} } as never))).rejects.toThrow(/HTTP 500/);
+ await new Promise((r) => setTimeout(r, 300));
+ expect(closed).toBe(2);
+ } finally {
+ auth.setAccountGpu(a, { url: fake.url });
+ globalThis.__fuobeTestGpuPort = was;
+ server.closeAllConnections?.();
+ await new Promise<void>((r) => server.close(() => r()));
+ }
+ });
+});
+
+describe("the account sweep never wipes accounts on a bad read of the auth file", () => {
+ it("keeps every account's files when the auth file can't be read, or lists no accounts", async () => {
+ const own = mine(b);
+ const file = path.join(dir, "auth.json");
+ const good = fs.readFileSync(file);
+ try {
+ fs.writeFileSync(file, "{ not json");
+ expect((await sweepAccountFiles()).accounts).toBe(0);
+ expect(fs.existsSync(absolutePath(own.relPath))).toBe(true);
+ fs.rmSync(file);
+ expect((await sweepAccountFiles()).accounts).toBe(0);
+ expect(fs.existsSync(absolutePath(own.relPath))).toBe(true);
+ // A file put back from before the sign-ups (no accounts in it) while accounts own files here.
+ fs.writeFileSync(file, JSON.stringify({ secret: "s", tokens: [] }));
+ expect((await sweepAccountFiles()).accounts).toBe(0);
+ expect(fs.existsSync(absolutePath(own.relPath))).toBe(true);
+ } finally {
+ fs.writeFileSync(file, good);
+ }
+ // Read whole, a deleted account's files still go.
+ const gone = auth.createAccount("[email protected]", "long enough").id;
+ const theirs = mine(gone);
+ auth.deleteAccount(gone);
+ expect((await sweepAccountFiles()).accounts).toBe(1);
+ expect(fs.existsSync(absolutePath(theirs.relPath))).toBe(false);
+ expect(fs.existsSync(absolutePath(own.relPath))).toBe(true);
+ });
+
+ it("removes a result's download and a zip left behind, after six hours", async () => {
+ const stale = path.join(scratchDir(), "gen-out-abcdefgh");
+ const zip = path.join(scratchDir(), "gen-abcdef.zip");
+ const fresh = path.join(scratchDir(), "gen2-out-abcdefgh");
+ for (const f of [stale, zip, fresh]) fs.writeFileSync(f, "x");
+ const old = new Date(Date.now() - 7 * 60 * 60_000);
+ fs.utimesSync(stale, old, old);
+ fs.utimesSync(zip, old, old);
+ await sweepAccountFiles();
+ expect(fs.existsSync(stale)).toBe(false);
+ expect(fs.existsSync(zip)).toBe(false);
+ expect(fs.existsSync(fresh)).toBe(true);
+ fs.rmSync(fresh, { force: true });
+ });
+});
+
+describe("one slow account can't hold every file send", () => {
+ it("sends one file at a time per account, and hands a free slot to an account that isn't sending", async () => {
+ const gates: (() => void)[] = [];
+ const slow = (who: string) => accountSend(who, () => new Promise<string>((r) => gates.push(() => r(who))));
+ const a1 = slow("A");
+ const a2 = slow("A");
+ const a3 = slow("A");
+ await new Promise((r) => setTimeout(r, 10));
+ expect(accountSends()).toMatchObject({ total: 1, busy: { A: 1 } });
+ const b1 = accountSend("B", async () => "B");
+ expect(await b1).toBe("B");
+ gates.shift()!();
+ expect(await a1).toBe("A");
+ await new Promise((r) => setTimeout(r, 10));
+ expect(accountSends().busy.A).toBe(1);
+ gates.shift()!();
+ await a2;
+ await new Promise((r) => setTimeout(r, 10));
+ gates.shift()!();
+ await a3;
+ expect(accountSends()).toMatchObject({ total: 0, waiting: [] });
+ });
+
+ it("takes turns between accounts: one with many waiting goes to the back after each (the 3D finish line too)", async () => {
+ const order: string[] = [];
+ const job = (who: string) =>
+ inTurn("test-turns", 1, who, async () => {
+ order.push(who);
+ await new Promise((r) => setTimeout(r, 5));
+ });
+ const all = [job("A"), job("A"), job("A")];
+ await new Promise((r) => setTimeout(r, 1));
+ all.push(job("B"));
+ await Promise.all(all);
+ expect(order).toEqual(["A", "B", "A", "A"]);
+ });
+
+ it("sends none of a run's other files once one has failed", async () => {
+ fake.opts.uploadStatus = 500;
+ fake.log.length = 0;
+ const pics = [mine(), mine(), mine()];
+ const r = await generationsRoute.POST(json("/api/generations", { feature: "image", modelId: "oss-qwen-edit", prompt: "Make the jacket red", inputs: { images: pics.map((p) => p.url) } }));
+ expect(r.status, await r.clone().text()).toBe(201);
+ const g = await settle((await r.json()).items[0].id);
+ expect(g?.status).toBe("failed");
+ expect(g?.error).toMatch(/upload/i);
+ expect(fake.log.filter((e) => e.path === "/upload/image")).toHaveLength(1);
+ expect(accountSends()).toMatchObject({ total: 0, waiting: [] });
+ });
+});
+
+describe("a Mixed Media effect's first step is checked for its LoRAs before the run is queued", () => {
+ it("names the look's LoRA the account's ComfyUI lacks (409), and keeps the fix on a step that fails later", async () => {
+ const preset = PRESETS.find((p) => p.open && p.prestep?.open.labels && p.prestep.open.loras?.length);
+ expect(preset, "a DoP Mixed Media effect with a LoRA").toBeTruthy();
+ const modelId = preset!.open!.modelId;
+ const own = mine();
+ const req = { feature: "video", modelId, presetId: preset!.id, prompt: "", inputs: { images: [own.url] }, account: a, engine: "open" } as never;
+ const fix = await asA(() => accountLoraFix(req));
+ const files = (preset!.prestep!.open.loras ?? []).map((l) => l.file);
+ expect(fix?.items.map((i) => i.file)).toEqual(expect.arrayContaining(files));
+ const r = await generationsRoute.POST(json("/api/generations", { feature: "video", modelId, presetId: preset!.id, prompt: "", inputs: { images: [own.url] } }));
+ expect(r.status).toBe(409);
+ expect((await r.json()).fix.items.map((i: { file: string }) => i.file)).toEqual(expect.arrayContaining(files));
+ });
+});
+
+describe("the owner's own work is as before", () => {
+ it("keeps the extension of the owner's file name for a type Fuobe doesn't map, never a page's; an account's is .bin", () => {
+ expect(saveFile({ data: Buffer.from("%PDF-1.7"), contentType: "application/pdf", name: "brief.pdf", source: "upload" }).relPath).toMatch(/\.pdf$/);
+ expect(saveFile({ data: Buffer.from("# notes"), contentType: "application/octet-stream", name: "notes.md", source: "upload" }).relPath).toMatch(/\.md$/);
+ expect(saveFile({ data: Buffer.from("<b>"), contentType: "text/html", name: "page.html", source: "upload" }).relPath).toMatch(/\.bin$/);
+ expect(saveFile({ data: Buffer.from("%PDF-1.7"), contentType: "application/pdf", name: "brief.pdf", source: "upload", accountId: a }).relPath).toMatch(/\.bin$/);
+ });
+
+ it("decodes the owner's large pictures; an account's stop at 40 megapixels", () => {
+ expect(pngPixelLimit()).toBeGreaterThanOrEqual(48_000_000);
+ expect(runAsTenant({ kind: "account", id: a }, () => pngPixelLimit())).toBe(MAX_PNG_PIXELS);
+ // An 8000 x 6000 claim: past the account's limit before anything is inflated.
+ const ihdr = Buffer.from(TINY_PNG);
+ ihdr.writeUInt32BE(8000, 16);
+ ihdr.writeUInt32BE(6000, 20);
+ expect(() => runAsTenant({ kind: "account", id: a }, () => decodePng(ihdr))).toThrow(/40 megapixels/);
+ });
+
+ it("keeps a share of a small disk free, not a fixed 20 GB, and the owner can set it", () => {
+ const GB = 2 ** 30;
+ expect(diskFloorBytes(40 * GB)).toBe(4 * GB);
+ expect(diskFloorBytes(10 * GB)).toBe(2 * GB);
+ expect(diskFloorBytes(2000 * GB)).toBe(20 * GB);
+ process.env.FUOBE_ACCOUNT_DISK_FREE_GB = "5";
+ try {
+ expect(diskFloorBytes(2000 * GB)).toBe(5 * GB);
+ } finally {
+ delete process.env.FUOBE_ACCOUNT_DISK_FREE_GB;
+ }
+ });
+});
diff --git a/tests/account-tools.test.ts b/tests/account-tools.test.ts
index 0a11c3cc..b7a26846 100644
--- a/tests/account-tools.test.ts
+++ b/tests/account-tools.test.ts
@@ -177,6 +177,8 @@ describe("an account runs the catalogue on its own ComfyUI", () => {
expect(done?.status).toBe("failed");
expect(done?.error).toMatch(/^Your ComfyUI doesn't have a LoRA file this needs/);
expect(done?.error).toContain("motionpushin-v5-wan-i2v-14b-720p-400.safetensors");
+ // What was missing stays on the failed step, so its tile can offer the pre-flight's "Fix it".
+ expect(done?.fix).toMatchObject({ code: "comfy_missing_model", items: [{ folder: "loras", file: "motionpushin-v5-wan-i2v-14b-720p-400.safetensors" }] });
expect(fake.log.some((e) => e.path === "/upload/image")).toBe(false);
// With the file there, the same run goes ahead.
fake.opts.loras = ["motionpushin-v5-wan-i2v-14b-720p-400.safetensors"];
diff --git a/tests/glb-finish-safety.test.ts b/tests/glb-finish-safety.test.ts
index 82bd2c89..3d0bbd21 100644
--- a/tests/glb-finish-safety.test.ts
+++ b/tests/glb-finish-safety.test.ts
@@ -55,7 +55,7 @@ function glb(image?: string): Buffer {
return Buffer.concat([header, jh, j, bh, bin]);
}
-const run = (input: string, output: string) => spawnSync(process.execPath, [SCRIPT, "--in", input, "--out", output], { encoding: "utf8", timeout: 60_000, cwd: dir });
+const run = (input: string, output: string, ...extra: string[]) => spawnSync(process.execPath, [SCRIPT, "--in", input, "--out", output, ...extra], { encoding: "utf8", timeout: 60_000, cwd: dir });
describe("the 3D finish reads only the model it was given", () => {
it("refuses a GLB whose image points at another file, and never reads it", () => {
@@ -90,6 +90,20 @@ describe("the 3D finish reads only the model it was given", () => {
expect(fs.existsSync(out)).toBe(true);
});
+ it("refuses an account's model with a texture over 4096 x 4096 before decoding it", async () => {
+ const sharp = (await import("sharp")).default;
+ const big = await sharp({ create: { width: 5000, height: 5000, channels: 3, background: "#808080" } }).png({ compressionLevel: 9 }).toBuffer();
+ const work = fs.mkdtempSync(path.join(dir, "job-"));
+ const raw = path.join(work, "raw.glb");
+ fs.writeFileSync(raw, glb(`data:image/png;base64,${big.toString("base64")}`));
+ const r = run(raw, path.join(work, "web.glb"), "--limits", "account");
+ expect(r.status, r.stderr).toBe(3);
+ expect(r.stderr).toMatch(/texture over 4096 x 4096/);
+ // The owner's model with the same texture is finished as before.
+ const own = run(raw, path.join(work, "own.glb"));
+ expect(own.status, own.stderr).toBe(0);
+ }, 60_000);
+
it("runs the scripts with a short environment, never the server's secrets", () => {
const env = scriptEnv();
expect(env.FUOBE_TEST_SECRET).toBeUndefined();
diff --git a/tests/helpers/fake-comfy-runner.ts b/tests/helpers/fake-comfy-runner.ts
index 065554af..c7a9f4c2 100644
--- a/tests/helpers/fake-comfy-runner.ts
+++ b/tests/helpers/fake-comfy-runner.ts
@@ -7,7 +7,10 @@
*
* Options for tests: `loras` (GET /models/loras), `delayMs` (until the history says done), `drip` (the history
* answers one byte every 2 s, never finishing), `huge` (/view streams without end), `promptId` (the job id /prompt
- * answers), `missing` (a file /prompt answers "not in list" for), `output` ("video" or "image").
+ * answers), `missing` (a file /prompt answers "not in list" for), `output` ("video" or "image"), `layers` (the
+ * history lists that many Qwen-Image-Layered layers, node 60), `frames` (an EXR export: a preview clip, node 5, and
+ * that many frames, node 3), `historyError` (/history answers HTTP 500 and then sends nothing), `uploadStatus` (the HTTP
+ * status /upload/image answers, e.g. 500 to fail every upload).
* This file runs under plain Node too: only erasable TypeScript.
*/
import http from "node:http";
@@ -22,6 +25,10 @@ export interface FakeComfyOptions {
promptId?: string;
missing?: string;
output?: "video" | "image";
+ layers?: number;
+ frames?: number;
+ historyError?: boolean;
+ uploadStatus?: number;
}
export interface FakeLogEntry {
@@ -91,6 +98,7 @@ export function startFakeComfy(opts: FakeComfyOptions = {}, port = 0): Promise<F
if (p === "/object_info") return json(200, {});
if (p === "/upload/image" && req.method === "POST") {
entry.upload = uploadedBytes(body, req.headers["content-type"] ?? "");
+ if (opts.uploadStatus && opts.uploadStatus !== 200) return json(opts.uploadStatus, { error: "upload refused" });
return json(200, { name: `fake_${log.length}.bin`, subfolder: "", type: "input" });
}
if (p === "/prompt" && req.method === "POST") {
@@ -109,6 +117,11 @@ export function startFakeComfy(opts: FakeComfyOptions = {}, port = 0): Promise<F
}
if (p.startsWith("/history/")) {
const id = decodeURIComponent(p.slice("/history/".length));
+ if (opts.historyError) {
+ res.writeHead(500, { "content-type": "text/plain" });
+ res.write("x");
+ return;
+ }
if (opts.drip) {
res.writeHead(200, { "content-type": "application/json" });
const t = setInterval(() => res.write(" "), 2000);
@@ -117,6 +130,10 @@ export function startFakeComfy(opts: FakeComfyOptions = {}, port = 0): Promise<F
}
const started = jobs.get(id);
if (started === undefined || Date.now() - started < (opts.delayMs ?? 0)) return json(200, {});
+ const done = { status: { completed: true, status_str: "success" } };
+ const list = (n: number, ext: string) => Array.from({ length: n }, (_, i) => ({ filename: `fake_${String(i + 1).padStart(5, "0")}_.${ext}`, subfolder: "", type: "output" }));
+ if (opts.layers) return json(200, { [id]: { ...done, outputs: { "60": { images: list(opts.layers, "png") } } } });
+ if (opts.frames) return json(200, { [id]: { ...done, outputs: { "5": { gifs: list(1, "mp4") }, "3": { images: list(opts.frames, "exr") } } } });
const file = opts.output === "image" ? { filename: "fake_00001_.png", subfolder: "", type: "output" } : { filename: "fake_00001.mp4", subfolder: "", type: "output" };
const key = opts.output === "image" ? "images" : "gifs";
return json(200, { [id]: { status: { completed: true, status_str: "success" }, outputs: { "900": { [key]: [file] } } } });
@@ -141,7 +158,12 @@ export function startFakeComfy(opts: FakeComfyOptions = {}, port = 0): Promise<F
pump();
return;
}
- const png = (url.searchParams.get("filename") ?? "").endsWith(".png");
+ const name = url.searchParams.get("filename") ?? "";
+ if (name.endsWith(".exr")) {
+ res.writeHead(200, { "content-type": "image/x-exr" });
+ return res.end(Buffer.from("762f3101", "hex"));
+ }
+ const png = name.endsWith(".png");
res.writeHead(200, { "content-type": png ? "image/png" : "video/mp4" });
return res.end(png ? TINY_PNG : TINY_MP4);
}
diff --git a/tests/runtime-auth.test.ts b/tests/runtime-auth.test.ts
index 569a321e..54095214 100644
--- a/tests/runtime-auth.test.ts
+++ b/tests/runtime-auth.test.ts
@@ -163,4 +163,11 @@ describe("proxy matcher (C13)", () => {
expect(matches("/apple-icon.png")).toBe(false);
expect(matches("/_next/static/chunks/a.js")).toBe(false);
});
+ it("skips only a real dot: a path with 'svg', 'ico' or 'png' after another character still runs the proxy", () => {
+ expect(matches("/api/svg")).toBe(true);
+ expect(matches("/x/svg")).toBe(true);
+ expect(matches("/aXsvg")).toBe(true);
+ expect(matches("/faviconXico")).toBe(true);
+ expect(matches("/apple-iconXpng")).toBe(true);
+ });
});