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: upload pictures, clips and sound, and run camera motions, effects and apps on your own ComfyUI

Adarsh5e6a421ddbc8
diff --git a/docs/public-signup.md b/docs/public-signup.md
index ce2c3e29..20a3a3b1 100644
--- a/docs/public-signup.md
+++ b/docs/public-signup.md
@@ -50,8 +50,8 @@ An account is signed in, but it sees the owner's studio as a guest does:
- **The owner's library stays the owner's.** An account opens every page and the catalog, but the
owner's results, files, uploads, folders, shares, projects (Layers, Cinema, Canvas, storyboards,
elements…) and Assist threads are hidden: the lists come back empty, and other reads answer 403.
- Every change to them (create, rename, move, share, delete, upload) answers 403 with
- `code: "library"`. Accounts have only their own runs (below), no uploads or projects yet.
+ Every change to them (create, rename, move, share, delete) answers 403 with `code: "library"`.
+ Accounts have their own uploads and runs (below), but no projects yet.
- **Settings, keys and tokens are the owner's.** Changing settings or model switches, the password,
API tokens, Public sign-up, LoRA downloads, Assist connectors and the MCP endpoint answer 403 for
an account.
@@ -61,8 +61,11 @@ An account is signed in, but it sees the owner's studio as a guest does:
to run this" card.
- **Its own runs are its own.** The runs an account starts on its GPU appear in its own lists
(`GET /api/generations`), and it can open, cancel and delete them and download their files. They
- stay out of the owner's lists, and no other account can open them. The live-updates stream isn't
- sent to accounts: their studios poll instead.
+ stay out of the owner's lists, and no other account can open them. An account's delete is for
+ good (it has no Trash), so its space comes back at once. The live-updates stream isn't sent to
+ accounts: their studios poll instead.
+- **Its own uploads are its own.** Only the account that uploaded a file can open it or use it in a
+ run. See [Uploads](#uploads).
## Managing accounts
@@ -72,7 +75,9 @@ account off (it is signed out at once and can't log in) or delete it, and export
The API is `GET /api/admin/accounts` (`?format=csv` for the file), `PATCH /api/admin/accounts/<id>`
with `{ "disabled": true | false }`, and `DELETE /api/admin/accounts/<id>`, for the owner only.
-An account can delete itself: `DELETE /api/auth/me` with `{ "password" }`.
+An account can delete itself: `DELETE /api/auth/me` with `{ "password" }`. When an account is
+deleted (by itself or by the owner), its runs are stopped and removed, and its uploads and results
+are deleted with it.
## Your GPU
@@ -99,16 +104,34 @@ cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188
- **Server-side requests.** Addresses on the server itself, on private networks or link-local
addresses are refused. The check runs again on the address each connection actually uses, so a
name that is later pointed at the server can't reach the studio's own ComfyUI. The studio's own
- ComfyUI address is refused too. `FUOBE_ALLOW_PRIVATE_URLS=1` allows private addresses, for a LAN
- install.
-- **Runs.** The Image, Video and Audio studios' generations (`POST /api/generations`) run on the
- account's ComfyUI with the open-source engine. Polls, uploads, outputs and cancels go there too,
- 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. Other
- tools (Canvas, Cinema, Assist…) answer 403 with `code: "own-gpu-tool"`, because they plan with
- the studio's own AI helpers. A LoRA must already be on the account's ComfyUI: the studio
- downloads LoRAs only into its own folder. Accounts can't upload files yet, so runs that start
- from a picture or a clip aren't available to them.
+ ComfyUI address is refused too, and so are IPv6 addresses that wrap an IPv4 address.
+ `FUOBE_ALLOW_PRIVATE_URLS=1` allows private addresses, for a LAN install, but never the server's
+ own addresses. Address checks are limited to 10 a minute.
+- **Runs.** Everything that runs through `POST /api/generations` runs on the account's ComfyUI
+ 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,
+ 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.
+- **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.
+- **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`
+ that lists each file, the folder it goes in and where to download it ("Your ComfyUI doesn't have
+ 2 LoRA files this needs. Download each one into ComfyUI/models/loras, keep the file name, then
+ press Generate again."). The same check runs again when the run is handed to your ComfyUI. A
+ 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.
- **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
@@ -116,10 +139,35 @@ cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188
`GET /api/models` lists the open-source models for a visitor, and the studios price a visitor's
run as it would go on its own GPU. The studio's own settings page isn't shown to visitors.
+## Uploads
+
+An account with its own ComfyUI connected can upload files (`POST /api/uploads`, the file as the
+request body with its type in `Content-Type` and its name in `X-File-Name`; an older page's
+multipart form works up to 26 MB). Without a connected GPU it answers 403 with
+`code: "connect-gpu"`, and a guest gets 401 with the sign-up card.
+
+| What | Types | Largest |
+|---|---|---|
+| Pictures | PNG, JPEG, WebP | 25 MB and 40 megapixels |
+| Sound | MP3, WAV, OGG, FLAC, M4A, WebM | 50 MB |
+| Clips | MP4, MOV, WebM, MKV, AVI | 95 MB (ComfyUI takes up to 100 MB unless started with more) |
+
+- The type is read from the file's first bytes. A file that isn't one of these answers 415.
+- `Content-Length` is required (411), and a file over its size answers 413 before it is read.
+- An account keeps up to 1 GB of uploads and 3 GB of files in all (uploads and results). Past that,
+ uploads and runs answer 413: delete some runs to make room.
+- Up to 60 uploads an hour, 300 a day and 2 at once (429 with `Retry-After`).
+- **How long files stay.** Uploads are removed after 14 days, even when a run still uses them.
+ Runs and their results are removed after 30 days. Everything goes at once when the account is
+ deleted.
+
`GET /api/auth/me` (open to everyone) says who is looking: `{ signedIn, owner, publicSignup,
account? }`.
The rules are in `src/lib/guest-access.ts` (which paths guests and accounts may use) and
`src/proxy.ts` (where they are applied). Your GPU is `src/server/account-gpu.ts`, `onOwnGpu` in
-`src/server/providers/comfyui.ts` and `accountRun` in `src/server/generations.ts`. The tests are in
-`tests/public-signup.test.ts`, `tests/accounts-admin.test.ts` and `tests/account-gpu.test.ts`.
+`src/server/providers/comfyui.ts` and `accountRun` in `src/server/generations.ts`; what an account's
+work may read is `src/server/tenant.ts`. Uploads are `src/app/api/uploads/route.ts` (which makes the
+proxy's checks itself, `src/server/direct-gate.ts`), the limits are in `src/server/account-files.ts`
+and the clean-up in `src/server/account-sweep.ts`. The tests are in `tests/public-signup.test.ts`,
+`tests/accounts-admin.test.ts`, `tests/account-gpu.test.ts` and the `tests/account-*.test.ts` files.
diff --git a/next.config.ts b/next.config.ts
index 7fd3ec2a..f8f8845d 100644
--- a/next.config.ts
+++ b/next.config.ts
@@ -5,8 +5,10 @@ const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
experimental: {
- // The sign-in proxy buffers request bodies (10 MB by default): uploads take up to 200 MB plus the form overhead.
- proxyClientMaxBodySize: "210mb",
+ // The sign-in proxy buffers request bodies (10 MB by default). Uploads skip it (src/proxy.ts matcher), so this is
+ // the largest other body: a Soul finish or a Layers render (64 MB) plus the form overhead. A body over it reaches
+ // the route cut short, with no error.
+ proxyClientMaxBodySize: "66mb",
},
async headers() {
return [
diff --git a/src/app/api/account/gpu/route.ts b/src/app/api/account/gpu/route.ts
index 083b1c83..7ad5a8e7 100644
--- a/src/app/api/account/gpu/route.ts
+++ b/src/app/api/account/gpu/route.ts
@@ -2,6 +2,9 @@ import { connection } from "next/server";
import { z } from "zod";
import { checkGpuAddress, GpuError, testGpu } from "@/server/account-gpu";
import { accountGpu, requestAccount, setAccountGpu } from "@/server/auth";
+import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES } from "@/server/account-files";
+import { clearAccountLoras } from "@/server/account-loras";
+import { hit } from "@/server/rate";
/**
* "Your GPU" (public sign-up): the account's own ComfyUI, where its runs go. GET says what is
@@ -25,6 +28,9 @@ const Body = z.object({ url: z.string().min(1).max(500), token: z.string().max(5
export async function PUT(request: Request) {
const a = await account(request);
if (!a) return notAccount();
+ // Each check makes the server call the address: a few a minute.
+ const rate = hit(`gpu:${a.id}`, ACCOUNT_LIMITS.gpuChecksPerMinute, 60_000);
+ if (!rate.ok) return Response.json({ error: ACCOUNT_MESSAGES.gpuChecks }, { status: 429, headers: { "Retry-After": String(rate.retryAfterS) } });
const parsed = Body.safeParse(await request.json().catch(() => null));
if (!parsed.success) return Response.json({ error: "Enter your ComfyUI's address" }, { status: 400 });
try {
@@ -33,7 +39,10 @@ export async function PUT(request: Request) {
const saved = accountGpu(a.id);
const token = parsed.data.token?.trim() || (saved?.url === url ? saved.token : undefined);
const info = await testGpu({ url, token });
- if (new URL(request.url).searchParams.get("test") !== "1") setAccountGpu(a.id, { url, token });
+ if (new URL(request.url).searchParams.get("test") !== "1") {
+ setAccountGpu(a.id, { url, token });
+ clearAccountLoras(a.id);
+ }
return Response.json({ gpu: { url, hasToken: !!token }, info });
} catch (e) {
if (e instanceof GpuError) return Response.json({ error: e.message }, { status: 422 });
@@ -45,5 +54,6 @@ export async function DELETE(request: Request) {
const a = await account(request);
if (!a) return notAccount();
setAccountGpu(a.id, null);
+ clearAccountLoras(a.id);
return Response.json({ gpu: null });
}
diff --git a/src/app/api/admin/accounts/[id]/route.ts b/src/app/api/admin/accounts/[id]/route.ts
index 6af172c2..136786b2 100644
--- a/src/app/api/admin/accounts/[id]/route.ts
+++ b/src/app/api/admin/accounts/[id]/route.ts
@@ -1,6 +1,7 @@
import { cookies } from "next/headers";
import { z } from "zod";
import { AccountError, deleteAccount, isOwnerRequest, listAccounts, SESSION_COOKIE, setAccountDisabled } from "@/server/auth";
+import { purgeAccount } from "@/server/account-sweep";
async function owner(request: Request): Promise<Response | null> {
return isOwnerRequest(request, (await cookies()).get(SESSION_COOKIE)?.value) ? null : Response.json({ error: "Only the studio's owner manages accounts" }, { status: 403 });
@@ -30,10 +31,13 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/admin/acco
export async function DELETE(request: Request, ctx: RouteContext<"/api/admin/accounts/[id]">) {
const denied = await owner(request);
if (denied) return denied;
+ const { id } = await ctx.params;
try {
- deleteAccount((await ctx.params).id);
+ deleteAccount(id);
} catch (e) {
return failed(e);
}
+ // Its runs and files go with it (running ones are stopped first).
+ await purgeAccount(id);
return new Response(null, { status: 204 });
}
diff --git a/src/app/api/auth/me/route.ts b/src/app/api/auth/me/route.ts
index 0ee9eefe..4d202c31 100644
--- a/src/app/api/auth/me/route.ts
+++ b/src/app/api/auth/me/route.ts
@@ -2,6 +2,7 @@ import { cookies } from "next/headers";
import { connection } from "next/server";
import { z } from "zod";
import { authEnabled, checkAccount, deleteAccount, publicSignup, SESSION_COOKIE, sessionViewer, validToken } from "@/server/auth";
+import { purgeAccount } from "@/server/account-sweep";
/** Who is looking: the owner, an account, or a guest; and whether sign-up is open. Open to everyone. */
export async function GET(request: Request) {
@@ -30,5 +31,7 @@ export async function DELETE(request: Request) {
if (!parsed.success || !checkAccount(session.account.email, parsed.data.password)) return Response.json({ error: "Wrong password" }, { status: 403 });
deleteAccount(session.account.id);
jar.delete(SESSION_COOKIE);
+ // Its runs and files go with it (running ones are stopped first).
+ await purgeAccount(session.account.id);
return new Response(null, { status: 204 });
}
diff --git a/src/app/api/files/[...path]/route.ts b/src/app/api/files/[...path]/route.ts
index f6a7e920..51f9696c 100644
--- a/src/app/api/files/[...path]/route.ts
+++ b/src/app/api/files/[...path]/route.ts
@@ -2,11 +2,6 @@ import { fileResponse } from "@/server/file-response";
export async function GET(request: Request, ctx: RouteContext<"/api/files/[...path]">) {
const { path: parts } = await ctx.params;
- let rel: string;
- try {
- rel = parts.map(decodeURIComponent).join("/");
- } catch {
- return new Response("Bad path", { status: 400 });
- }
- return fileResponse(request, rel);
+ // Next has decoded each segment once already: decoding again would turn %252e into "." (stored names never need it).
+ return fileResponse(request, parts.join("/"));
}
diff --git a/src/app/api/generations/[id]/finish/route.ts b/src/app/api/generations/[id]/finish/route.ts
index 6aecfc51..00f3b1b5 100644
--- a/src/app/api/generations/[id]/finish/route.ts
+++ b/src/app/api/generations/[id]/finish/route.ts
@@ -1,19 +1,25 @@
+import { requestAccount } from "@/server/auth";
import { FinishError, finishOutput } from "@/server/generations";
const MAX_BYTES = 64 * 1024 * 1024;
+/** An account's finished picture (its own result: the proxy checks): smaller. */
+const ACCOUNT_MAX_BYTES = 32 * 1024 * 1024;
const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
/**
* Fuobe Soul's finished picture (the look's grade and overlay, made in the browser): it replaces the raw output,
- * which stays as meta.original. Form fields: file (PNG), index (the output's place).
+ * which stays as meta.original. Form fields: file (PNG), index (the output's place). An account's file is stored as
+ * its own (through the generation).
*/
export async function POST(request: Request, ctx: RouteContext<"/api/generations/[id]/finish">) {
const { id } = await ctx.params;
+ const max = requestAccount(request) ? ACCOUNT_MAX_BYTES : MAX_BYTES;
+ if (Number(request.headers.get("content-length") ?? 0) > max + 64 * 1024) return Response.json({ error: `That picture is too large (${max / 2 ** 20} MB max)` }, { status: 413 });
const form = await request.formData().catch(() => null);
const file = form?.get("file");
const index = Number(form?.get("index"));
if (!(file instanceof File)) return Response.json({ error: "No file" }, { status: 400 });
- if (file.size > MAX_BYTES) return Response.json({ error: "That picture is too large (64 MB max)" }, { status: 413 });
+ if (file.size > max) return Response.json({ error: `That picture is too large (${max / 2 ** 20} MB max)` }, { status: 413 });
const data = Buffer.from(await file.arrayBuffer());
if (file.type !== "image/png" || !data.subarray(0, 8).equals(PNG_MAGIC)) return Response.json({ error: "Finished pictures are PNG images" }, { status: 415 });
try {
diff --git a/src/app/api/generations/[id]/route.ts b/src/app/api/generations/[id]/route.ts
index e27de293..c1d8d8b2 100644
--- a/src/app/api/generations/[id]/route.ts
+++ b/src/app/api/generations/[id]/route.ts
@@ -2,6 +2,7 @@ import { connection } from "next/server";
import { getGeneration, setFavorite } from "@/server/generations";
import { deleteForever, setPinned, setReview, trashGenerations } from "@/server/library";
import { isReviewStatus } from "@/lib/library";
+import { requestAccount } from "@/server/auth";
export async function GET(_req: Request, ctx: RouteContext<"/api/generations/[id]">) {
await connection();
@@ -22,10 +23,13 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/generation
return g ? Response.json(g) : Response.json({ error: "Not found" }, { status: 404 });
}
-/** Move to the Trash (restore with POST /api/generations/bulk {action: "restore"}); `?forever=1` deletes for good. */
+/**
+ * Move to the Trash (restore with POST /api/generations/bulk {action: "restore"}); `?forever=1` deletes for good. An
+ * account's run (the proxy checks it is its own) is always deleted for good: an account has no Trash, and its space comes back at once.
+ */
export async function DELETE(request: Request, ctx: RouteContext<"/api/generations/[id]">) {
const { id } = await ctx.params;
- if (new URL(request.url).searchParams.get("forever") === "1") await deleteForever([id]);
+ if (requestAccount(request) || new URL(request.url).searchParams.get("forever") === "1") await deleteForever([id]);
else trashGenerations([id]);
return new Response(null, { status: 204 });
}
diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.ts
index 062af4cc..f79ed846 100644
--- a/src/app/api/generations/route.ts
+++ b/src/app/api/generations/route.ts
@@ -1,9 +1,16 @@
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 { ensureTrashPurge, listOptionsFrom } from "@/server/library";
+import { hit, unhit } from "@/server/rate";
import { GenerationRequestSchema } from "@/server/request-schema";
import { gateGeneration, GPU_SETUP_HEADER } from "@/server/gpu/gate";
import { gpuTargetFor } from "@/server/gpu/target";
@@ -22,9 +29,33 @@ export async function GET(request: Request) {
return Response.json({ items: listGenerations({ ...listOptionsFrom(new URL(request.url).searchParams), account: account?.id }) });
}
+/** An account's runs going now (queued or running), counted as runs: a run's jobs and chain steps share a batch. */
+function activeRuns(accountId: string): number {
+ const r = db()
+ .prepare(
+ "SELECT COUNT(DISTINCT COALESCE(batch_id, id)) AS n FROM generations WHERE status IN ('queued', 'running') AND json_extract(request_json, '$.account') = ?",
+ )
+ .get(accountId) as { n: number };
+ return r.n;
+}
+
+const refuse = (status: number, error: string, extra: Record<string, unknown> = {}, headers: Record<string, string> = {}) =>
+ Response.json({ error, ...extra }, { status, headers: { "Cache-Control": "no-store", ...headers } });
+
/** Start a generation; `?preview=1` only says what it would run as (model, operation, jobs, outputs, cost). */
export async function POST(request: Request) {
- const body: unknown = await request.json().catch(() => null);
+ const viewer = requestViewer(request);
+ const account = viewer.kind === "account" ? viewer.account : null;
+ const preview = new URL(request.url).searchParams.get("preview") === "1";
+ // An account's run request is words and file paths (files are uploaded first): small.
+ const limitBody = !!account && !preview;
+ if (limitBody && Number(request.headers.get("content-length") ?? 0) > ACCOUNT_LIMITS.runBodyBytes) return refuse(413, ACCOUNT_MESSAGES.bodyTooBig);
+ const text = await request.text().catch(() => "");
+ if (limitBody && Buffer.byteLength(text) > ACCOUNT_LIMITS.runBodyBytes) return refuse(413, ACCOUNT_MESSAGES.bodyTooBig);
+ let body: unknown = null;
+ try {
+ body = JSON.parse(text);
+ } catch {}
const parsed = GenerationRequestSchema.safeParse(body);
if (!parsed.success) {
return Response.json({ error: parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ") }, { status: 400 });
@@ -33,17 +64,33 @@ export async function POST(request: Request) {
// so: previewGeneration and createGenerations move it (generations.ts currentRequest, replaced.ts).
const asked = parsed.data as Parameters<typeof createGenerations>[0];
// Public sign-up: an account runs on its own ComfyUI only (the open engine), never the install's providers.
- const viewer = requestViewer(request);
- const account = viewer.kind === "account" ? viewer.account : null;
- const req = account ? { ...asked, account: account.id, engine: "open" as const } : { ...asked, account: undefined };
+ let req = account ? { ...asked, account: account.id, engine: "open" as const } : { ...asked, account: undefined };
const own = account ? accountRun(account.id, "comfyui") : undefined;
- const preview = new URL(request.url).searchParams.get("preview") === "1";
if (own && "error" in own && !preview) {
return Response.json({ error: own.error, code: "connect-gpu" }, { status: 403, headers: { [CONNECT_GPU_HEADER]: "1" } });
}
const onOwn = <T,>(fn: () => T): T => (own && "run" in own ? own.run(fn) : fn());
- // A visitor's price check: priced as it would run, on its own GPU (none yet: the open engine, no demo).
- const priced = <T,>(fn: () => T): T => (viewer.kind === "owner" ? fn() : asVisitor(account ? accountGpu(account.id) : null, fn));
+ // A visitor's price check: priced as it would run, as that visitor, on its own GPU (none yet: the open engine, no demo).
+ const priced = <T,>(fn: () => T): T => (viewer.kind === "owner" ? fn() : asVisitor(account ? accountGpu(account.id) : null, fn, account?.id));
+ const notes: string[] = [];
+ if (account && !preview) {
+ // Room on the server, room in the account's files, and a fair share of runs.
+ if (!diskHasRoom()) return refuse(503, ACCOUNT_MESSAGES.diskLow);
+ if (accountUsage(account.id).total >= ACCOUNT_LIMITS.totalBytes) return refuse(413, ACCOUNT_MESSAGES.filesFull);
+ if (activeRuns(account.id) >= ACCOUNT_LIMITS.activeRuns) return refuse(429, ACCOUNT_MESSAGES.activeRuns, {}, { "Retry-After": "30" });
+ const rate = hit(`run:${account.id}`, ACCOUNT_LIMITS.runsPerHour, 60 * 60_000);
+ if (!rate.ok) return refuse(429, ACCOUNT_MESSAGES.runRate, {}, { "Retry-After": String(rate.retryAfterS) });
+ if ((req.params?.numOutputs ?? 1) > ACCOUNT_LIMITS.outputsPerRun) {
+ req = { ...req, params: { ...req.params, numOutputs: ACCOUNT_LIMITS.outputsPerRun } };
+ notes.push(ACCOUNT_MESSAGES.outputsCapped);
+ }
+ // Only files it uploaded here, or its own results (no links, no data: URIs, nobody else's).
+ const problem = accountInputProblem(req, account.id);
+ if (problem) {
+ unhit(`run:${account.id}`);
+ return refuse(problem.status, problem.error, { code: problem.code });
+ }
+ }
try {
if (preview) {
const { model, ...p } = priced(() => previewGeneration(req));
@@ -63,19 +110,36 @@ export async function POST(request: Request) {
// A 3D model from someone else's ComfyUI is finished on this server (decimate, web GLB, turntable): accounts
// don't get Image to 3D until that finish runs under an account's own limits.
if (account && outputKind(planned.op, planned.model) === "model3d") {
+ unhit(`run:${account.id}`);
return Response.json({ error: OWN_GPU_TOOL_MESSAGE, code: "own-gpu-tool" }, { status: 403 });
}
const skip = (body as { gpuCheck?: unknown } | null)?.gpuCheck === "skip";
const gate = await gateGeneration(gpuTargetFor(request, "read"), { request: req, route: planned.route, op: planned.op, modelId: planned.model.id, skip, actor: account?.id ?? "owner" });
- if (!gate.ok) return Response.json({ error: gate.message, code: "gpu-setup", ref: gate.ref, plan: gate.plan }, { status: 409, headers: { [GPU_SETUP_HEADER]: "1" } });
+ if (!gate.ok) {
+ if (account) unhit(`run:${account.id}`);
+ return Response.json({ error: gate.message, code: "gpu-setup", ref: gate.ref, plan: gate.plan }, { status: 409, headers: { [GPU_SETUP_HEADER]: "1" } });
+ }
gpuWarning = gate.warning;
}
}
+ 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);
+ });
+ if (fix) {
+ unhit(`run:${account.id}`);
+ return refuse(409, missingFilesMessage(fix), { code: "comfy_missing_model", fix });
+ }
+ }
const items = onOwn(() => createGenerations(req));
// What the run leaves out or changes (a model that replaced a retired one, a LoRA that runs only on a GPU, a length the API rounds).
- const notes = [...new Set(items.flatMap((g) => g.notes ?? []))];
- return Response.json({ items, ...(notes.length && { notes }), ...(gpuWarning && { gpuWarning }) }, { status: 201 });
+ const all = [...new Set([...notes, ...items.flatMap((g) => g.notes ?? [])])];
+ return Response.json({ items, ...(all.length && { notes: all }), ...(gpuWarning && { gpuWarning }) }, { status: 201 });
} catch (e) {
+ if (account) unhit(`run:${account.id}`);
return Response.json({ error: (e as Error).message }, { status: 422 });
}
}
diff --git a/src/app/api/media/probe/route.ts b/src/app/api/media/probe/route.ts
index 7899918b..965852d6 100644
--- a/src/app/api/media/probe/route.ts
+++ b/src/app/api/media/probe/route.ts
@@ -1,14 +1,19 @@
import { z } from "zod";
+import { requestAccount } from "@/server/auth";
import { probeSource } from "@/server/shorts";
import { body, handle } from "@/server/shorts-schemas";
+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.
*/
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");
- return Response.json(await probeSource(url));
+ const account = requestAccount(request);
+ const info = account ? await runAsTenant({ kind: "account", id: account.id }, () => probeSource(url)) : await probeSource(url);
+ return Response.json(info);
});
}
diff --git a/src/app/api/uploads/route.ts b/src/app/api/uploads/route.ts
index 851e7978..015d0f59 100644
--- a/src/app/api/uploads/route.ts
+++ b/src/app/api/uploads/route.ts
@@ -1,24 +1,215 @@
-import { contentTypeFor, saveFile } from "@/server/storage";
+import fs from "node:fs";
+import path from "node:path";
+import { nanoid } from "nanoid";
+import { CONNECT_GPU_HEADER, CONNECT_GPU_MESSAGE } from "@/lib/guest-access";
+import { imageSize } from "@/lib/image-size";
+import { sniffMedia, type SniffKind } from "@/lib/sniff";
+import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountUsage, diskHasRoom } from "@/server/account-files";
+import { accountGpu, type Account } from "@/server/auth";
+import { gateDirect } from "@/server/direct-gate";
+import { enter, hit } from "@/server/rate";
+import { adoptFile, contentTypeFor, saveFile, scratchDir } from "@/server/storage";
-const MAX_BYTES = 200 * 1024 * 1024;
+/**
+ * Upload a picture, clip or sound. The body is the file itself (Content-Type and X-File-Name: its name, URI-encoded),
+ * streamed to disk; a multipart form with a `file` field still works (the CLI, older pages). The proxy doesn't run
+ * on this route (src/proxy.ts config.matcher), so a large upload never waits in its memory: gateDirect makes the
+ * proxy's checks here.
+ *
+ * - The owner: up to 200 MB, the types below.
+ * - An account (public sign-up): only with its own ComfyUI connected; a picture up to 25 MB and 40 megapixels, a
+ * sound up to 50 MB, a clip up to 95 MB; its uploads up to 1 GB and all its files up to 3 GB; 60 uploads an hour,
+ * 300 a day, 2 at once. The stored type is read from the file's first bytes, never taken from the client.
+ */
+
+const OWNER_MAX_BYTES = 200 * 1024 * 1024;
const ALLOWED = /^(image\/(png|jpeg|webp|gif)|video\/(mp4|webm|quicktime|x-matroska|x-msvideo)|audio\/(mpeg|wav|x-wav|ogg|flac|mp4|webm))$/;
/** Names browsers give AVI and Matroska files, to the one Fuobe stores them under. */
const VIDEO_ALIASES: Record<string, string> = { "video/avi": "video/x-msvideo", "video/msvideo": "video/x-msvideo", "video/vnd.avi": "video/x-msvideo", "video/mkv": "video/x-matroska" };
+const KIND_CAP: Record<SniffKind, number> = { image: ACCOUNT_LIMITS.imageBytes, audio: ACCOUNT_LIMITS.audioBytes, video: ACCOUNT_LIMITS.videoBytes };
+const KIND_MESSAGE: Record<SniffKind, string> = { image: ACCOUNT_MESSAGES.imageTooBig, audio: ACCOUNT_MESSAGES.audioTooBig, video: ACCOUNT_MESSAGES.videoTooBig };
+
+const json = (status: number, body: Record<string, unknown>, headers: Record<string, string> = {}) =>
+ Response.json(body, { status, headers: { "Cache-Control": "no-store", ...headers } });
+
+class TooBig extends Error {}
+
+/** The file's name as display text only: no folders, no control or path characters, at most 120 characters. */
+function displayName(raw: string | null): string | undefined {
+ if (!raw) return undefined;
+ let name = raw;
+ try {
+ name = decodeURIComponent(raw);
+ } catch {}
+ name = (name.split(/[\\/]/).pop() ?? "")
+ .replace(/[\u0000-\u001f\u007f<>:"/\\|?*]/g, "_")
+ .trim()
+ .slice(0, 120);
+ return name || undefined;
+}
+
+/** The type a client says a file is (its Content-Type, else its name's extension), with the browser aliases. */
+function declaredType(contentType: string | null, name: string | undefined): string {
+ const t = (contentType ?? "").split(";")[0].trim().toLowerCase();
+ const given = !t || t === "application/octet-stream" ? contentTypeFor(name ?? "", "") : t;
+ return VIDEO_ALIASES[given] ?? given;
+}
+
+const kindOf = (type: string): SniffKind | null => (/^image\//.test(type) ? "image" : /^video\//.test(type) ? "video" : /^audio\//.test(type) ? "audio" : null);
+
+/** Stream a request body into `dest`, at most `max` bytes (TooBig past it; no file is left on any failure). */
+async function streamTo(body: ReadableStream<Uint8Array> | null, dest: string, max: number): Promise<number> {
+ const out = fs.createWriteStream(dest);
+ const reader = body?.getReader();
+ let bytes = 0;
+ try {
+ while (reader) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ bytes += value.length;
+ if (bytes > max) throw new TooBig();
+ if (!out.write(value)) await new Promise<void>((resolve, reject) => out.once("drain", resolve).once("error", reject));
+ }
+ await new Promise<void>((resolve, reject) => out.end((e?: Error | null) => (e ? reject(e) : resolve())));
+ return bytes;
+ } catch (e) {
+ reader?.cancel().catch(() => {});
+ out.destroy();
+ fs.rmSync(dest, { force: true });
+ throw e;
+ }
+}
+
+/** The first bytes of a file on disk (enough to tell its type and a picture's size). */
+function headOf(file: string, n = 1024 * 1024): Buffer {
+ const fd = fs.openSync(file, "r");
+ try {
+ const buf = Buffer.alloc(Math.min(n, fs.fstatSync(fd).size));
+ fs.readSync(fd, buf, 0, buf.length, 0);
+ return buf;
+ } finally {
+ fs.closeSync(fd);
+ }
+}
+
+const tempFile = () => path.join(scratchDir(), `up-${nanoid(12)}`);
+
export async function POST(request: Request) {
- const form = await request.formData().catch(() => null);
- const file = form?.get("file");
- if (!(file instanceof File)) return Response.json({ error: "No file" }, { status: 400 });
- if (file.size > MAX_BYTES) return Response.json({ error: "File too large (200 MB max)" }, { status: 413 });
- // Scripts often send no type (or octet-stream): go by the file extension then.
- const given = !file.type || file.type === "application/octet-stream" ? contentTypeFor(file.name, "") : file.type;
- const type = VIDEO_ALIASES[given] ?? given;
- if (!ALLOWED.test(type)) return Response.json({ error: `Unsupported file type ${type || file.type || "unknown"}` }, { status: 415 });
- const asset = saveFile({
- data: Buffer.from(await file.arrayBuffer()),
- contentType: type,
- name: file.name,
- source: "upload",
- });
- return Response.json(asset, { status: 201 });
+ const viewer = gateDirect(request);
+ if (viewer instanceof Response) return viewer;
+ if (viewer.kind === "account") return accountUpload(request, viewer.account);
+ return ownerUpload(request);
+}
+
+// ---------------------------------------------------------------------------
+// The owner
+
+async function ownerUpload(request: Request): Promise<Response> {
+ if ((request.headers.get("content-type") ?? "").toLowerCase().startsWith("multipart/form-data")) {
+ const form = await request.formData().catch(() => null);
+ const file = form?.get("file");
+ if (!(file instanceof File)) return Response.json({ error: "No file" }, { status: 400 });
+ if (file.size > OWNER_MAX_BYTES) return Response.json({ error: "File too large (200 MB max)" }, { status: 413 });
+ // Scripts often send no type (or octet-stream): go by the file extension then.
+ const type = declaredType(file.type, file.name);
+ if (!ALLOWED.test(type)) return Response.json({ error: `Unsupported file type ${type || file.type || "unknown"}` }, { status: 415 });
+ const asset = saveFile({ data: Buffer.from(await file.arrayBuffer()), contentType: type, name: displayName(file.name), source: "upload" });
+ return Response.json(asset, { status: 201 });
+ }
+ // The file as the body.
+ const name = displayName(request.headers.get("x-file-name"));
+ const type = declaredType(request.headers.get("content-type"), name);
+ if (!ALLOWED.test(type)) return Response.json({ error: `Unsupported file type ${type || "unknown"}` }, { status: 415 });
+ if (Number(request.headers.get("content-length") ?? 0) > OWNER_MAX_BYTES) return Response.json({ error: "File too large (200 MB max)" }, { status: 413 });
+ const dest = tempFile();
+ let bytes: number;
+ try {
+ bytes = await streamTo(request.body, dest, OWNER_MAX_BYTES);
+ } catch (e) {
+ if (e instanceof TooBig) return Response.json({ error: "File too large (200 MB max)" }, { status: 413 });
+ throw e;
+ }
+ if (!bytes) {
+ fs.rmSync(dest, { force: true });
+ return Response.json({ error: "No file" }, { status: 400 });
+ }
+ return Response.json(adoptFile({ from: dest, contentType: type, name, source: "upload" }), { status: 201 });
+}
+
+// ---------------------------------------------------------------------------
+// An account
+
+async function accountUpload(request: Request, account: Account): Promise<Response> {
+ if (!accountGpu(account.id)) return json(403, { error: CONNECT_GPU_MESSAGE, code: "connect-gpu" }, { [CONNECT_GPU_HEADER]: "1" });
+ if (!diskHasRoom()) return json(503, { error: ACCOUNT_MESSAGES.diskLow });
+ // A fair share: 60 an hour, 300 a day, 2 at once.
+ const hour = hit(`up:h:${account.id}`, ACCOUNT_LIMITS.uploadsPerHour, 60 * 60_000);
+ const day = hour.ok ? hit(`up:d:${account.id}`, ACCOUNT_LIMITS.uploadsPerDay, 24 * 60 * 60_000) : hour;
+ if (!hour.ok || !day.ok) return json(429, { error: ACCOUNT_MESSAGES.uploadRate }, { "Retry-After": String(Math.max(hour.retryAfterS, day.retryAfterS)) });
+ const release = enter(`up:${account.id}`, ACCOUNT_LIMITS.uploadsAtOnce);
+ if (!release) return json(429, { error: ACCOUNT_MESSAGES.uploadRate }, { "Retry-After": "10" });
+ try {
+ return await accountUploadBody(request, account);
+ } finally {
+ release();
+ }
+}
+
+async function accountUploadBody(request: Request, account: Account): Promise<Response> {
+ const lengthHeader = request.headers.get("content-length");
+ const length = lengthHeader === null ? NaN : Number(lengthHeader);
+ if (!Number.isFinite(length) || length < 0) return json(411, { error: ACCOUNT_MESSAGES.lengthNeeded });
+ const multipart = (request.headers.get("content-type") ?? "").toLowerCase().startsWith("multipart/form-data");
+ // A page from before the file was sent as it is: only a small form is read (it is held in memory).
+ if (multipart && length > ACCOUNT_LIMITS.multipartBytes) return json(413, { error: ACCOUNT_MESSAGES.reloadToUpload });
+ let name = multipart ? undefined : displayName(request.headers.get("x-file-name"));
+ const declared = multipart ? null : kindOf(declaredType(request.headers.get("content-type"), name));
+ // Refused before a byte is read: over the declared kind's cap, or over the largest cap.
+ if (declared && length > KIND_CAP[declared]) return json(413, { error: KIND_MESSAGE[declared] });
+ if (length > ACCOUNT_LIMITS.videoBytes) return json(413, { error: ACCOUNT_MESSAGES.videoTooBig });
+ const usage = accountUsage(account.id);
+ if (usage.uploads + length > ACCOUNT_LIMITS.uploadsBytes) return json(413, { error: ACCOUNT_MESSAGES.uploadsFull });
+ if (usage.total + length > ACCOUNT_LIMITS.totalBytes) return json(413, { error: ACCOUNT_MESSAGES.filesFull });
+
+ const dest = tempFile();
+ let bytes: number;
+ let declaredFull = "";
+ try {
+ if (multipart) {
+ const form = await request.formData().catch(() => null);
+ const file = form?.get("file");
+ if (!(file instanceof File)) return json(400, { error: "No file" });
+ if (file.size > ACCOUNT_LIMITS.multipartBytes) return json(413, { error: ACCOUNT_MESSAGES.reloadToUpload });
+ name = displayName(file.name);
+ declaredFull = file.type;
+ fs.writeFileSync(dest, Buffer.from(await file.arrayBuffer()));
+ bytes = file.size;
+ } else {
+ declaredFull = request.headers.get("content-type") ?? "";
+ // Never more than it said it would send.
+ bytes = await streamTo(request.body, dest, Math.min(length, ACCOUNT_LIMITS.videoBytes));
+ }
+ } catch (e) {
+ fs.rmSync(dest, { force: true });
+ if (e instanceof TooBig) return json(413, { error: ACCOUNT_MESSAGES.videoTooBig });
+ throw e;
+ }
+ const drop = (status: number, error: string) => {
+ fs.rmSync(dest, { force: true });
+ return json(status, { error });
+ };
+ if (!bytes) return drop(400, "No file");
+ // The stored type is the one its bytes say: a page or a script never passes for a picture.
+ const head = headOf(dest);
+ const sniffed = sniffMedia(head, declaredType(declaredFull, name));
+ if (!sniffed) return drop(415, ACCOUNT_MESSAGES.wrongType);
+ if (bytes > KIND_CAP[sniffed.kind]) return drop(413, KIND_MESSAGE[sniffed.kind]);
+ if (sniffed.kind === "image") {
+ const size = imageSize(head);
+ if (!size) return drop(415, ACCOUNT_MESSAGES.wrongType);
+ if (size.width * size.height > ACCOUNT_LIMITS.imagePixels) return drop(413, ACCOUNT_MESSAGES.imageTooManyPixels);
+ }
+ const asset = adoptFile({ from: dest, contentType: sniffed.contentType, name, source: "upload", accountId: account.id });
+ return json(201, { ...asset });
}
diff --git a/src/components/studio/media-slot.tsx b/src/components/studio/media-slot.tsx
index 379f4b0f..e504cf94 100644
--- a/src/components/studio/media-slot.tsx
+++ b/src/components/studio/media-slot.tsx
@@ -7,6 +7,7 @@ import { toast } from "sonner";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { useAssets, type Asset } from "@/lib/api";
+import { postFile } from "@/lib/upload";
import type { MediaKind } from "@/lib/catalog/types";
import { slotCaption } from "@/lib/composer";
import { cn } from "@/lib/utils";
@@ -55,14 +56,8 @@ export const kindOfFile = (f: File): MediaKind => {
export const wrongKindMessage = (kind: MediaKind) =>
({ image: "Image only — drop a photo here", video: "Video only — drop a clip here", audio: "Audio only — drop a sound file here", text: "Text only — drop a .txt or .srt file here", model3d: "3D only — drop a .glb file here" })[kind];
-async function upload(file: File, signal?: AbortSignal): Promise<Asset> {
- const form = new FormData();
- form.append("file", file);
- const res = await fetch("/api/uploads", { method: "POST", body: form, signal });
- const body = (await res.json().catch(() => ({}))) as Asset & { error?: string };
- if (!res.ok) throw new Error(body.error ?? `Upload failed (${res.status})`);
- return body;
-}
+/** The file as it is: the server streams it (src/lib/upload.ts), and its error is the toast. */
+const upload = (file: File, signal?: AbortSignal): Promise<Asset> => postFile(file, signal);
/**
* Upload a File and stream state changes back: a local preview first (`uploading: true`), then
diff --git a/src/instrumentation.ts b/src/instrumentation.ts
index 1471ecf0..ff6ff650 100644
--- a/src/instrumentation.ts
+++ b/src/instrumentation.ts
@@ -10,6 +10,9 @@ export async function register() {
ensureRunner();
const { ensureTrashPurge } = await import("./server/library");
ensureTrashPurge();
+ // Public sign-up: accounts' uploads leave after 14 days and their runs after 30 (then daily); a deleted account's files go.
+ const { ensureAccountSweep } = await import("./server/account-sweep");
+ ensureAccountSweep();
// Faceless / Explainer renders whose narration was timed while the server was down continue with their scenes.
const { ensureFacelessRunner } = await import("./server/faceless");
ensureFacelessRunner();
diff --git a/src/lib/api.ts b/src/lib/api.ts
index c3ba2f56..9f71691e 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -26,6 +26,7 @@ import {
type StreamEvent,
} from "./generation-stream";
import { cursorAfter, filterToSearch, type AssetUse, type FeedFilter, type Folder } from "./library";
+import { postFile } from "./upload";
import type { ShareCreated, ShareInfo, ShareListItem, SharePatch, ShareRequest } from "./share";
import type { AccessSummary } from "./model-access";
@@ -722,10 +723,9 @@ export function useShareActions() {
// ---------------------------------------------------------------------------
// Uploads & assets
+/** Upload a file as it is (streamed by the server: src/lib/upload.ts). */
export async function uploadFile(file: File): Promise<Asset> {
- const form = new FormData();
- form.append("file", file);
- return json<Asset>(await fetch("/api/uploads", { method: "POST", body: form }));
+ return postFile(file);
}
/** A stored file's uses: where it's used, in one line ("2 results and the element “Maya”"), empty when nothing uses it. */
diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.ts
index 21b360a4..31cbeb87 100644
--- a/src/lib/guest-access.ts
+++ b/src/lib/guest-access.ts
@@ -107,8 +107,6 @@ export function isPriceCheck(method: string, pathname: string, search: string):
* the MCP endpoint…) is refused with "Connect your GPU": it never spends the owner's keys or GPU.
*/
const LIBRARY_CHANGES: [methods: string, path: RegExp][] = [
- ["POST", /^\/api\/uploads$/],
- ["POST", /^\/api\/media\/probe$/],
["POST", /^\/api\/folders$/],
["PATCH DELETE", /^\/api\/folders\/[^/]+$/],
["PATCH DELETE", /^\/api\/generations\/[^/]+$/],
@@ -140,8 +138,9 @@ const GENERATION = /^\/api\/generations\/(?!(?:facets|trash|stream|zip|bulk|loca
/** The generation an account's request is about (its own runs: the proxy checks it made it), or undefined. */
export function accountGeneration(method: string, pathname: string): string | undefined {
- const cancel = /^\/api\/generations\/([^/]+)\/cancel$/.exec(pathname);
- if (method === "POST" && cancel) return cancel[1];
+ // Cancel, and Fuobe Soul's finished picture for its own result.
+ const step = /^\/api\/generations\/([^/]+)\/(cancel|finish)$/.exec(pathname);
+ if (method === "POST" && step) return step[1];
const one = GENERATION.exec(pathname);
return one && (method === "GET" || method === "HEAD" || method === "DELETE") ? one[1] : undefined;
}
@@ -157,12 +156,17 @@ export function accountOwnRead(pathname: string): boolean {
/** GPU pre-flight reads: each answers for the account's own GPU only (src/server/gpu/target.ts). */
const GPU_READS = new Set(["/api/gpu/readiness", "/api/gpu/badges", "/api/gpu/plan"]);
-/** A change an account may send: signing out, its own GPU and its check, and price checks (reads go by guestRead, as a guest's). */
+/**
+ * A change an account may send: signing out, its own GPU and its check, price checks (reads go by guestRead, as a
+ * guest's), an upload (the route checks it: src/app/api/uploads, which the proxy's matcher leaves out) and a look at its
+ * own clip's header (the route reads only its own files).
+ */
export function accountMayChange(method: string, pathname: string, search: string): boolean {
if (method === "POST" && pathname === "/api/auth/logout") return true;
if ((method === "PUT" || method === "DELETE") && pathname === "/api/account/gpu") return true;
// GPU pre-flight: checking its own ComfyUI (reads only; the routes check the target and the request themselves).
if ((method === "POST" && pathname === "/api/gpu/check") || (method === "PUT" && pathname === "/api/gpu/inventory")) return true;
+ if (method === "POST" && (pathname === "/api/uploads" || pathname === "/api/media/probe")) return true;
return isPriceCheck(method, pathname, search);
}
@@ -175,15 +179,16 @@ export const ACCOUNT_LIBRARY_MESSAGE = "This studio's library is its owner's. Fr
export const LIBRARY_MESSAGE = "Free accounts can't save to this studio's library yet.";
/**
- * Runs an account may start once it has connected its own ComfyUI ("Your GPU"): the studios' generations, which
- * the route sends to that ComfyUI only (src/app/api/generations/route.ts, generations.ts accountRun). Other tools
- * plan with the install's AI helpers or its own ComfyUI, so they stay refused.
+ * Runs an account may start once it has connected its own ComfyUI ("Your GPU"): the studios' generations, camera
+ * motions, effects and apps, which the route sends to that ComfyUI only, with only its own uploaded files
+ * (src/app/api/generations/route.ts, generations.ts accountRun). Other tools plan with the install's AI helpers or
+ * its own ComfyUI, so they stay refused.
*/
export function ownGpuRun(method: string, pathname: string): boolean {
return method === "POST" && pathname === "/api/generations";
}
-export const OWN_GPU_TOOL_MESSAGE = "This tool doesn't run on your own GPU yet. The Image, Video and Audio studios do: pick an open-source model there.";
+export const OWN_GPU_TOOL_MESSAGE = "This tool doesn't run on your own GPU yet. Camera motions, effects, apps and the Image, Video and Audio studios do.";
/** Set on an account's refused run: the client shows "Connect your GPU to run this". */
export const CONNECT_GPU_HEADER = "x-fuobe-connect-gpu";
diff --git a/src/lib/missing-files.ts b/src/lib/missing-files.ts
new file mode 100644
index 00000000..f1a9b1b4
--- /dev/null
+++ b/src/lib/missing-files.ts
@@ -0,0 +1,88 @@
+import { libraryEntry } from "@/lib/catalog/loras";
+import type { LoraRef } from "@/lib/catalog/types";
+
+/**
+ * Files a run needs that the account's own ComfyUI doesn't have ("Your GPU"): what to download, and where to put it.
+ * Fuobe never downloads anything onto an account's machine; it says what is missing and where each file comes from.
+ * The shape is the pre-flight's fix (code "comfy_missing_model") with a download link on each item.
+ */
+export type MissingDownload = "direct" | "civitai-token" | "hf-gated";
+
+export interface MissingFile {
+ /** The ComfyUI models folder it goes in ("loras", "checkpoints"…). */
+ folder: string;
+ /** The file name, as the run loads it. */
+ file: string;
+ /** Where it downloads from. */
+ url?: string;
+ /** Its model card. */
+ page?: string;
+ download?: MissingDownload;
+ sizeBytes?: number;
+}
+
+export interface MissingFiles {
+ code: "comfy_missing_model";
+ workflowId?: string;
+ items: MissingFile[];
+}
+
+const slash = (f: string) => f.replace(/\\/g, "/");
+
+/**
+ * The LoRAs in `needs` that `listed` (the ComfyUI's GET /models/loras) doesn't have, by exact name ("\" read as "/").
+ * Links come from Fuobe's LoRA library; a LoRA the run itself named may show the https link it gave. A private LoRA
+ * (`own`) is never named.
+ */
+export function missingLoras(needs: LoraRef[], listed: string[]): MissingFile[] {
+ const have = new Set(listed.map(slash));
+ const out: MissingFile[] = [];
+ const seen = new Set<string>();
+ for (const l of needs) {
+ if (!l.file || l.own || have.has(slash(l.file)) || seen.has(slash(l.file))) continue;
+ seen.add(slash(l.file));
+ const entry = libraryEntry(l);
+ if (entry) {
+ out.push({ folder: "loras", file: l.file, url: entry.url, page: entry.page, download: entry.download, ...(entry.sizeBytes && { sizeBytes: entry.sizeBytes }) });
+ continue;
+ }
+ // A preset's own LoRA (the catalog names its link), or one the run itself named: its https link, and a Hugging
+ // Face repo's page.
+ const given = l.url && /^https:\/\//.test(l.url) ? l.url : undefined;
+ const repo = given ? /^(https:\/\/huggingface\.co\/[^/]+\/[^/]+)\/resolve\//.exec(given)?.[1] : undefined;
+ out.push({
+ folder: "loras",
+ file: l.file,
+ ...(given && { url: given, download: /^https:\/\/civitai\.com\//.test(given) ? ("civitai-token" as const) : ("direct" as const) }),
+ ...(repo && { page: repo }),
+ });
+ }
+ return out;
+}
+
+const size = (n: number) => (n >= 2 ** 30 ? `${(n / 2 ** 30).toFixed(1)} GB` : `${Math.max(1, Math.round(n / 2 ** 20))} MB`);
+
+/** One item as a line: the file, where it downloads from, and what to know first. */
+function itemLine(i: MissingFile): string {
+ // civitai's download link answers 401 without signing in: its model page is where a person gets the file.
+ const link = i.download === "civitai-token" ? (i.page ?? i.url) : (i.url ?? i.page);
+ if (!link) return `• ${i.file} (we don't have a download link for it)`;
+ const note =
+ i.download === "civitai-token" ? "sign in to civitai to download" : i.download === "hf-gated" ? "accept the licence on Hugging Face first" : i.sizeBytes ? size(i.sizeBytes) : "";
+ return `• ${i.file}: ${link}${note ? ` (${note})` : ""}`;
+}
+
+/** What the run says: how many files, where they go, and each one's link (at most 5, then "and N more"). */
+export function missingFilesMessage(m: MissingFiles): string {
+ const n = m.items.length;
+ const folders = [...new Set(m.items.map((i) => i.folder))];
+ const kind = folders.length === 1 && folders[0] === "loras" ? "LoRA file" : "model file";
+ const where = folders.length === 1 ? `ComfyUI/models/${folders[0]}` : "the ComfyUI/models folder named for it";
+ const head =
+ n === 1
+ ? `Your ComfyUI doesn't have a ${kind} this needs. Download it into ${where}, keep the file name, then press Generate again.`
+ : `Your ComfyUI doesn't have ${n} ${kind}s this needs. Download each one into ${where}, keep the file name, then press Generate again.`;
+ const lines = m.items.slice(0, 5).map(itemLine);
+ if (n > 5) lines.push(`and ${n - 5} more`);
+ return [head, ...lines].join("\n");
+}
diff --git a/src/lib/sniff.ts b/src/lib/sniff.ts
new file mode 100644
index 00000000..4676d8b0
--- /dev/null
+++ b/src/lib/sniff.ts
@@ -0,0 +1,67 @@
+/**
+ * What a file is, from its first bytes (at least 64): the stored type of an upload is this one, never the type the
+ * client declared, so a page or a script can't be stored as a picture. Pictures (PNG, JPEG, WebP; GIF only when
+ * `gif` is allowed), clips (MP4, MOV, WebM, Matroska, AVI) and sound (MP3, WAV, OGG, FLAC, M4A, WebM). Never SVG or
+ * HTML. Null when it is none of these.
+ */
+export type SniffKind = "image" | "video" | "audio";
+
+export interface Sniffed {
+ contentType: string;
+ kind: SniffKind;
+}
+
+const ascii = (b: Uint8Array, at: number, n: number) => String.fromCharCode(...b.subarray(at, at + n));
+
+/** The EBML DocType of a WebM / Matroska file ("webm" or "matroska"), read from its header. */
+function ebmlDocType(b: Uint8Array): string | null {
+ // The DocType element: id 0x4282, a one-byte size (0x80 | n), then n bytes.
+ for (let i = 4; i < Math.min(b.length - 3, 64); i++) {
+ if (b[i] === 0x42 && b[i + 1] === 0x82) {
+ const n = b[i + 2] & 0x7f;
+ if (b[i + 2] & 0x80 && n > 0 && i + 3 + n <= b.length) return ascii(b, i + 3, n).toLowerCase();
+ }
+ }
+ return null;
+}
+
+export function sniffMedia(head: Uint8Array, declared?: string, opts: { gif?: boolean } = {}): Sniffed | null {
+ const b = head;
+ if (b.length < 4) return null;
+ const said = (declared ?? "").split(";")[0].trim().toLowerCase();
+ // Pictures.
+ if (b.length >= 8 && b[0] === 0x89 && ascii(b, 1, 3) === "PNG" && b[4] === 0x0d && b[5] === 0x0a && b[6] === 0x1a && b[7] === 0x0a) return { contentType: "image/png", kind: "image" };
+ if (b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return { contentType: "image/jpeg", kind: "image" };
+ if (b.length >= 12 && ascii(b, 0, 4) === "RIFF" && ascii(b, 8, 4) === "WEBP") return { contentType: "image/webp", kind: "image" };
+ if (opts.gif && b.length >= 6 && (ascii(b, 0, 6) === "GIF87a" || ascii(b, 0, 6) === "GIF89a")) return { contentType: "image/gif", kind: "image" };
+ // ISO base media (MP4, MOV, M4A): "ftyp" at offset 4, then the brand.
+ if (b.length >= 12 && ascii(b, 4, 4) === "ftyp") {
+ const brand = ascii(b, 8, 4);
+ if (brand === "qt ") return { contentType: "video/quicktime", kind: "video" };
+ // An M4A says so in its brand; other sound in an MP4 box goes by the type declared.
+ if (brand === "M4A " || brand === "M4B " || said.startsWith("audio/")) return { contentType: "audio/mp4", kind: "audio" };
+ return { contentType: "video/mp4", kind: "video" };
+ }
+ // A QuickTime file that starts with another atom ("moov", "mdat", "wide", "free").
+ if (b.length >= 8 && ["moov", "mdat", "wide", "free", "skip"].includes(ascii(b, 4, 4)) && said === "video/quicktime") return { contentType: "video/quicktime", kind: "video" };
+ // WebM and Matroska.
+ if (b[0] === 0x1a && b[1] === 0x45 && b[2] === 0xdf && b[3] === 0xa3) {
+ const doc = ebmlDocType(b);
+ if (doc === "webm") return said.startsWith("audio/") ? { contentType: "audio/webm", kind: "audio" } : { contentType: "video/webm", kind: "video" };
+ if (doc === "matroska") return { contentType: "video/x-matroska", kind: "video" };
+ return null;
+ }
+ // RIFF: AVI and WAV.
+ if (b.length >= 12 && ascii(b, 0, 4) === "RIFF") {
+ const form = ascii(b, 8, 4);
+ if (form === "AVI ") return { contentType: "video/x-msvideo", kind: "video" };
+ if (form === "WAVE") return { contentType: "audio/wav", kind: "audio" };
+ return null;
+ }
+ if (ascii(b, 0, 4) === "OggS") return { contentType: "audio/ogg", kind: "audio" };
+ if (ascii(b, 0, 4) === "fLaC") return { contentType: "audio/flac", kind: "audio" };
+ // MP3: an ID3 tag, or an MPEG audio frame sync (11 bits set; layer bits not 00).
+ if (ascii(b, 0, 3) === "ID3") return { contentType: "audio/mpeg", kind: "audio" };
+ if (b[0] === 0xff && (b[1] & 0xe0) === 0xe0 && (b[1] & 0x06) !== 0) return { contentType: "audio/mpeg", kind: "audio" };
+ return null;
+}
diff --git a/src/lib/upload.ts b/src/lib/upload.ts
new file mode 100644
index 00000000..4434e93a
--- /dev/null
+++ b/src/lib/upload.ts
@@ -0,0 +1,17 @@
+import type { Asset } from "@/lib/api";
+
+/**
+ * Upload a file as it is (the body is the file; its type and its name in headers), so the server streams it to disk
+ * instead of reading a whole form into memory. Throws with the server's own message ("That clip is over 95 MB…").
+ */
+export async function postFile(file: File, signal?: AbortSignal): Promise<Asset> {
+ const res = await fetch("/api/uploads", {
+ method: "POST",
+ body: file,
+ signal,
+ headers: { "Content-Type": file.type || "application/octet-stream", "X-File-Name": encodeURIComponent(file.name) },
+ });
+ const body = (await res.json().catch(() => ({}))) as Asset & { error?: string };
+ if (!res.ok) throw new Error(body.error ?? `Upload failed (${res.status})`);
+ return body;
+}
diff --git a/src/proxy.ts b/src/proxy.ts
index e6e473ee..d6c07d33 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -207,6 +207,7 @@ export function proxy(request: NextRequest) {
export const config = {
// Everything except build assets and the public folder's own files: the favicon and app icons,
// the demo samples, the preset covers, vendored scripts (the 3D viewer's meshopt decoder) and the
- // SVGs at the root. Generated SVGs under /api/files stay behind sign-in.
- matcher: ["/((?!_next/static|_next/image|favicon\\.ico$|apple-icon\\.png$|samples/|previews/|vendor/|[^/]+\\.svg$).*)"],
+ // 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$).*)"],
};
diff --git a/src/server/account-files.ts b/src/server/account-files.ts
new file mode 100644
index 00000000..ce945953
--- /dev/null
+++ b/src/server/account-files.ts
@@ -0,0 +1,124 @@
+import "server-only";
+import fs from "node:fs";
+import { DATA_DIR, db } from "./db";
+
+/**
+ * Public sign-up ("Your GPU"): what an account may keep on this server, and how much. An account's uploads and the
+ * files of its runs carry its id (assets.account_id); these numbers cap them, and account-sweep.ts removes them in time.
+ * The numbers are defaults the owner can change here.
+ */
+
+const MB = 2 ** 20;
+const GB = 2 ** 30;
+const DAY = 24 * 60 * 60_000;
+
+export const ACCOUNT_LIMITS = {
+ /** Picture uploads: PNG, JPEG or WebP, up to this size and 40 megapixels. */
+ imageBytes: 25 * MB,
+ imagePixels: 40_000_000,
+ /** Sound uploads: MP3, WAV, OGG, FLAC, M4A or WebM. */
+ audioBytes: 50 * MB,
+ /** Clips: MP4, MOV, WebM, MKV or AVI (under ComfyUI's 100 MB default and a free tunnel's 100 MB request limit). */
+ videoBytes: 95 * MB,
+ /** A multipart upload (an old tab) is read in memory: only this small. */
+ multipartBytes: 26 * MB,
+ /** Live uploads per account, and all its files (uploads and results). */
+ uploadsBytes: 1 * GB,
+ totalBytes: 3 * GB,
+ /** Uploads: per hour, per day, and at once. */
+ uploadsPerHour: 60,
+ uploadsPerDay: 300,
+ uploadsAtOnce: 2,
+ /** 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. */
+ diskFreeBytes: 20 * GB,
+ /** Runs: at once (queued or running), per hour, and outputs per run. */
+ activeRuns: 4,
+ runsPerHour: 60,
+ 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. */
+ outputsPerJob: 16,
+ /** How long a job may wait in the account's ComfyUI's queue. */
+ queueMs: 30 * 60_000,
+ /** GPU address checks and saves, per minute. */
+ gpuChecksPerMinute: 10,
+} as const;
+
+export const RETENTION_MS = { upload: ACCOUNT_LIMITS.uploadDays * DAY, run: ACCOUNT_LIMITS.runDays * DAY };
+
+export const ACCOUNT_MESSAGES = {
+ imageTooBig: "That picture is over 25 MB. Save it smaller, then try again.",
+ 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.",
+ 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.",
+ uploadRate: "That's a lot of uploads at once. Try again in a few minutes.",
+ diskLow: "The studio is short of space right now. Try again later.",
+ activeRuns: "You have 4 runs going. Start the next one when one finishes.",
+ runRate: "That's a lot of runs this hour. Try again later.",
+ 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.",
+ reloadToUpload: "Reload the page, then upload again.",
+ lengthNeeded: "Send the file with its size (Content-Length).",
+} as const;
+
+/** What an account stores: all its files, its uploads, and how many uploads. */
+export function accountUsage(id: string): { total: number; uploads: number; uploadCount: number } {
+ const r = db()
+ .prepare(
+ `SELECT COALESCE(SUM(size), 0) AS total, COALESCE(SUM(CASE WHEN source = 'upload' THEN size ELSE 0 END), 0) AS uploads,
+ COALESCE(SUM(CASE WHEN source = 'upload' THEN 1 ELSE 0 END), 0) AS uploadCount FROM assets WHERE account_id = ?`,
+ )
+ .get(id) as { total: number; uploads: number; uploadCount: number };
+ return { total: Number(r.total), uploads: Number(r.uploads), uploadCount: Number(r.uploadCount) };
+}
+
+declare global {
+ /** Tests only: the free disk space to report. */
+ var __fuobeTestDiskFree: 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;
+ try {
+ fs.mkdirSync(DATA_DIR, { recursive: true });
+ const s = fs.statfsSync(DATA_DIR);
+ return Number(s.bavail) * Number(s.bsize);
+ } catch {
+ return Infinity;
+ }
+}
+
+/** Whether the server has room for an account's upload or run. */
+export const diskHasRoom = () => diskFreeBytes() >= ACCOUNT_LIMITS.diskFreeBytes;
+
+// ---------------------------------------------------------------------------
+// When an account is deleted
+
+declare global {
+ var __fuobeAccountDeleted: ((id: string) => void | Promise<void>)[] | undefined;
+}
+
+/** Work to do when an account is deleted, after its runs and files are gone (other features register theirs here). */
+export function onAccountDeleted(hook: (id: string) => void | Promise<void>): void {
+ const hooks = (globalThis.__fuobeAccountDeleted ??= []);
+ if (!hooks.includes(hook)) hooks.push(hook);
+}
+
+export async function runAccountDeletedHooks(id: string): Promise<void> {
+ for (const hook of globalThis.__fuobeAccountDeleted ?? []) {
+ try {
+ await hook(id);
+ } catch (e) {
+ console.warn(`[fuobe] cleanup for a deleted account failed: ${(e as Error).message}`);
+ }
+ }
+}
diff --git a/src/server/account-gpu.ts b/src/server/account-gpu.ts
index 8f0432ad..a1cd8062 100644
--- a/src/server/account-gpu.ts
+++ b/src/server/account-gpu.ts
@@ -3,7 +3,7 @@ import dns from "node:dns/promises";
import net from "node:net";
import { accountGpu, type Account, type AccountGpu } from "./auth";
import { PROVIDERS } from "./providers";
-import { fetchPublic, isPrivateAddress } from "./remote-fetch";
+import { blockedForAccounts, fetchPublic, isLoopbackGpu } from "./remote-fetch";
import { isInstallHost, REFUSED_ADDRESS } from "./gpu/hosts";
/**
@@ -36,8 +36,9 @@ export async function checkGpuAddress(raw: string, o: { resolve?: (host: string)
if (u.search || u.hash) throw new GpuError("Use the address without ? or #");
const host = u.hostname.replace(/^\[|\]$/g, "").toLowerCase();
const local = host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".lan") || host.endsWith(".internal") || !host.includes(".");
- if (!allowPrivate()) {
- if (local && !net.isIP(host)) throw new GpuError(LOCAL_GPU_MESSAGE);
+ // A stand-in ComfyUI on this machine is allowed in tests and `next dev` only (remote-fetch.ts loopbackGpuPort).
+ if (!isLoopbackGpu(u)) {
+ if (local && !net.isIP(host) && !allowPrivate()) throw new GpuError(LOCAL_GPU_MESSAGE);
const resolve = o.resolve ?? (async (h: string) => (await dns.lookup(h, { all: true, verbatim: true })).map((a) => a.address));
let addrs: string[];
try {
@@ -46,12 +47,14 @@ export async function checkGpuAddress(raw: string, o: { resolve?: (host: string)
throw new GpuError(`Couldn't find ${host}. Check the address (is the tunnel running?)`);
}
if (!addrs.length) throw new GpuError(`Couldn't find ${host}. Check the address (is the tunnel running?)`);
- if (addrs.some(isPrivateAddress)) throw new GpuError(LOCAL_GPU_MESSAGE);
+ // Private networks, this machine's own addresses (loopback too, even with FUOBE_ALLOW_PRIVATE_URLS), wrapped IPv4.
+ if (addrs.some(blockedForAccounts)) throw new GpuError(LOCAL_GPU_MESSAGE);
}
const url = normal(u);
// The install's own ComfyUI on any scheme, port or path (ComfyUI answers every route under /api too), compared by
// host. One message for every such refusal, so it never confirms a guessed address.
- if (isInstallHost(url)) throw new GpuError(REFUSED_ADDRESS);
+ // (The tests' and `next dev`'s stand-in on this machine is on a port of its own: loopbackGpuPort.)
+ if (!isLoopbackGpu(u) && isInstallHost(url)) throw new GpuError(REFUSED_ADDRESS);
return url;
}
@@ -65,7 +68,7 @@ export interface GpuInfo {
export async function testGpu(gpu: AccountGpu, o: { resolve?: (host: string) => Promise<string[]>; timeoutMs?: number } = {}): Promise<GpuInfo> {
let res: Response;
try {
- res = await fetchPublic(`${gpu.url}/system_stats`, { headers: gpu.token ? { Authorization: `Bearer ${gpu.token}` } : {} }, { timeoutMs: o.timeoutMs ?? 10_000, resolve: o.resolve });
+ res = await fetchPublic(`${gpu.url}/system_stats`, { headers: gpu.token ? { Authorization: `Bearer ${gpu.token}` } : {} }, { timeoutMs: o.timeoutMs ?? 10_000, deadlineMs: (o.timeoutMs ?? 10_000) + 5_000, maxBytes: 1 * 2 ** 20, resolve: o.resolve });
} catch (e) {
throw new GpuError(`Couldn't reach your ComfyUI at ${gpu.url}: ${(e as Error).message}`);
}
diff --git a/src/server/account-inputs.ts b/src/server/account-inputs.ts
new file mode 100644
index 00000000..eb53038c
--- /dev/null
+++ b/src/server/account-inputs.ts
@@ -0,0 +1,66 @@
+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";
+
+/**
+ * The files an account's run names (public sign-up, "Your GPU"): only files it uploaded here, or its own results. No
+ * links (the server never fetches one for an account), no data: URIs (stored inline in the run), no asset ids, and
+ * never someone else's file. Checked by the run route before anything is queued; storage.ts guardRef checks again when
+ * 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 const INPUT_NOT_ALLOWED = "Upload the file here first. Runs on your GPU use files you uploaded.";
+
+const notAllowed: InputProblem = { status: 400, code: "input-not-allowed", error: INPUT_NOT_ALLOWED };
+
+/** 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. */
+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 };
+ }
+ 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 };
+ try {
+ if (!fs.statSync(absolutePath(rel)).isFile()) return { status: 404, code: "input-gone", error: GONE_MESSAGE };
+ } catch {
+ return { status: 404, code: "input-gone", error: GONE_MESSAGE };
+ }
+ return null;
+}
+
+/**
+ * The first problem with the files an account's run names, or null. Every value in `inputs` is a file; in
+ * `params.extra`, every top-level string (or list of strings) that names one.
+ */
+export function accountInputProblem(req: Pick<GenerationRequest, "inputs" | "params">, accountId: string): InputProblem | null {
+ const refs: string[] = [];
+ for (const v of Object.values(req.inputs ?? {})) {
+ if (v === undefined || v === null) continue;
+ const list = Array.isArray(v) ? v : [v];
+ for (const x of list) {
+ if (typeof x !== "string") return notAllowed;
+ if (x) refs.push(x);
+ }
+ }
+ for (const v of Object.values(req.params?.extra ?? {})) {
+ const list = typeof v === "string" ? [v] : Array.isArray(v) && v.every((x) => typeof x === "string") ? (v as string[]) : [];
+ refs.push(...list.filter(looksLikeFile));
+ }
+ for (const ref of refs) {
+ const problem = checkFile(ref.trim(), accountId);
+ if (problem) return problem;
+ }
+ return null;
+}
diff --git a/src/server/account-library.ts b/src/server/account-library.ts
index 3f2331ab..fe95fa92 100644
--- a/src/server/account-library.ts
+++ b/src/server/account-library.ts
@@ -1,10 +1,12 @@
import "server-only";
+import path from "node:path";
import { db } from "./db";
/**
- * An account's own runs (public sign-up, "Your GPU"): a generation an account started carries its
- * id in the stored request (`account`, set by the server only). Everything else is the owner's.
- * The proxy lets an account read, cancel and delete only its own (src/proxy.ts).
+ * An account's own runs and files (public sign-up, "Your GPU"): a generation an account started carries its id in the
+ * stored request (`account`, set by the server only); a stored file carries it in `assets.account_id` (its upload, or a
+ * file of its run). Everything else is the owner's. The proxy lets an account read, cancel and delete only its own
+ * (src/proxy.ts), and its runs read only its own files (storage.ts guardRef).
*/
/** Who made this generation: an account id, null for the owner, undefined when there is no such generation. */
@@ -13,10 +15,30 @@ export function generationAccount(id: string): string | null | undefined {
return row ? (row.account ?? null) : undefined;
}
-/** Who made the generation this stored file came from (undefined: not a generation's file). */
+/**
+ * Whose stored file this is (`rel`: its path under the files folder, with / or the platform's separator): an account id,
+ * null for the owner, undefined when no file is stored there. A file stamped before the account column existed goes by
+ * the run that made it.
+ */
export function fileAccount(rel: string): string | null | undefined {
+ // Rows store the platform's separator (backslashes on Windows); a URL always has /.
+ const native = rel.split("/").join(path.sep);
+ const row = db()
+ .prepare(
+ `SELECT COALESCE(a.account_id, CASE WHEN json_valid(g.request_json) THEN json_extract(g.request_json, '$.account') END) AS account
+ FROM assets a LEFT JOIN generations g ON g.id = a.generation_id WHERE a.rel_path IN (?, ?) LIMIT 1`,
+ )
+ .get(rel, native) as { account: string | null } | undefined;
+ return row ? (row.account ?? null) : undefined;
+}
+
+/** Whose stored file this asset id is (as fileAccount; undefined when there is no such asset). */
+export function assetAccount(id: string): string | null | undefined {
const row = db()
- .prepare("SELECT json_extract(g.request_json, '$.account') AS account FROM assets a JOIN generations g ON g.id = a.generation_id WHERE a.rel_path = ? LIMIT 1")
- .get(rel) as { account: string | null } | undefined;
+ .prepare(
+ `SELECT COALESCE(a.account_id, CASE WHEN json_valid(g.request_json) THEN json_extract(g.request_json, '$.account') END) AS account
+ FROM assets a LEFT JOIN generations g ON g.id = a.generation_id WHERE a.id = ? LIMIT 1`,
+ )
+ .get(id) as { account: string | null } | undefined;
return row ? (row.account ?? null) : undefined;
}
diff --git a/src/server/account-loras.ts b/src/server/account-loras.ts
new file mode 100644
index 00000000..350a87ad
--- /dev/null
+++ b/src/server/account-loras.ts
@@ -0,0 +1,60 @@
+import "server-only";
+import type { LoraRef, ModelRoute } from "@/lib/catalog/types";
+import { missingFilesMessage, missingLoras, type MissingFiles } from "@/lib/missing-files";
+import { comfyLoraFiles, ownGpu } from "./providers/comfyui";
+import { tenantAccount } from "./tenant";
+
+/**
+ * The LoRAs an account's run adds (a preset's, a model's, the request's, a graph's own) must be on the account's own
+ * ComfyUI: Fuobe checks its GET /models/loras before the run is queued and again when it is handed over, and says
+ * what to download when one is missing. Nothing is ever downloaded onto the account's machine. The workflow's other
+ * files (checkpoints, encoders…) are the pre-flight's to check; ComfyUI's own "not in list" answer is the last word.
+ */
+
+declare global {
+ var __fuobeAccountLoras: Map<string, { at: number; files: string[] }> | undefined;
+}
+
+const TTL_MS = 60_000;
+const cache = () => (globalThis.__fuobeAccountLoras ??= new Map());
+
+/** The LoRA files on the account's ComfyUI (inside its run: onOwnGpu), cached a minute; null when it can't say. */
+export async function accountLoraList(route?: ModelRoute): Promise<string[] | null> {
+ const gpu = ownGpu();
+ if (!gpu?.url) return null;
+ const key = `${tenantAccount() ?? ""}|${gpu.url}`;
+ const hit = cache().get(key);
+ if (hit && Date.now() - hit.at < TTL_MS) return hit.files;
+ const files = await comfyLoraFiles(route);
+ if (!files || !Array.isArray(files)) return null;
+ const clean = files.filter((f): f is string => typeof f === "string");
+ cache().set(key, { at: Date.now(), files: clean });
+ if (cache().size > 5000) cache().delete(cache().keys().next().value!);
+ return clean;
+}
+
+/** Forget an account's list (its GPU address changed, or it was disconnected). */
+export function clearAccountLoras(accountId: string): void {
+ for (const k of cache().keys()) if (k.startsWith(`${accountId}|`)) cache().delete(k);
+}
+
+/** A run that needs files the account's ComfyUI doesn't have: `fix` lists them (409 comfy_missing_model). */
+export class MissingFilesError extends Error {
+ readonly status = 409;
+ constructor(readonly fix: MissingFiles) {
+ super(missingFilesMessage(fix));
+ }
+}
+
+/**
+ * The LoRAs in `needs` the account's ComfyUI lacks, or null (all there, nothing needed, or its list couldn't be read:
+ * the run goes ahead and ComfyUI's own check has the last word).
+ */
+export async function checkAccountLoras(needs: LoraRef[], workflowId?: string, route?: ModelRoute): Promise<MissingFiles | null> {
+ const wanted = needs.filter((l) => l?.file);
+ if (!wanted.length) return null;
+ const listed = await accountLoraList(route);
+ if (!listed) return null;
+ const items = missingLoras(wanted, listed);
+ return items.length ? { code: "comfy_missing_model", ...(workflowId && { workflowId }), items } : null;
+}
diff --git a/src/server/account-sweep.ts b/src/server/account-sweep.ts
new file mode 100644
index 00000000..d3134b5a
--- /dev/null
+++ b/src/server/account-sweep.ts
@@ -0,0 +1,97 @@
+import "server-only";
+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 { db } from "./db";
+import { deleteForever } from "./library";
+import { deleteAsset, scratchDir } from "./storage";
+
+/**
+ * Public sign-up: what an account keeps on this server goes in time. Its uploads after 14 days (even when a run still
+ * names them: a file can't be kept alive for ever), its runs and their files after 30, and everything at once when the
+ * account is deleted. Runs at boot, then daily (src/instrumentation.ts).
+ */
+
+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;
+
+/** Every account that owns a run or a file here. */
+function owners(): string[] {
+ const runs = db()
+ .prepare("SELECT DISTINCT json_extract(request_json, '$.account') AS id FROM generations WHERE json_extract(request_json, '$.account') IS NOT NULL")
+ .all() as { id: string }[];
+ const files = db().prepare("SELECT DISTINCT account_id AS id FROM assets WHERE account_id IS NOT NULL").all() as { id: string }[];
+ return [...new Set([...runs, ...files].map((r) => r.id).filter(Boolean))];
+}
+
+/**
+ * Remove a deleted account's runs (running ones are cancelled first) and files, then run the cleanups other features
+ * registered (account-files.ts onAccountDeleted).
+ */
+export async function purgeAccount(id: string): Promise<{ runs: number; files: number }> {
+ const runIds = (db().prepare("SELECT id FROM generations WHERE json_extract(request_json, '$.account') = ?").all(id) as { id: string }[]).map((r) => r.id);
+ let runs = 0;
+ for (let i = 0; i < runIds.length; i += 200) runs += await deleteForever(runIds.slice(i, i + 200));
+ const files = (db().prepare("SELECT id FROM assets WHERE account_id = ?").all(id) as { id: string }[]).map((r) => r.id);
+ for (const f of files) deleteAsset(f);
+ clearAccountLoras(id);
+ await runAccountDeletedHooks(id);
+ return { runs, files: files.length };
+}
+
+/** One sweep (see the header). `now` for tests. */
+export async function sweepAccountFiles(now = Date.now()): Promise<{ uploads: number; runs: number; files: number; accounts: number }> {
+ // Uploads past their time.
+ const uploads = db()
+ .prepare("SELECT id FROM assets WHERE account_id IS NOT NULL AND source = 'upload' AND created_at < ?")
+ .all(now - RETENTION_MS.upload) as { id: string }[];
+ for (const u of uploads) deleteAsset(u.id);
+ // Runs past their time (not one still going), with their files.
+ const old = (
+ db()
+ .prepare("SELECT id FROM generations WHERE json_extract(request_json, '$.account') IS NOT NULL AND created_at < ? AND status NOT IN ('queued', 'running')")
+ .all(now - RETENTION_MS.run) as { id: string }[]
+ ).map((r) => r.id);
+ let runs = 0;
+ for (let i = 0; i < old.length; i += 200) runs += await deleteForever(old.slice(i, i + 200));
+ // Results kept for a run another one named, once both are gone.
+ const orphans = db()
+ .prepare(
+ "SELECT id FROM assets WHERE account_id IS NOT NULL AND source != 'upload' AND created_at < ? AND (generation_id IS NULL OR generation_id NOT IN (SELECT id FROM generations))",
+ )
+ .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));
+ for (const id of gone) await purgeAccount(id);
+ // Upload temp files the server left behind.
+ 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 });
+ } catch {}
+ }
+ } catch {}
+ return { uploads: uploads.length, runs, files: orphans.length, accounts: gone.length };
+}
+
+declare global {
+ var __fuobeAccountSweep: { timer: NodeJS.Timeout } | undefined;
+}
+
+/** Sweep now, then every day (once per process). */
+export function ensureAccountSweep(): void {
+ if (globalThis.__fuobeAccountSweep) return;
+ const run = () => void sweepAccountFiles().catch((e) => console.warn(`[fuobe] account sweep failed: ${(e as Error).message}`));
+ const timer = setInterval(run, DAY);
+ timer.unref?.();
+ globalThis.__fuobeAccountSweep = { timer };
+ run();
+}
diff --git a/src/server/db.ts b/src/server/db.ts
index 515deb2c..c79c27bd 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -5,6 +5,7 @@ import path from "node:path";
export const DATA_DIR = path.resolve(/*turbopackIgnore: true*/ process.env.FUOBE_DATA_DIR ?? path.join(process.cwd(), "data"));
+/** Run in order, once each: a migration is known by its place in this list (append only, never reorder). */
export const MIGRATIONS: string[] = [
`CREATE TABLE IF NOT EXISTS generations (
id TEXT PRIMARY KEY,
@@ -593,6 +594,17 @@ export const MIGRATIONS: string[] = [
);
CREATE INDEX IF NOT EXISTS gpu_audit_target ON gpu_audit(target_key, at DESC);
ALTER TABLE generations ADD COLUMN fix_json TEXT;`,
+ // Public sign-up ("Your GPU"): who owns a stored file. An account's uploads and the files of its runs carry its id; the
+ // owner's stay NULL. Files made before this go by the run that made them. Keep this entry last when rebasing: a
+ // migration is known by its place in this list.
+ `ALTER TABLE assets ADD COLUMN account_id TEXT;
+ UPDATE assets SET account_id = (
+ SELECT json_extract(g.request_json, '$.account') FROM generations g
+ WHERE g.id = assets.generation_id AND json_valid(g.request_json)
+ ) WHERE generation_id IS NOT NULL;
+ CREATE INDEX IF NOT EXISTS assets_account ON assets(account_id, created_at DESC);
+ CREATE INDEX IF NOT EXISTS assets_rel ON assets(rel_path);
+ CREATE INDEX IF NOT EXISTS assets_generation ON assets(generation_id);`,
];
declare global {
diff --git a/src/server/direct-gate.ts b/src/server/direct-gate.ts
new file mode 100644
index 00000000..4f4d87a3
--- /dev/null
+++ b/src/server/direct-gate.ts
@@ -0,0 +1,28 @@
+import "server-only";
+import { GUEST_HEADER, GUEST_RUN_MESSAGE } from "@/lib/guest-access";
+import { authEnabled, crossSite, hostAllowed, publicSignup, requestViewer, type Account } from "./auth";
+
+/**
+ * The proxy's checks, for a route the proxy doesn't run on (src/proxy.ts config.matcher leaves /api/uploads out, so a
+ * large upload streams to the route instead of being held in the proxy's memory). In the proxy's order: a host this
+ * install answers (without a password), a request from this site, then who is asking. Returns the viewer, or the
+ * answer the proxy would have given.
+ */
+export function gateDirect(request: Request): { kind: "owner" } | { kind: "account"; account: Account } | Response {
+ const url = new URL(request.url);
+ const host = request.headers.get("host") ?? url.host;
+ // DNS rebinding: a page whose own name now points at this machine (no password: the sign-in check can't stop it).
+ if (!authEnabled() && !hostAllowed(host)) {
+ return Response.json(
+ { error: `Blocked a request for ${host}, which isn't a local address. If that's how you reach Fuobe, add it to FUOBE_ALLOWED_ORIGINS (or set a password).` },
+ { status: 403 },
+ );
+ }
+ if (crossSite(request, url.host)) {
+ return Response.json({ error: "Blocked a request from another website. Use Fuobe from its own address (or add it to FUOBE_ALLOWED_ORIGINS)." }, { status: 403 });
+ }
+ const viewer = requestViewer(request);
+ if (viewer.kind === "owner" || viewer.kind === "account") return viewer;
+ if (publicSignup(host)) return Response.json({ error: GUEST_RUN_MESSAGE }, { status: 401, headers: { [GUEST_HEADER]: "1", "Cache-Control": "no-store" } });
+ return Response.json({ error: "Sign in, or send an API token as Authorization: Bearer fuobe_…" }, { status: 401, headers: { "WWW-Authenticate": 'Bearer realm="fuobe"' } });
+}
diff --git a/src/server/enhance.ts b/src/server/enhance.ts
index 33e2612d..b08c4127 100644
--- a/src/server/enhance.ts
+++ b/src/server/enhance.ts
@@ -3,6 +3,7 @@ import Anthropic from "@anthropic-ai/sdk";
import type { MediaKind, Operation } from "@/lib/catalog/types";
import { activeLocal, aiHelper, chatLocal, type JsonSpec } from "./llm";
import { engineMode, getSetting } from "./settings";
+import { tenant } from "./tenant";
/**
* "Enhance prompt": rewrite a short idea into a rich, model-friendly prompt.
@@ -92,6 +93,9 @@ async function viaLocal(system: string, user: string, images: LlmImage[], opts:
* model, whichever server runs it (Ollama, LM Studio, Unsloth Studio or the custom one: Settings → AI helper).
*/
export function llmTextBackend(): "claude" | "ollama" | null {
+ // An account's run or a visitor's price check never uses the install's AI helper (its LLM, its Claude key): the
+ // offline wording (heuristicEnhance) is used instead.
+ if (tenant()) return null;
const choice = aiHelper();
if (choice === "none") return null;
if (choice === "anthropic" || (choice === "auto" && engineMode() !== "open" && !!getSetting("anthropicKey"))) return "claude";
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 0f95207e..1484c246 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -51,9 +51,16 @@ 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, probeComfy } from "./providers/comfyui";
+import { comfyLoraFiles, onOwnGpu, outputFetch, outsideOwnGpu, ownGpu, probeComfy } from "./providers/comfyui";
import { accountGpu } from "./auth";
-import { CONNECT_GPU_MESSAGE, OWN_GPU_TOOL_MESSAGE } from "@/lib/guest-access";
+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 { checkAccountLoras } from "./account-loras";
+import { missingFilesMessage } from "@/lib/missing-files";
+import { Readable } from "node:stream";
+import { pipeline } from "node:stream/promises";
import { graphLoras } from "@/lib/catalog/character-swap";
import { ensureLorasOnComfy, prepareCloudLoras, withoutUnreachableCivitai } from "./loras";
import { ACCESS_PLACE } from "@/lib/model-access";
@@ -63,9 +70,9 @@ import type { PollContext, PollResult, RemoteOutput } from "./providers/types";
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 } from "./settings";
-import { fetchRemoteToFile } from "./remote-fetch";
-import { adoptFile, contentTypeFor, deleteAsset, localHead, readRef, saveFile, scratchDir } from "./storage";
+import { engineMode, getSetting, withCandidates, withoutCandidates } from "./settings";
+import { blockedForAccounts, fetchRemoteToFile } from "./remote-fetch";
+import { absolutePath, adoptFile, contentTypeFor, deleteAsset, localHead, readRef, saveFile, scratchDir } from "./storage";
interface Row {
id: string;
@@ -566,6 +573,12 @@ function sizedMixedFrame(plan: ReturnType<typeof planGeneration>, req: Generatio
return fit ? { ...plan, params: { ...plan.params, extra: { ...plan.params.extra, image_size: fit } } } : plan;
}
+/**
+ * The elements "@Name" can mention: the owner's. An account's run or a visitor's price check has none, so "@Name" stays
+ * words there (an owner's element photo or LoRA never reaches someone else's run).
+ */
+export const mentionElements = () => (tenant() ? [] : listElements());
+
/** Resolve mentions and drawings, plan, enforce the engine mode and pick a provider route. */
function prepare(original: GenerationRequest) {
// @element mentions become reference images / LoRAs; the stored request keeps the mentions for "Reuse".
@@ -579,7 +592,7 @@ function prepare(original: GenerationRequest) {
const allowed = found && offeredFor(found, onSide);
const model = allowed && dualEngine(allowed) ? onEngine(allowed, engineFor(allowed, onSide)) : allowed;
const lookup = (id: string) => (model && id === model.id ? model : getModel(id));
- const req = model ? stripMotionPaths(applySketch(applyMentions(worded, model, listElements()).request, model).request, model) : worded;
+ const req = model ? stripMotionPaths(applySketch(applyMentions(worded, model, mentionElements()).request, model).request, model) : worded;
let plan = sizedMixedFrame(planGeneration(req, lookup, getPreset), req);
if (mode !== "both" && plan.model.engine !== mode) {
throw new Error(
@@ -718,7 +731,26 @@ export interface CreateOptions {
const depIds = (v: string | null): string[] => (!v ? [] : v.startsWith("[") ? (JSON.parse(v) as string[]) : [v]);
-export function createGenerations(asked: GenerationRequest, opts: CreateOptions = {}): Generation[] {
+/**
+ * Public sign-up: inside an account's run (accountRun) every request it makes, and every step its chains queue, is
+ * stamped as the account's own, on the open engine. A request stamped for another account, a step that waits for
+ * someone else's run, a run on an account's GPU outside its account, and a guest's run are refused.
+ */
+function stampTenant(asked: GenerationRequest, opts: CreateOptions): GenerationRequest {
+ if (tenant()?.kind === "guest") throw new Error(GUEST_RUN_MESSAGE);
+ const who = tenantAccount();
+ if (!who) {
+ if (ownGpu()) throw new Error("A run on an account's own GPU must be that account's run.");
+ return asked;
+ }
+ if (asked.account && asked.account !== who) throw new Error("That run belongs to another account.");
+ const deps = opts.dependsOn === undefined ? [] : Array.isArray(opts.dependsOn) ? opts.dependsOn : [opts.dependsOn];
+ if (deps.some((d) => generationAccount(d) !== who)) throw new Error("An earlier step of this run isn't yours.");
+ return { ...asked, account: who, engine: "open" };
+}
+
+export function createGenerations(given: GenerationRequest, opts: CreateOptions = {}): Generation[] {
+ const asked = stampTenant(given, opts);
// A retired model or operation (a retry, an old script, a saved project) runs on what replaced it, and says so.
const moved = currentRequest(asked);
const original = moved.request;
@@ -1100,9 +1132,13 @@ async function advanceDependents(): Promise<void> {
}
submitting().add(r.id);
let handedOff = false;
+ // An account's step reads its inputs, and is planned, as its run was: as that account, on its own ComfyUI.
+ const own = stored.account ? accountRun(stored.account, "comfyui") : undefined;
+ const asRun = <T,>(fn: () => T): T => (own && "run" in own ? own.run(fn) : fn());
try {
+ if (own && "error" in own) throw new Error(own.error);
// The planned op (r.op), not request.op: a translate whose op was inferred still gets the cue list.
- const values = await Promise.all(outputs.map((o, i) => chainValue(pickOutput(o, slots[i]), slots[i], r.op)));
+ const values = await asRun(() => Promise.all(outputs.map((o, i) => chainValue(pickOutput(o, slots[i]), slots[i], r.op))));
const missing = values.findIndex((u) => !u);
if (missing >= 0) {
fail(`${earlier} has no ${slotNoun(slots[missing])} to use`);
@@ -1112,7 +1148,8 @@ async function advanceDependents(): Promise<void> {
// the engine it runs on, ComfyUI taken as answering: one on the cloud doesn't use it, so doesn't wait for it.
const model = getModel(request.modelId);
const runs = model && dualEngine(model) ? onEngine(model, pickEngine(model, request.engine, engineMode(), () => true)) : model;
- if (runs?.routes.some((x) => x.provider === "comfyui") && !(await probeComfy()) && deps.some((d) => d!.provider === "comfyui")) {
+ // (An account's step looks at its own ComfyUI, never the install's: inside its run, probeComfy says yes and the run finds out.)
+ if (runs?.routes.some((x) => x.provider === "comfyui") && !(await asRun(() => probeComfy())) && deps.some((d) => d!.provider === "comfyui")) {
// The earlier steps ran for real on ComfyUI: one missed check (a server busy finishing them, or restarting)
// mustn't make this one a demo, which chainMode fails. Look again at once (one forced look a sweep), then wait
// for the next sweeps (COMFY_WAIT from the first miss) before chainMode has its say.
@@ -1130,10 +1167,7 @@ async function advanceDependents(): Promise<void> {
// Filled with the slots that have an input; stored with its whole chain (and what was skipped) for a retry.
const filled = withChainInputs({ ...request, chain: slots }, values as string[]);
const original: GenerationRequest = { ...filled, chain: request.chain, chainFilled: true };
- // An account's step is planned as its run was: on its own ComfyUI.
- const own = original.account ? accountRun(original.account, "comfyui") : undefined;
- if (own && "error" in own) throw new Error(own.error);
- const prepared = own ? own.run(() => prepare(original)) : prepare(original);
+ const prepared = asRun(() => prepare(original));
const mode = chainMode(prepared, deps as Pick<Row, "provider">[], original);
if (mode.error) throw new Error(mode.error);
const p = mode.forceDemo ? { ...prepared, demo: true, providerId: "mock" as const, cost: 0 } : prepared;
@@ -1181,15 +1215,41 @@ export function accountRun(accountId: string, providerId: string): { run: <T>(fn
const gpu = accountGpu(accountId);
if (!gpu) return { error: CONNECT_GPU_MESSAGE };
if (providerId !== "comfyui") return { error: OWN_GPU_ONLY };
- return { run: (fn) => onOwnGpu(gpu, () => withCandidates({ engineMode: "open", demoMode: "off" }, fn)) };
+ // As the account (tenant.ts: only its own files and runs), on its own ComfyUI, the open engine, no demo outputs.
+ return { run: (fn) => runAsTenant({ kind: "account", id: accountId }, () => onOwnGpu(gpu, () => withCandidates({ engineMode: "open", demoMode: "off" }, fn))) };
}
/**
- * Plan (and price) as a visitor's run would go: on its own ComfyUI (none yet: an empty address that
- * reaches nothing), the open engine, no demo outputs. For previews; a run goes through accountRun.
+ * 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
+ * accountRun.
*/
-export function asVisitor<T>(gpu: { url: string; token?: string } | null, fn: () => T): T {
- return onOwnGpu(gpu ?? { url: "" }, () => withCandidates({ engineMode: "open", demoMode: "off" }, fn));
+export function asVisitor<T>(gpu: { url: string; token?: string } | null, fn: () => T, accountId?: string): T {
+ return runAsTenant(accountId ? { kind: "account", id: accountId } : { kind: "guest" }, () =>
+ onOwnGpu(gpu ?? { url: "" }, () => withCandidates({ engineMode: "open", demoMode: "off" }, 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 => {
@@ -1221,38 +1281,53 @@ async function submitNow(
const adapter = provider(providerId);
submitting().add(id);
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());
const prep = async (ref?: string) => {
if (!ref) return undefined;
- const f = await readRef(ref);
- return adapter.prepareFile(f.data, f.contentType, f.name, route);
+ return gate(async () => {
+ const f = await readRef(ref);
+ return adapter.prepareFile(f.data, f.contentType, f.name, route);
+ });
};
// The input clip's header (size, frame rate, length): upscalers that take a factor and frame-count routes read it.
let source: Pick<GenInput, "sourceSize" | "sourceFps" | "sourceDuration"> = {};
const prepVideo = async (ref?: string) => {
if (!ref) return undefined;
- const f = await readRef(ref);
- const facts = mediaFacts(f.data);
- source = {
- ...(facts.width && facts.height ? { sourceSize: { width: facts.width, height: facts.height } } : {}),
- ...(facts.fps ? { sourceFps: facts.fps } : {}),
- ...(facts.duration ? { sourceDuration: facts.duration } : {}),
- };
- return adapter.prepareFile(f.data, f.contentType, f.name, route);
+ return gate(async () => {
+ const f = await readRef(ref);
+ const facts = mediaFacts(f.data);
+ source = {
+ ...(facts.width && facts.height ? { sourceSize: { width: facts.width, height: facts.height } } : {}),
+ ...(facts.fps ? { sourceFps: facts.fps } : {}),
+ ...(facts.duration ? { sourceDuration: facts.duration } : {}),
+ };
+ return adapter.prepareFile(f.data, f.contentType, f.name, route);
+ });
};
// A talking avatar is as long as its voice (fal's InfiniteTalk and Wan 2.2 S2V take a frame count): the voice's header.
const prepVoice = async (ref?: string) => {
if (!ref) return undefined;
- const f = await readRef(ref);
- const facts = mediaFacts(f.data);
- if (facts.duration && !source.sourceDuration) source = { ...source, sourceDuration: facts.duration };
- return adapter.prepareFile(f.data, f.contentType, f.name, route);
+ return gate(async () => {
+ const f = await readRef(ref);
+ const facts = mediaFacts(f.data);
+ if (facts.duration && !source.sourceDuration) source = { ...source, sourceDuration: facts.duration };
+ return adapter.prepareFile(f.data, f.contentType, f.name, route);
+ });
};
const prepMask = async (ref?: string) => {
if (!ref) return undefined;
- const f = await readRef(ref);
- const fmt = route.map?.maskFormat;
- const data = fmt && fmt !== "white" && f.contentType === "image/png" ? convertMask(f.data, fmt) : f.data;
- return adapter.prepareFile(data, f.contentType, f.name, route);
+ return gate(async () => {
+ const f = await readRef(ref);
+ const fmt = route.map?.maskFormat;
+ const data = fmt && fmt !== "white" && f.contentType === "image/png" ? convertMask(f.data, fmt) : f.data;
+ return adapter.prepareFile(data, f.contentType, f.name, route);
+ });
};
let prompt = plan.prompt;
if (req.params?.enhancePrompt && prompt) {
@@ -1377,11 +1452,24 @@ declare global {
var __fuobeRunner: RunnerState | undefined;
}
+/**
+ * Run `fn` as the owner's background work: outside any account's run (its tenant, its ComfyUI, the open-engine settings
+ * it runs with). Timers started inside inherit where they were started, so the runner, often first started by a run, is
+ * started this way: every tick then polls each row in that row's own context.
+ */
+export function outsideRuns<T>(fn: () => T): T {
+ return outsideTenant(() => outsideOwnGpu(() => withoutCandidates(fn)));
+}
+
/**
* Start the background runner (once per process; started at boot by src/instrumentation.ts).
* Also installs the live-update hooks and primes the reachability probes routing reads.
*/
export function ensureRunner(): void {
+ outsideRuns(startRunner);
+}
+
+function startRunner(): void {
watchGenerations(db());
const cur = globalThis.__fuobeRunner;
if (cur) {
@@ -1447,10 +1535,13 @@ async function tick(): Promise<void> {
state.busy = true;
try {
sweepInterrupted();
+ // The owner's jobs first. An account's ComfyUI may be slow to answer: its polls run on their own, so they never hold
+ // up the owner's (pollGuarded never polls one row twice at once).
const active = db()
- .prepare("SELECT * FROM generations WHERE status IN ('queued','running') AND external_id IS NOT NULL ORDER BY created_at ASC LIMIT 50")
+ .prepare(`SELECT * FROM generations WHERE status IN ('queued','running') AND external_id IS NOT NULL ORDER BY ${ACCOUNT_LAST}, created_at ASC LIMIT 100`)
.all() as Row[];
- await Promise.all([...active.map(pollGuarded), pollTrainings().catch(() => {}), advanceDependents().catch(() => {})]);
+ for (const r of active) if (accountOf(r)) void pollGuarded(r);
+ await Promise.all([...active.filter((r) => !accountOf(r)).map(pollGuarded), pollTrainings().catch(() => {}), advanceDependents().catch(() => {})]);
} finally {
state.busy = false;
}
@@ -1463,7 +1554,7 @@ async function fastTick(): Promise<void> {
try {
const rows = db()
.prepare(
- "SELECT g.*, r.started_at AS run_started_at FROM generations g LEFT JOIN generation_runs r ON r.id = g.id WHERE g.status = 'running' AND g.external_id IS NOT NULL AND g.progress IS NOT NULL ORDER BY g.created_at ASC LIMIT 50",
+ `SELECT g.*, r.started_at AS run_started_at FROM generations g LEFT JOIN generation_runs r ON r.id = g.id WHERE g.status = 'running' AND g.external_id IS NOT NULL AND g.progress IS NOT NULL ORDER BY ${ACCOUNT_LAST.replace("request_json", "g.request_json")}, g.created_at ASC LIMIT 50`,
)
.all() as (Row & { run_started_at: number | null })[];
const now = Date.now();
@@ -1474,12 +1565,17 @@ async function fastTick(): Promise<void> {
const ran = r.run_started_at ? r.updated_at - r.run_started_at : 0;
return ran > 0 && p > 0 && (p * (now - r.run_started_at!)) / ran >= 0.9;
});
- await Promise.all(nearlyDone.slice(0, 20).map(pollGuarded));
+ const soon = nearlyDone.slice(0, 20);
+ for (const r of soon) if (accountOf(r)) void pollGuarded(r);
+ await Promise.all(soon.filter((r) => !accountOf(r)).map(pollGuarded));
} finally {
state.fastBusy = false;
}
}
+/** Order by: the owner's rows (no account in the request) before accounts'. */
+const ACCOUNT_LAST = "(json_extract(request_json, '$.account') IS NOT NULL)";
+
function runRoute(model: NonNullable<ReturnType<typeof getModel>>, r: Pick<Row, "op" | "provider">): ModelRoute {
return model.routes.find((x) => x.op === r.op && (x.provider === r.provider || r.provider === "mock")) ?? model.routes[0];
}
@@ -1516,10 +1612,13 @@ async function pollOne(r: Row): Promise<void> {
} catch (e) {
pollError = e;
}
+ // An account's job waits at most 30 minutes in its own ComfyUI's queue.
+ const account = accountOf(r);
+ const queueMs = account ? ACCOUNT_LIMITS.queueMs : QUEUE_TIMEOUT_MS;
if (!res || res.state === "queued" || res.state === "running") {
// A job that has just left the queue gets its full running time from now.
const startsNow = res?.state === "running" && !run.started_at;
- const overdue = run.started_at ? now - run.started_at > TIMEOUT_MS : !startsNow && now - run.submitted_at > QUEUE_TIMEOUT_MS;
+ const overdue = run.started_at ? now - run.started_at > TIMEOUT_MS : !startsNow && now - run.submitted_at > queueMs;
if (overdue) {
// Stop the provider's job too, so it doesn't keep rendering (or billing) for nothing.
await provider(r.provider)
@@ -1527,7 +1626,11 @@ async function pollOne(r: Row): Promise<void> {
.catch(() => {});
update(r.id, {
status: "failed",
- error: run.started_at ? `Timed out after ${TIMEOUT_MS / 60_000} minutes` : `Timed out waiting ${QUEUE_TIMEOUT_MS / 3_600_000} hours in the provider's queue`,
+ error: run.started_at
+ ? `Timed out after ${TIMEOUT_MS / 60_000} minutes`
+ : account
+ ? `Timed out waiting ${queueMs / 60_000} minutes in your ComfyUI's queue`
+ : `Timed out waiting ${QUEUE_TIMEOUT_MS / 3_600_000} hours in the provider's queue`,
completed_at: now,
message: null,
});
@@ -1545,6 +1648,9 @@ async function pollOne(r: Row): Promise<void> {
// Mark first so a slow download isn't polled twice.
update(r.id, { status: "running", progress: 0.99, message: "Saving results" });
const outputs: OutputFile[] = [];
+ // An account's job keeps at most 16 outputs, and a result it can't save fails the job (never a link to its ComfyUI).
+ const dropped = account && res.outputs.length > ACCOUNT_LIMITS.outputsPerJob ? res.outputs.length - ACCOUNT_LIMITS.outputsPerJob : 0;
+ if (dropped) res = { ...res, outputs: res.outputs.slice(0, ACCOUNT_LIMITS.outputsPerJob) };
// Remove background: of a cut-out and its mask (BiRefNet's answer), the one asked for (params.matteOutput).
const matte = r.op === "bg-remove-video" ? (JSON.parse(r.request_json) as GenerationRequest).params?.matteOutput : undefined;
// The face mosaic's cloud step answers with the faces' masks: the result is the picture, pixelated under them.
@@ -1561,6 +1667,12 @@ async function pollOne(r: Row): Promise<void> {
try {
outputs.push(await persistOutput(o, r.id));
} catch (e) {
+ if (account) {
+ for (const kept of outputs) if (kept.assetId) deleteAsset(kept.assetId);
+ const why = e instanceof AccountFilesFull ? e.message : `Couldn't save a result from your ComfyUI: ${(e as Error).message}`;
+ update(r.id, { status: "failed", error: why, completed_at: Date.now(), message: null });
+ return;
+ }
outputs.push({ url: o.url, kind: o.kind ?? r.kind, ...inlineText(o.text, o.meta), ...(o.draftId ? { draftId: o.draftId } : {}) });
console.warn(`[fuobe] could not save output for ${r.id}: ${(e as Error).message}`);
}
@@ -1588,7 +1700,7 @@ async function pollOne(r: Row): Promise<void> {
status: "succeeded",
outputs_json: JSON.stringify(outputs),
progress: 1,
- message: null,
+ message: dropped ? `Kept the first ${ACCOUNT_LIMITS.outputsPerJob} results (your ComfyUI made ${ACCOUNT_LIMITS.outputsPerJob + dropped})` : null,
completed_at: Date.now(),
});
}
@@ -1596,9 +1708,12 @@ async function pollOne(r: Row): Promise<void> {
/** Start (or keep running) the 3D finish of a job whose outputs are stored; it marks the job done when it ends. */
function resumeFinish(r: Row): void {
const outputs = JSON.parse(r.outputs_json || "[]") as OutputFile[];
+ // An account's model: one account finish at a time, and no turntable on the server (its browser records one).
+ const account = accountOf(r);
startModelFinish(r.id, outputs, {
op: r.op,
provider: r.provider,
+ account,
onMessage: (message) => update(r.id, { message }),
done: (finished) => {
const now = db().prepare("SELECT status, external_meta_json FROM generations WHERE id = ?").get(r.id) as Pick<Row, "status" | "external_meta_json"> | undefined;
@@ -1608,7 +1723,7 @@ function resumeFinish(r: Row): void {
delete meta.finishing;
update(r.id, { status: "succeeded", outputs_json: JSON.stringify(finished), external_meta_json: JSON.stringify(meta), progress: 1, message: null, completed_at: Date.now() });
// The model can be opened and downloaded now; its turntable is rendered after and added to the result.
- startTurntable(r.id, outputStore(r.id));
+ if (!account) startTurntable(r.id, outputStore(r.id));
},
});
}
@@ -1727,7 +1842,8 @@ async function keepLink(v: unknown, label: string, generationId: string): Promis
return saveFile({ data: f.data, contentType: f.contentType, source: "generation", generationId }).url;
}
const dest = path.join(scratchDir(), `${generationId}-${label}-${nanoid(6)}`);
- const res = await fetchRemoteToFile(v, dest);
+ // An account's run: 1 GB at most, and never this machine or its networks.
+ const res = await fetchRemoteToFile(v, dest, tenantAccount() ? { maxBytes: ACCOUNT_LIMITS_FILE_BYTES, blocked: blockedForAccounts } : {});
const name = new URL(res.url).pathname.split("/").pop() || undefined;
const header = res.contentType && res.contentType !== "application/octet-stream" ? res.contentType : null;
return adoptFile({ from: dest, contentType: header ?? contentTypeFor(name ?? "", "application/octet-stream"), name, source: "generation", generationId }).url;
@@ -1750,8 +1866,81 @@ function relinkMain(meta: Record<string, unknown> | undefined, from: string, to:
return out;
}
+/** The most one file of an account's run may weigh (a result, or a file it links to). */
+const ACCOUNT_LIMITS_FILE_BYTES = 2 ** 30;
+
+/** An account's files are full (ACCOUNT_LIMITS.totalBytes): the job fails with this message. */
+class AccountFilesFull extends Error {}
+
+/** Types an account's result is stored as; any other is stored as application/octet-stream (.bin), never served as a page. */
+const ACCOUNT_OUTPUT_TYPES = new Set([
+ "image/png",
+ "image/jpeg",
+ "image/webp",
+ "image/gif",
+ "video/mp4",
+ "video/webm",
+ "video/quicktime",
+ "audio/mpeg",
+ "audio/wav",
+ "audio/x-wav",
+ "audio/ogg",
+ "audio/flac",
+ "audio/mp4",
+ "audio/aac",
+ "audio/webm",
+ "model/gltf-binary",
+ "text/plain",
+ "application/x-subrip",
+ "text/vtt",
+]);
+
+const accountType = (t: string) => {
+ const bare = t.split(";")[0].trim().toLowerCase();
+ return ACCOUNT_OUTPUT_TYPES.has(bare) ? bare : "application/octet-stream";
+};
+
+/** Before an account's file is kept: refuse it (and remove `file`, when given) when its files would pass 3 GB. */
+function roomFor(account: string, bytes: number, file?: string): void {
+ if (accountUsage(account).total + bytes <= ACCOUNT_LIMITS.totalBytes) return;
+ if (file) fs.rmSync(file, { force: true });
+ throw new AccountFilesFull(ACCOUNT_MESSAGES.filesFull);
+}
+
+/**
+ * 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.
+ */
+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 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;
+ }
+ roomFor(account, fs.statSync(dest).size, dest);
+ const header = res.headers.get("content-type")?.split(";")[0];
+ const given = o.contentType ?? (header && header !== "application/octet-stream" ? header : contentTypeFor(new URL(o.url).searchParams.get("filename") ?? o.url));
+ const asset = adoptFile({ from: dest, contentType: accountType(given), source: "generation", generationId, accountId: account });
+ const meta = relinkMain(linked, o.url, asset.url);
+ const text = o.text ?? (asset.kind === "text" && asset.size <= MAX_INLINE_TEXT * 4 ? fs.readFileSync(absolutePath(asset.relPath), "utf8") : undefined);
+ return {
+ url: asset.url,
+ kind: asset.contentType === "application/octet-stream" ? (o.kind ?? asset.kind) : asset.kind,
+ contentType: asset.contentType,
+ assetId: asset.id,
+ ...inlineText(text, meta),
+ ...(o.draftId ? { draftId: o.draftId } : {}),
+ };
+}
+
async function persistOutput(o: RichOutput, generationId: string): Promise<OutputFile> {
const linked = await persistArtifacts(o.meta, generationId, o.url);
+ const account = tenantAccount();
+ if (account && o.url && /^https?:\/\//.test(o.url)) return persistAccountOutput(o, generationId, account, linked);
let data: Buffer;
let contentType = o.contentType;
if (!o.url && o.text !== undefined) {
@@ -1772,6 +1961,10 @@ async function persistOutput(o: RichOutput, generationId: string): Promise<Outpu
const header = res.headers.get("content-type")?.split(";")[0];
contentType ??= header && header !== "application/octet-stream" ? header : contentTypeFor(new URL(o.url).searchParams.get("filename") ?? o.url);
}
+ if (account) {
+ roomFor(account, data.length);
+ contentType = accountType(contentType!);
+ }
const asset = saveFile({ data, contentType: contentType!, source: "generation", generationId });
const meta = relinkMain(linked, o.url, asset.url);
// A text file's words travel with the generation, so feeds and the next chained step can use them.
diff --git a/src/server/loras.ts b/src/server/loras.ts
index ea1c4043..1c332881 100644
--- a/src/server/loras.ts
+++ b/src/server/loras.ts
@@ -6,6 +6,7 @@ import { cloudPath, civitaiVersion, gated, libraryEntry, localOnly, loraByFile,
import type { LoraRef } from "@/lib/catalog/types";
import { DATA_DIR, db } from "./db";
import { getSetting } from "./settings";
+import { tenant } from "./tenant";
/**
* LoRA files for both engines. Nothing here is committed to the repo: files are fetched when a run needs them.
@@ -302,6 +303,8 @@ const licenceSnapshot = (ref: LoraRef, entry: LoraEntry | undefined, permissions
* with what to do. `listed` is ComfyUI's own list (GET /models/loras), null when it can't be read.
*/
export async function ensureLorasOnComfy(loras: LoraRef[] | undefined, listed: string[] | null, onProgress?: (m: string) => void): Promise<void> {
+ // Never for an account's run: this writes to the install's own LoRA folder (account-loras.ts checks its ComfyUI instead).
+ if (tenant()) throw new Error("LoRAs are never downloaded for a run on someone's own GPU");
if (!loras?.length) return;
const dir = getSetting("comfyLorasDir");
// A list ComfyUI couldn't give says nothing: without a folder to check, ComfyUI's own check has the last word.
@@ -569,6 +572,8 @@ export function filesInLoraFolder(): { files: Set<string>; problem?: string } {
* never carries it (fitLoras leaves it out and says so).
*/
export function withoutUnreachableCivitai(loras: LoraRef[], target: MirrorTarget): { loras: LoraRef[]; notes: string[] } {
+ // An account's run: the install's civitai key and LoRA folder say nothing about its ComfyUI (account-loras.ts checks that).
+ if (tenant()) return { loras, notes: [] };
const civitai = loras.filter((l) => !l.hostedUrl && needsToken(l.url) && (target === "comfyui" || !localOnly(l)));
if (!civitai.length || civitaiKey()) return { loras, notes: [] };
const folder = target === "comfyui" && getSetting("comfyLorasDir") ? filesInLoraFolder().files : null;
@@ -593,7 +598,8 @@ export function withoutUnreachableCivitai(loras: LoraRef[], target: MirrorTarget
* nothing is left out, ComfyUI's own check has the last word).
*/
export function withoutMissingOnComfy(loras: LoraRef[], listed: string[] | null): { loras: LoraRef[]; notes: string[] } {
- if (!loras.length || !listed || getSetting("comfyLorasDir")) return { loras, notes: [] };
+ // An account's run: account-loras.ts names what its ComfyUI lacks.
+ if (tenant() || !loras.length || !listed || getSetting("comfyLorasDir")) return { loras, notes: [] };
const have = new Set(listed.map((f) => f.replace(/\\/g, "/")));
const missing = loras.filter((l) => l.file && !have.has(l.file));
if (!missing.length) return { loras, notes: [] };
diff --git a/src/server/model3d-finish.ts b/src/server/model3d-finish.ts
index 59ad4180..dc33cd43 100644
--- a/src/server/model3d-finish.ts
+++ b/src/server/model3d-finish.ts
@@ -72,13 +72,45 @@ function killTree(child: ChildProcess): void {
type Run = { code: number | null; stdout: string; stderr: string };
-function runScript(script: string, args: string[], o: { timeoutMs: number; signal: AbortSignal; lowPriority?: boolean; onLine?: (line: string) => void }): Promise<Run> {
+/** The only variables finish-glb.mjs and render-turntable.mjs read (and what Node, Chromium and ffmpeg need to start). */
+const SCRIPT_ENV = [
+ "PATH",
+ "Path",
+ "SYSTEMROOT",
+ "SystemRoot",
+ "TEMP",
+ "TMP",
+ "TMPDIR",
+ "HOME",
+ "USERPROFILE",
+ "LOCALAPPDATA",
+ "APPDATA",
+ "LANG",
+ "FFMPEG_PATH",
+ "CHROMIUM_PATH",
+ "FUOBE_CHROMIUM",
+ "PLAYWRIGHT_BROWSERS_PATH",
+];
+
+/**
+ * The environment the scripts run with: a short list, never the server's own (its keys, passwords and tokens stay in
+ * this process, whatever a model file makes a script do).
+ */
+export function scriptEnv(): NodeJS.ProcessEnv {
+ const env = {} as NodeJS.ProcessEnv;
+ for (const k of SCRIPT_ENV) if (process.env[k] !== undefined) env[k] = process.env[k]!;
+ env.FUOBE_PARENT_PIPE = "1";
+ return env;
+}
+
+function runScript(script: string, args: string[], o: { timeoutMs: number; signal: AbortSignal; cwd: string; lowPriority?: boolean; onLine?: (line: string) => void }): Promise<Run> {
return new Promise((resolve, reject) => {
if (o.signal.aborted) return reject(new Error("Stopped"));
- // stdin stays open and unused: the script stops when it closes (this server went away).
+ // stdin stays open and unused: the script stops when it closes (this server went away). It runs in the job's
+ // own temp folder, with a short environment.
const child = spawn(process.execPath, [path.join(SCRIPTS, script), ...args], {
- cwd: /*turbopackIgnore: true*/ process.cwd(),
- env: { ...process.env, FUOBE_PARENT_PIPE: "1" },
+ cwd: o.cwd,
+ env: scriptEnv(),
windowsHide: true,
stdio: ["pipe", "pipe", "pipe"],
});
@@ -130,6 +162,7 @@ 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());
@@ -141,6 +174,20 @@ function oneAtATime<T>(fn: () => Promise<T>): Promise<T> {
return next;
}
+// 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;
+}
+
+/** An account's raw GLB over this is kept as it is, with no finish. */
+export const ACCOUNT_FINISH_MAX_BYTES = 300 * 2 ** 20;
+
+/** What an account's finished model says of its turntable: none on the server; the 3D page records one in the browser. */
+export const ACCOUNT_TURNTABLE = "skipped: record it in your browser";
+
/**
* Step 1 (see the header): the web GLB. Returns the outputs to store: the model output with meta.web and
* meta.finish (turntable "queued" when there's a web GLB to render).
@@ -148,7 +195,7 @@ function oneAtATime<T>(fn: () => Promise<T>): Promise<T> {
export async function finishModel(
generationId: string,
outputs: OutputFile[],
- o: { op: string; provider: string; onMessage?: (m: string) => void; signal?: AbortSignal },
+ o: { op: string; provider: string; onMessage?: (m: string) => void; signal?: AbortSignal; account?: string },
): Promise<OutputFile[]> {
const signal = o.signal ?? new AbortController().signal;
const i = modelToFinish(o, outputs);
@@ -157,15 +204,19 @@ export async function finishModel(
const asset = getAsset(mesh.assetId!);
if (!asset) return outputs;
const raw = absolutePath(asset.relPath);
- const tmp = await fs.promises.mkdtemp(path.join(os.tmpdir(), "fuobe-3d-"));
const finish: Record<string, unknown> = { version: MODEL_FINISH_VERSION };
const meta: Record<string, unknown> = { ...mesh.meta };
+ if (o.account && asset.size > ACCOUNT_FINISH_MAX_BYTES) {
+ finish.error = "web GLB: the model is over 300 MB, so it is kept as it is";
+ return outputs.map((x, j) => (j === i ? { ...mesh, meta: { ...meta, finish } } : x));
+ }
+ const tmp = await fs.promises.mkdtemp(path.join(os.tmpdir(), "fuobe-3d-"));
try {
o.onMessage?.("Finishing the 3D model");
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 });
+ const run = await runScript("finish-glb.mjs", ["--in", raw, "--out", webFile], { timeoutMs: FINISH_TIMEOUT_MS, signal, cwd: tmp });
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) {
@@ -175,7 +226,7 @@ export async function finishModel(
if (stats) {
const web = saveFile({ data: await fs.promises.readFile(webFile), contentType: "model/gltf-binary", name: "model-web.glb", source: "derived", generationId });
meta.web = web.url;
- Object.assign(finish, { material: stats.material, triangles: stats.triangles, rawBytes: stats.bytesIn, webBytes: stats.bytesOut, webAsset: web.id, turntable: "queued" });
+ Object.assign(finish, { material: stats.material, triangles: stats.triangles, rawBytes: stats.bytesIn, webBytes: stats.bytesOut, webAsset: web.id, turntable: o.account ? ACCOUNT_TURNTABLE : "queued" });
}
} finally {
await removeDir(tmp);
@@ -196,12 +247,14 @@ export function finishing(generationId: string): boolean {
export function startModelFinish(
generationId: string,
outputs: OutputFile[],
- o: { op: string; provider: string; onMessage?: (m: string) => void; done: (outputs: OutputFile[]) => void },
+ o: { op: string; provider: string; onMessage?: (m: string) => void; done: (outputs: OutputFile[]) => void; account?: string },
): void {
if (finishing(generationId)) return;
const ctl = new AbortController();
running().set(generationId, ctl);
- void finishModel(generationId, outputs, { ...o, signal: ctl.signal })
+ 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())
.catch((e) => {
if (ctl.signal.aborted) return null;
console.warn(`[fuobe] 3D finish for ${generationId} failed: ${(e as Error).message}`);
@@ -295,6 +348,7 @@ async function renderTurntable(generationId: string, mesh: OutputFile, store: Ou
return runScript("render-turntable.mjs", ["--glb", absolutePath(web.relPath), "--out", video, "--poster", posterFile, "--material", finish.material ?? "auto"], {
timeoutMs: TURNTABLE_TIMEOUT_MS,
signal,
+ cwd: tmp,
lowPriority: true,
// "frame 12/96" after each frame.
onLine: (line) => {
diff --git a/src/server/png.ts b/src/server/png.ts
index 456b6d65..a027ffd8 100644
--- a/src/server/png.ts
+++ b/src/server/png.ts
@@ -12,6 +12,9 @@ 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). */
+export const MAX_PNG_PIXELS = 40_000_000;
+
interface Decoded {
width: number;
height: number;
@@ -44,7 +47,10 @@ 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)");
- const raw = zlib.inflateSync(Buffer.concat(idat));
+ // 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`);
+ // 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;
const px = Buffer.alloc(stride * height);
for (let y = 0; y < height; y++) {
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index 7c25efbd..f8d8ff05 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -121,11 +121,33 @@ export function onOwnGpu<T>(gpu: OwnGpu, fn: () => T): T {
/** Inside onOwnGpu: the account's ComfyUI. */
export const ownGpu = (): OwnGpu | undefined => ownGpuStore.getStore();
-/** fetch() for a provider's file: through fetchPublic on an account's own ComfyUI. */
+/** Run `fn` outside any account's ComfyUI (the install's own again). */
+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 }) : fetch(url, init);
+ return ownGpu() ? fetchPublic(url, init, { timeoutMs: 120_000, ...OWN_OUTPUT_LIMITS }) : fetch(url, init);
+}
+
+/**
+ * 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
+ * 60 seconds. A slow or endless answer can't hold the server.
+ */
+export function ownGpuLimits(p: string): { maxBytes: number; deadlineMs: number } {
+ const at = p.split("?")[0];
+ if (at.startsWith("/view")) return OWN_OUTPUT_LIMITS;
+ if (at.startsWith("/upload/")) return { maxBytes: 2 ** 20, deadlineMs: 5 * 60_000 };
+ if (at.startsWith("/object_info")) return { maxBytes: 64 * 2 ** 20, deadlineMs: 2 * 60_000 };
+ return { maxBytes: 8 * 2 ** 20, deadlineMs: 60_000 };
}
+/** A job id as ComfyUI gives it (a UUID): anything else from an account's ComfyUI is refused, never put in a path. */
+export const PROMPT_ID = /^[\w-]{1,64}$/;
+
function baseUrl(worker: ComfyWorker = "main"): string {
const own = ownGpu();
if (own) return own.url;
@@ -157,7 +179,7 @@ async function comfyFetch(p: string, init: RequestInit = {}, worker: ComfyWorker
// A visitor without a GPU of its own (a price check): nothing to reach, and never the install's.
if (!base) throw new ProviderError(CONNECT_GPU_MESSAGE);
try {
- return await fetchPublic(`${base}${p}`, { ...init, headers: { ...authHeaders(worker), ...(init.headers ?? {}) } }, { timeoutMs: 120_000 });
+ return await fetchPublic(`${base}${p}`, { ...init, headers: { ...authHeaders(worker), ...(init.headers ?? {}) } }, { timeoutMs: 120_000, ...ownGpuLimits(p) });
} catch (e) {
throw new ProviderError(`Can't reach your ComfyUI at ${base} (${(e as Error).message}). Is it running, and is its tunnel up?`);
}
@@ -543,9 +565,15 @@ declare global {
const MEDIA_FILE = /^(video|audio)\//;
const MEDIA_EXT = /\.(mp4|m4v|mov|m4a|wav|flac|mp3)$/i;
+/** A file name as remembered: an account's ComfyUI names its own files, so they are kept apart by its address. */
+const mediaKey = (name: string) => {
+ const own = ownGpu();
+ return own ? `${own.url}|${name}` : name;
+};
+
function rememberMedia(name: string, info: MediaInfo) {
const seen = (globalThis.__fuobeComfyMedia ??= new Map());
- seen.set(name, info);
+ seen.set(mediaKey(name), info);
if (seen.size > 256) seen.delete(seen.keys().next().value!);
}
@@ -567,7 +595,7 @@ function aviInfo(data: Buffer): MediaInfo | null {
/** The header facts of a file this server uploaded to ComfyUI (a still has only its size; undefined for unreadable containers). */
export function mediaInfoFor(name: unknown): MediaInfo | undefined {
- return typeof name === "string" ? globalThis.__fuobeComfyMedia?.get(name) : undefined;
+ return typeof name === "string" ? globalThis.__fuobeComfyMedia?.get(mediaKey(name)) : undefined;
}
/** Inputs a workflow handles its own way (the manifest doesn't say). */
@@ -1333,7 +1361,7 @@ async function uploadTo(worker: ComfyWorker, data: Buffer, contentType: string,
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`);
}
if (!res.ok) {
- const text = await res.text().catch(() => "");
+ const text = (await res.text().catch(() => "")).slice(0, 500);
throw worker === "isolated" ? isolatedAnswer("an upload", res.status, reasonOf(text)) : new ProviderError(`ComfyUI upload failed: ${res.status} ${text}`);
}
const j = (await res.json()) as { name: string; subfolder?: string };
@@ -1440,14 +1468,20 @@ export const comfyProvider: ProviderAdapter = {
// A LoRA it lacks: point at its model card (a civitai download URL answers 401 without the key) and the LoRA folder setting.
const loraModels = (input.loras ?? []).map((l) => ({ file: l.file, folder: "loras", url: loraByFile(l.file)?.page ?? (l.url && !needsToken(l.url) ? l.url : undefined) }));
let detail = body.node_errors && Object.keys(body.node_errors as object).length ? explainComfyError(body.node_errors, { ...manifest, models: [...manifest.models, ...loraModels] }) : (missingPack ?? body.error?.message);
- if (detail && loraModels.some((l) => detail!.includes(`"${l.file}"`))) detail = `${detail}\nSet the LoRA folder in Settings → LoRAs and Fuobe downloads LoRAs before a run`;
+ // (Settings → LoRAs is the owner's page: an account's ComfyUI gets its LoRAs by hand.)
+ if (detail && !ownGpu() && loraModels.some((l) => detail!.includes(`"${l.file}"`))) detail = `${detail}\nSet the LoRA folder in Settings → LoRAs and Fuobe downloads LoRAs before a run`;
if (!detail && !res.ok && worker === "isolated") throw isolatedAnswer("the prompt", res.status);
throw Object.assign(new ProviderError(detail ?? `ComfyUI /prompt failed (${res.status})`, res.status), fix ? { fix } : {});
}
+ if (!PROMPT_ID.test(body.prompt_id)) {
+ // Stop it there: an id Fuobe can't use would never be collected.
+ throw new ProviderError(ownGpu() ? "Your ComfyUI answered with a job id Fuobe can't use." : "ComfyUI answered with a job id Fuobe can't use.");
+ }
return { externalId: body.prompt_id, meta: { ...meta, generationId, ...(worker === "isolated" && { worker }) }, payload: wf };
},
async poll({ externalId, meta }) {
+ if (!PROMPT_ID.test(externalId)) return { state: "failed", error: "ComfyUI answered with a job id Fuobe can't use." };
const worker: ComfyWorker = meta.worker === "isolated" ? "isolated" : "main";
let manifest: ManifestWorkflow | undefined;
try {
@@ -1479,7 +1513,7 @@ export const comfyProvider: ProviderAdapter = {
};
const isDone = (e: HistoryEntry | undefined): e is HistoryEntry => !!e && (!!e.status?.completed || e.status?.status_str === "success" || e.status?.status_str === "error");
- const entry = (await comfyJson<Record<string, HistoryEntry>>(`/history/${externalId}`, worker))[externalId];
+ const entry = (await comfyJson<Record<string, HistoryEntry>>(`/history/${encodeURIComponent(externalId)}`, worker))[externalId];
if (isDone(entry)) return finished(entry);
// Still queued or running?
@@ -1490,7 +1524,7 @@ export const comfyProvider: ProviderAdapter = {
const pendingIdx = queue.queue_pending?.findIndex((q) => q[1] === externalId) ?? -1;
if (!running && pendingIdx < 0 && !entry) {
// It may have finished between the two requests (ComfyUI moves it from the queue to the history at once).
- const again = (await comfyJson<Record<string, HistoryEntry>>(`/history/${externalId}`, worker))[externalId];
+ const again = (await comfyJson<Record<string, HistoryEntry>>(`/history/${encodeURIComponent(externalId)}`, worker))[externalId];
if (isDone(again)) return finished(again);
const misses = globalThis.__fuobeComfyMisses ?? (globalThis.__fuobeComfyMisses = new Map());
const n = (misses.get(externalId) ?? 0) + 1;
diff --git a/src/server/rate.ts b/src/server/rate.ts
new file mode 100644
index 00000000..b8a03026
--- /dev/null
+++ b/src/server/rate.ts
@@ -0,0 +1,63 @@
+import "server-only";
+
+/**
+ * A sliding-window limiter in memory, keyed by a string ("up:<accountId>", "run:<accountId>", "gpu:<accountId>"). Each
+ * key keeps the times of its recent hits. One server process: a restart starts every count again, which is fine for
+ * limits that only keep one account from crowding out the others.
+ */
+
+declare global {
+ var __fuobeRate: Map<string, number[]> | undefined;
+ var __fuobeRateBusy: Map<string, number> | undefined;
+}
+
+const hits = (): Map<string, number[]> => (globalThis.__fuobeRate ??= new Map());
+
+/** What a key's hits look like now: ok when another fits; retryAfterS when it doesn't. */
+export function peek(key: string, limit: number, windowMs: number, now = Date.now()): { ok: boolean; retryAfterS: number } {
+ const list = (hits().get(key) ?? []).filter((t) => t > now - windowMs);
+ if (list.length < limit) return { ok: true, retryAfterS: 0 };
+ return { ok: false, retryAfterS: Math.max(1, Math.ceil((list[list.length - limit] + windowMs - now) / 1000)) };
+}
+
+/** Count a hit when it fits under `limit` in `windowMs`; else refuse it, with the seconds until one fits. */
+export function hit(key: string, limit: number, windowMs: number, now = Date.now()): { ok: boolean; retryAfterS: number } {
+ const map = hits();
+ const list = (map.get(key) ?? []).filter((t) => t > now - windowMs);
+ if (list.length >= limit) {
+ map.set(key, list);
+ return { ok: false, retryAfterS: Math.max(1, Math.ceil((list[list.length - limit] + windowMs - now) / 1000)) };
+ }
+ list.push(now);
+ map.set(key, list);
+ // Keys nobody uses any more go (a rough sweep, so the map can't grow without end).
+ if (map.size > 20_000) for (const [k, v] of map) if (!v.length || v[v.length - 1] < now - 24 * 60 * 60_000) map.delete(k);
+ return { ok: true, retryAfterS: 0 };
+}
+
+/** Take back the last hit of a key (a request refused for another reason after it was counted). */
+export function unhit(key: string): void {
+ hits().get(key)?.pop();
+}
+
+/** At most `limit` at once for a key: returns a release function, or null when the key is full. */
+export function enter(key: string, limit: number): (() => void) | null {
+ const busy = (globalThis.__fuobeRateBusy ??= new Map());
+ const n = busy.get(key) ?? 0;
+ if (n >= limit) return null;
+ busy.set(key, n + 1);
+ let done = false;
+ return () => {
+ if (done) return;
+ done = true;
+ const left = (busy.get(key) ?? 1) - 1;
+ if (left > 0) busy.set(key, left);
+ else busy.delete(key);
+ };
+}
+
+/** Tests: forget every count. */
+export function resetRates(): void {
+ globalThis.__fuobeRate?.clear();
+ globalThis.__fuobeRateBusy?.clear();
+}
diff --git a/src/server/remote-fetch.ts b/src/server/remote-fetch.ts
index 704d5a69..5c1b9400 100644
--- a/src/server/remote-fetch.ts
+++ b/src/server/remote-fetch.ts
@@ -4,7 +4,8 @@ import fs from "node:fs";
import http from "node:http";
import https from "node:https";
import net from "node:net";
-import { Readable } from "node:stream";
+import os from "node:os";
+import { Readable, Transform } from "node:stream";
/**
* Fetch a file from a URL someone handed us (API callers, MCP clients, the Assist LLM) without
@@ -54,14 +55,29 @@ function hextets(ip: string): number[] | null {
return all.length === 8 && all.every((n) => Number.isFinite(n)) ? all : null;
}
+const embedded = (hi: number, lo: number) => `${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`;
+
+/**
+ * The IPv4 addresses an IPv6 address carries inside it: IPv4-mapped (::ffff:a.b.c.d), IPv4-compatible (::a.b.c.d),
+ * NAT64 (64:ff9b::/96 and the local-use 64:ff9b:1::/48), 6to4 (2002::/16) and Teredo (2001::/32: its server, and its
+ * client with the bits flipped). `wrapped` is true for every form but the mapped one, which a dual-stack socket uses
+ * for plain IPv4.
+ */
+function innerV4(h: number[]): { v4: string[]; wrapped: boolean } {
+ if (h.slice(0, 5).every((x) => x === 0) && h[5] === 0xffff) return { v4: [embedded(h[6], h[7])], wrapped: false };
+ if (h.slice(0, 6).every((x) => x === 0) && (h[6] !== 0 || h[7] > 1)) return { v4: [embedded(h[6], h[7])], wrapped: true };
+ if (h[0] === 0x64 && h[1] === 0xff9b) return { v4: [embedded(h[6], h[7])], wrapped: true };
+ if (h[0] === 0x2002) return { v4: [embedded(h[1], h[2])], wrapped: true };
+ if (h[0] === 0x2001 && h[1] === 0) return { v4: [embedded(h[2], h[3]), embedded(h[6] ^ 0xffff, h[7] ^ 0xffff)], wrapped: true };
+ return { v4: [], wrapped: false };
+}
+
function blockedV6(ip: string): boolean {
const h = hextets(ip);
if (!h) return true;
- const embedded = (hi: number, lo: number) => `${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`;
if (h.slice(0, 7).every((x) => x === 0)) return true; // :: and ::1
- if (h.slice(0, 5).every((x) => x === 0) && h[5] === 0xffff) return blockedV4(embedded(h[6], h[7])); // ::ffff:a.b.c.d
- if (h[0] === 0x64 && h[1] === 0xff9b) return blockedV4(embedded(h[6], h[7])); // NAT64
- if (h[0] === 0x2002) return blockedV4(embedded(h[1], h[2])); // 6to4
+ const inner = innerV4(h);
+ if (inner.v4.length && !(h[0] === 0x2001 && h[1] === 0)) return inner.v4.some(blockedV4);
return (h[0] & 0xfe00) === 0xfc00 || (h[0] & 0xffc0) === 0xfe80 || (h[0] & 0xffc0) === 0xfec0 || (h[0] & 0xff00) === 0xff00;
}
@@ -72,6 +88,89 @@ export function isPrivateAddress(ip: string): boolean {
return true;
}
+// ---------------------------------------------------------------------------
+// An account's own ComfyUI (public sign-up): stricter than a link someone hands us
+
+declare global {
+ /** This machine's own addresses (os.networkInterfaces), refreshed every minute. */
+ var __fuobeSelfAddresses: { at: number; set: Set<string> } | undefined;
+ /** Tests only: the port of a stand-in ComfyUI an account may use on this machine (see loopbackGpuPort). */
+ var __fuobeTestGpuPort: number | undefined;
+}
+
+/** An address as compared: IPv4 as it is, IPv6 as 8 hextets (no zone). */
+const canonical = (ip: string): string => {
+ const bare = ip.toLowerCase().split("%")[0];
+ if (!net.isIPv6(bare)) return bare;
+ const h = hextets(bare);
+ return h ? h.map((x) => x.toString(16)).join(":") : bare;
+};
+
+/** This machine's own addresses (every interface, plus FUOBE_SELF_ADDRESSES, a comma list: a public address behind NAT). */
+export function selfAddresses(): Set<string> {
+ const cur = globalThis.__fuobeSelfAddresses;
+ if (cur && Date.now() - cur.at < 60_000) return cur.set;
+ const set = new Set<string>();
+ try {
+ for (const list of Object.values(os.networkInterfaces())) for (const a of list ?? []) set.add(canonical(a.address));
+ } catch {}
+ for (const a of (process.env.FUOBE_SELF_ADDRESSES ?? "").split(",")) if (a.trim()) set.add(canonical(a.trim()));
+ globalThis.__fuobeSelfAddresses = { at: Date.now(), set };
+ return set;
+}
+
+/** Loopback and "this host" addresses, in any IPv6 form that carries them. */
+function loopbackish(ip: string): boolean {
+ if (net.isIPv4(ip)) {
+ const [a] = v4(ip);
+ return a === 127 || a === 0;
+ }
+ const h = hextets(ip);
+ if (!h) return true;
+ if (h.slice(0, 7).every((x) => x === 0)) return true;
+ return innerV4(h).v4.some(loopbackish);
+}
+
+/**
+ * Addresses an account's ComfyUI may never be at: private and reserved networks (isPrivateAddress), this machine's own
+ * addresses, and IPv6 addresses that wrap an IPv4 address (::a.b.c.d, NAT64, 6to4, Teredo: no tunnel needs them, and
+ * they hide what they reach). FUOBE_ALLOW_PRIVATE_URLS=1 allows LAN addresses, never loopback or this machine.
+ */
+export function blockedForAccounts(ip: string): boolean {
+ if (!net.isIP(ip)) return true;
+ const h = net.isIPv6(ip) ? hextets(ip) : null;
+ const inner = h ? innerV4(h) : { v4: [] as string[], wrapped: false };
+ if (inner.wrapped) return true;
+ const self = selfAddresses();
+ if (self.has(canonical(ip)) || inner.v4.some((x) => self.has(x))) return true;
+ if (loopbackish(ip)) return true;
+ return !allowPrivate() && isPrivateAddress(ip);
+}
+
+/** Ports a stand-in ComfyUI may never use (the real ones on this machine, and the studio's own). */
+const RESERVED_PORTS = [8000, 8188, 8189, 8190, 8288, 3000, 3001];
+
+/**
+ * Tests and `next dev` only: an account's GPU may be a stand-in ComfyUI on this machine, at one port
+ * (vitest: globalThis.__fuobeTestGpuPort; `next dev`: FUOBE_DEV_GPU_LOOPBACK_PORT). `next start` and `next build`
+ * run with NODE_ENV=production, so this is always null on a live server.
+ */
+export function loopbackGpuPort(): number | null {
+ if (process.env.NODE_ENV === "production") return null;
+ const v =
+ process.env.VITEST === "true" ? globalThis.__fuobeTestGpuPort : process.env.NODE_ENV === "development" ? Number(process.env.FUOBE_DEV_GPU_LOOPBACK_PORT) : NaN;
+ return typeof v === "number" && Number.isInteger(v) && v >= 1024 && v <= 65535 && !RESERVED_PORTS.includes(v) ? v : null;
+}
+
+/** An address that is the stand-in ComfyUI of loopbackGpuPort: http://localhost or http://127.0.0.1 at exactly that port. */
+export function isLoopbackGpu(u: URL): boolean {
+ const port = loopbackGpuPort();
+ const host = u.hostname.replace(/^\[|\]$/g, "").toLowerCase();
+ return port !== null && u.protocol === "http:" && (host === "localhost" || host === "127.0.0.1") && Number(u.port) === port;
+}
+
+const LOOPBACK = new Set(["127.0.0.1", "::1"]);
+
export interface RemoteFetchOptions {
maxBytes?: number;
timeoutMs?: number;
@@ -222,13 +321,31 @@ function get(
* fetch() for a server someone else named (an account's own ComfyUI, public sign-up): any method and
* body, the response streamed, but the connection only goes to a public address, checked on the
* address the socket actually connects to (so a name re-pointed at this machine after it was saved
- * still can't reach the install's own ComfyUI or anything else on its network). Redirects aren't
- * followed. FUOBE_ALLOW_PRIVATE_URLS=1 allows private addresses, as for fetchRemote.
+ * still can't reach the install's own ComfyUI or anything else on its network: blockedForAccounts).
+ * Redirects aren't followed. The whole exchange has a deadline and the answer a size cap, so a slow
+ * or endless answer can't hold the server. FUOBE_ALLOW_PRIVATE_URLS=1 allows LAN addresses, never
+ * loopback or this machine's own.
*/
-export async function fetchPublic(url: string, init: RequestInit = {}, o: Pick<RemoteFetchOptions, "resolve" | "blocked" | "timeoutMs"> = {}): Promise<Response> {
+export interface PublicFetchOptions extends Pick<RemoteFetchOptions, "resolve" | "blocked"> {
+ /** Idle time: no bytes for this long ends the request (default 60 s). */
+ timeoutMs?: number;
+ /** The whole exchange, the answer's body read to its end included (default 60 s): past it, request and answer are destroyed. */
+ deadlineMs?: number;
+ /** The most the answer's body may hold (default 8 MiB): past it, reading the body fails. */
+ maxBytes?: number;
+}
+
+export const PUBLIC_FETCH_MAX_BYTES = 8 * 2 ** 20;
+
+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> {
const target = new URL(url);
if (target.protocol !== "http:" && target.protocol !== "https:") throw new RemoteFetchError(`Only http(s) addresses, not ${target.protocol}`);
- const blocked = o.blocked ?? ((ip: string) => !allowPrivate() && isPrivateAddress(ip));
+ // A stand-in ComfyUI on this machine (tests and `next dev` only): loopback, and nothing else, for this request.
+ const blocked = o.blocked ?? (isLoopbackGpu(target) ? (ip: string) => !LOOPBACK.has(ip) : blockedForAccounts);
+ const maxBytes = o.maxBytes ?? PUBLIC_FETCH_MAX_BYTES;
+ const deadlineMs = o.deadlineMs ?? 60_000;
const resolve = o.resolve ?? (async (host: string) => (await dns.lookup(host, { all: true, verbatim: true })).map((a) => a.address));
const host = target.hostname.replace(/^\[|\]$/g, "");
if (net.isIP(host) && blocked(host)) throw refuse(target.host);
@@ -249,18 +366,68 @@ export async function fetchPublic(url: string, init: RequestInit = {}, o: Pick<R
(e: Error) => cb(e, "", 4),
);
};
+ const tooBig = () => new RemoteFetchError(`The answer was over ${mbOf(maxBytes)}`);
return new Promise<Response>((resolveRes, reject) => {
+ let settled = false;
+ // The answer's body, counted on its way to the caller.
+ let counted: Transform | null = null;
+ const settle = (e?: Error, res?: Response) => {
+ if (settled) return;
+ settled = true;
+ if (e) reject(e);
+ else resolveRes(res!);
+ };
+ const fail = (e: Error) => {
+ clearTimeout(deadline);
+ req.destroy(e);
+ counted?.destroy(e);
+ settle(e);
+ };
+ // The whole exchange, not only the idle time: a ComfyUI that drips a byte at a time can't hold a request open.
+ const deadline = setTimeout(() => fail(new RemoteFetchError(`${target.host} took over ${Math.round(deadlineMs / 1000)} s to answer`)), deadlineMs);
+ deadline.unref?.();
const req = (target.protocol === "https:" ? https : http).request(target, { method: asked.method, headers, lookup, timeout: o.timeoutMs ?? 60_000 }, (res) => {
const status = res.statusCode ?? 0;
const out = new Headers();
for (const [k, v] of Object.entries(res.headers)) if (v !== undefined) out.set(k, Array.isArray(v) ? v.join(", ") : v);
+ if (Number(res.headers["content-length"] ?? 0) > maxBytes) {
+ res.destroy();
+ return fail(tooBig());
+ }
const empty = asked.method === "HEAD" || status === 204 || status === 304;
- if (empty) res.resume();
- resolveRes(new Response(empty ? null : (Readable.toWeb(res) as ReadableStream<Uint8Array>), { status, statusText: res.statusMessage, headers: out }));
+ if (empty) {
+ res.resume();
+ clearTimeout(deadline);
+ return settle(undefined, new Response(null, { status, statusText: res.statusMessage, headers: out }));
+ }
+ let seen = 0;
+ counted = new Transform({
+ transform(this: Transform, chunk: Buffer, _enc, cb) {
+ seen += chunk.length;
+ if (seen > maxBytes) {
+ // The answer's own error first (at once): destroying the response after can't replace it.
+ this.destroy(tooBig());
+ res.destroy();
+ return;
+ }
+ cb(null, chunk);
+ },
+ });
+ 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));
+ res.pipe(stream);
+ settle(undefined, new Response(Readable.toWeb(stream) as ReadableStream<Uint8Array>, { status, statusText: res.statusMessage, headers: out }));
});
req.on("timeout", () => req.destroy(new RemoteFetchError(`Timed out reaching ${target.host}`)));
- req.on("error", (e) => reject(e instanceof RemoteFetchError ? e : new RemoteFetchError(`Couldn't reach ${target.host}: ${e.message}`)));
- if (init.signal) init.signal.addEventListener("abort", () => req.destroy(new RemoteFetchError("Aborted")), { once: true });
+ req.on("error", (e) => {
+ const err = e instanceof RemoteFetchError ? e : new RemoteFetchError(`Couldn't reach ${target.host}: ${e.message}`);
+ counted?.destroy(err);
+ clearTimeout(deadline);
+ settle(err);
+ });
+ if (init.signal) init.signal.addEventListener("abort", () => fail(new RemoteFetchError("Aborted")), { once: true });
req.end(body);
});
}
diff --git a/src/server/settings.ts b/src/server/settings.ts
index ac62d665..fa95ac7d 100644
--- a/src/server/settings.ts
+++ b/src/server/settings.ts
@@ -87,6 +87,11 @@ export function withCandidates<T>(values: Partial<Record<SettingName, string>>,
return candidates.run(values, fn);
}
+/** Run `fn` with the saved settings only (outside any withCandidates). */
+export function withoutCandidates<T>(fn: () => T): T {
+ return candidates.exit(fn);
+}
+
/** Inside withCandidates: whether `name` is being tried with an unsaved value. */
export function isCandidate(name: SettingName): boolean {
return candidates.getStore()?.[name] !== undefined;
diff --git a/src/server/storage.ts b/src/server/storage.ts
index 36cbfd4a..a5000561 100644
--- a/src/server/storage.ts
+++ b/src/server/storage.ts
@@ -5,6 +5,8 @@ import { nanoid } from "nanoid";
import { DATA_DIR, db } from "./db";
import type { MediaKind } from "@/lib/catalog/types";
import { fetchRemote } from "./remote-fetch";
+import { tenant, tenantAccount } from "./tenant";
+import { assetAccount, fileAccount, generationAccount } from "./account-library";
export const FILES_DIR = path.join(DATA_DIR, "files");
@@ -24,6 +26,7 @@ const EXT_BY_TYPE: Record<string, string> = {
"audio/flac": "flac",
"audio/mp4": "m4a",
"audio/aac": "aac",
+ "audio/webm": "webm",
// Text outputs (transcripts, translations, scripts) and 3D models.
"text/plain": "txt",
"application/x-subrip": "srt",
@@ -102,6 +105,8 @@ export interface Asset {
generationId: string | null;
createdAt: number;
url: string;
+ /** Public sign-up: the account the file belongs to (its upload, or a file of its run); absent for the owner's. */
+ accountId?: string;
}
interface AssetRow {
@@ -114,6 +119,7 @@ interface AssetRow {
source: Asset["source"];
generation_id: string | null;
created_at: number;
+ account_id?: string | null;
}
export function fileUrl(relPath: string): string {
@@ -132,15 +138,30 @@ function toAsset(r: AssetRow): Asset {
generationId: r.generation_id,
createdAt: r.created_at,
url: fileUrl(r.rel_path),
+ ...(r.account_id ? { accountId: r.account_id } : {}),
};
}
-type NewAsset = { contentType: string; name?: string; source: Asset["source"]; generationId?: string };
+/** `accountId`: the account a file is stored for (default: the tenant's, else the account whose run made it). */
+type NewAsset = { contentType: string; name?: string; source: Asset["source"]; generationId?: string; accountId?: string };
-/** Store a file under files/<outputs|uploads>/<day>/<id>.<ext>: `put` writes it there, then its row is added. */
+/** The account a new file belongs to: given, the work's tenant, or the account whose run made it (null: the owner). */
+function ownerOf(opts: NewAsset): string | null {
+ return opts.accountId ?? tenantAccount() ?? (opts.generationId ? generationAccount(opts.generationId) : null) ?? 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.
+ */
function addAsset(opts: NewAsset, put: (abs: string) => void): Asset {
const id = nanoid(12);
- const ext = EXT_BY_TYPE[opts.contentType.split(";")[0].trim()] ?? opts.name?.split(".").pop()?.toLowerCase() ?? "bin";
+ 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 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}`);
const abs = path.join(FILES_DIR, relPath);
@@ -156,11 +177,12 @@ function addAsset(opts: NewAsset, put: (abs: string) => void): Asset {
source: opts.source,
generation_id: opts.generationId ?? null,
created_at: Date.now(),
+ account_id: account,
};
db()
.prepare(
- `INSERT INTO assets (id, kind, name, rel_path, content_type, size, source, generation_id, created_at)
- VALUES (@id, @kind, @name, @rel_path, @content_type, @size, @source, @generation_id, @created_at)`,
+ `INSERT INTO assets (id, kind, name, rel_path, content_type, size, source, generation_id, created_at, account_id)
+ VALUES (@id, @kind, @name, @rel_path, @content_type, @size, @source, @generation_id, @created_at, @account_id)`,
)
.run(row);
return toAsset(row);
@@ -192,7 +214,8 @@ export function getAsset(id: string): Asset | null {
/** Newest first; page with `before` (+ `beforeId`): the last asset of the previous page. Derived renders only when asked for. */
export function listAssets(opts: { source?: Asset["source"]; kind?: MediaKind; limit?: number; before?: number; beforeId?: string }): Asset[] {
- const where: string[] = [];
+ // The owner's files: an account's uploads and results are its own (public sign-up).
+ const where: string[] = ["account_id IS NULL"];
const args: unknown[] = [];
if (opts.source) {
where.push("source = ?");
@@ -232,6 +255,8 @@ 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;
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;
const fd = fs.openSync(absolutePath(rel), "r");
try {
const buf = Buffer.alloc(Math.min(maxBytes, fs.fstatSync(fd).size));
@@ -250,6 +275,8 @@ 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).
+ if (tenant()) guardRef(ref);
if (ref.startsWith("data:")) {
const m = /^data:([^;,]+)?(;base64)?,(.*)$/s.exec(ref);
if (!m) throw new Error("Malformed data URI");
@@ -278,6 +305,57 @@ 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). */
+export class RefError extends Error {
+ constructor(
+ message: string,
+ readonly status: 403 | 404,
+ ) {
+ super(message);
+ }
+}
+
+export const LINK_INPUT_MESSAGE = "Upload the file first. Runs on your GPU can't fetch links.";
+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 {
+ if (!ref.startsWith("/api/files/")) return null;
+ try {
+ return decodeURIComponent(ref.slice("/api/files/".length).split("?")[0]);
+ } catch {
+ return null;
+ }
+}
+
+/** Whether the tenant owns this file (an account: its own; a guest: none). */
+function ownsRef(ref: string, rel?: string | null): boolean {
+ const who = tenantAccount();
+ if (!who) return false;
+ if (ref.startsWith("/api/files/")) {
+ const r = rel ?? filesRel(ref);
+ return !!r && fileAccount(r) === who;
+ }
+ return assetAccount(ref) === who;
+}
+
+/**
+ * Inside a tenant (an account's run, a visitor's price check), what a run may read: a data: URI (the server makes these;
+ * the run route refuses them from accounts) and the tenant's own stored files. A link is refused (the server never
+ * fetches one for an account); another's file reads as not yours, one that is gone as gone. Throws a RefError.
+ */
+export function guardRef(ref: string): void {
+ if (!tenant() || ref.startsWith("data:")) return;
+ if (/^https?:\/\//i.test(ref)) throw new RefError(LINK_INPUT_MESSAGE, 403);
+ const owner = ref.startsWith("/api/files/") ? (filesRel(ref) === null ? undefined : fileAccount(filesRel(ref)!)) : assetAccount(ref);
+ if (owner === undefined) throw new RefError(GONE_MESSAGE, 404);
+ if (!tenantAccount() || owner !== tenantAccount()) throw new RefError(NOT_YOURS_MESSAGE, 403);
+}
+
export function toDataUri(data: Buffer, contentType: string): string {
return `data:${contentType};base64,${data.toString("base64")}`;
}
diff --git a/src/server/tenant.ts b/src/server/tenant.ts
new file mode 100644
index 00000000..df35c5d3
--- /dev/null
+++ b/src/server/tenant.ts
@@ -0,0 +1,31 @@
+import "server-only";
+import { AsyncLocalStorage } from "node:async_hooks";
+
+/**
+ * Who a piece of server work is for (public sign-up). An account's run, its polls and its chained steps run
+ * inside `runAsTenant({ kind: "account", id })` (generations.ts accountRun), a visitor's price check inside
+ * `{ kind: "guest" }` (asVisitor). Inside a tenant the server uses only that tenant's own things: its files
+ * (storage.ts readRef, localHead), its runs (createGenerations), never the owner's elements, LLM or LoRA folder.
+ * Outside any tenant: the owner, or the owner's background work.
+ */
+export type Tenant = { kind: "account"; id: string } | { kind: "guest" };
+
+declare global {
+ var __fuobeTenant: AsyncLocalStorage<Tenant> | undefined;
+}
+
+const store = () => (globalThis.__fuobeTenant ??= new AsyncLocalStorage<Tenant>());
+
+export const runAsTenant = <T,>(t: Tenant, fn: () => T): T => store().run(t, fn);
+
+/** Undefined: the owner (or the owner's background work). */
+export const tenant = (): Tenant | undefined => store().getStore();
+
+/** Run `fn` as the owner's work, outside any tenant (timers and background work it starts stay outside too). */
+export const outsideTenant = <T,>(fn: () => T): T => store().exit(fn);
+
+/** The account the current work is for, if any. */
+export const tenantAccount = (): string | undefined => {
+ const t = tenant();
+ return t?.kind === "account" ? t.id : undefined;
+};
diff --git a/src/server/visitor.ts b/src/server/visitor.ts
index c4101abe..491f4fc0 100644
--- a/src/server/visitor.ts
+++ b/src/server/visitor.ts
@@ -4,11 +4,12 @@ import { asVisitor } from "./generations";
/**
* Run a price check (an estimate route, or `?preview=1`) as the asker's run would go: the owner's
- * as always; a guest's or an account's on its own GPU (none yet: an address that reaches nothing),
- * the open engine and no demo outputs, so a visitor is never told a run is a free demo.
+ * as always; a guest's or an account's as that visitor (only its own files), on its own GPU (none
+ * yet: an address that reaches nothing), the open engine and no demo outputs, so a visitor is never
+ * told a run is a free demo.
*/
export function priceAs<T>(request: Request, fn: () => T): T {
const v = requestViewer(request);
if (v.kind === "owner") return fn();
- return asVisitor(v.kind === "account" ? accountGpu(v.account.id) : null, fn);
+ return v.kind === "account" ? asVisitor(accountGpu(v.account.id), fn, v.account.id) : asVisitor(null, fn);
}
diff --git a/tests/account-inputs.test.ts b/tests/account-inputs.test.ts
new file mode 100644
index 00000000..baa92823
--- /dev/null
+++ b/tests/account-inputs.test.ts
@@ -0,0 +1,123 @@
+import fs from "node:fs";
+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";
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-account-inputs-"));
+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;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const realFetch = globalThis.fetch;
+const fetched: string[] = [];
+globalThis.fetch = (async (input: RequestInfo | URL) => {
+ fetched.push(String(input instanceof Request ? input.url : input));
+ return new Response("not stubbed", { status: 599 });
+}) as typeof fetch;
+
+const auth = await import("@/server/auth");
+const { POST } = await import("@/app/api/generations/route");
+const { saveFile, deleteAsset } = await import("@/server/storage");
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+
+let fake: FakeComfy;
+let a = "";
+let cookie = "";
+beforeAll(async () => {
+ fake = await startFakeComfy({ loras: [], delayMs: 60_000 });
+ globalThis.__fuobeTestGpuPort = fake.port;
+ auth.setPassword("install password");
+ a = 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;
+ await fake.close();
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+beforeEach(() => {
+ resetRates();
+ // Each test starts with no runs going.
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();
+});
+
+const motion = (images: string[], extra: Record<string, unknown> = {}) => ({ feature: "video", modelId: "fuobe-dop", presetId: "motion-zoom-in", prompt: "a slow push", inputs: { images }, ...extra });
+
+function run(body: unknown, raw?: string) {
+ const text = raw ?? JSON.stringify(body);
+ return POST(new Request("http://localhost:3000/api/generations", { method: "POST", headers: { cookie, host: "localhost:3000", "content-type": "application/json", "content-length": String(Buffer.byteLength(text)) }, body: text }));
+}
+
+const own = () => saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload", accountId: a });
+
+describe("an account's run names only files it uploaded here", () => {
+ it("refuses the owner's file, in inputs or in params.extra", async () => {
+ const owners = saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload" });
+ const r = await run(motion([owners.url]));
+ expect(r.status).toBe(403);
+ expect(await r.json()).toMatchObject({ code: "input-not-yours", error: "That file isn't yours. Upload your own." });
+ const extra = await run(motion([own().url], { params: { extra: { audio2: owners.url } } }));
+ expect(extra.status).toBe(403);
+ expect(extra.headers.get("x-fuobe-gpu-setup")).toBeNull();
+ });
+
+ it("refuses data: URIs, links and asset ids", async () => {
+ for (const ref of [`data:image/png;base64,${TINY_PNG.toString("base64")}`, "https://example.com/a.png", own().id]) {
+ const r = await run(motion([ref]));
+ expect(r.status, ref.slice(0, 30)).toBe(400);
+ expect((await r.json()).code).toBe("input-not-allowed");
+ }
+ });
+
+ it("says when an upload has expired", async () => {
+ const gone = own();
+ deleteAsset(gone.id);
+ const r = await run(motion([gone.url]));
+ expect(r.status).toBe(404);
+ expect(await r.json()).toMatchObject({ code: "input-gone", error: "That file has expired. Upload it again." });
+ });
+
+ it("runs with its own upload", async () => {
+ const r = await run(motion([own().url]));
+ expect(r.status).toBe(201);
+ const { items } = await r.json();
+ expect(items[0].request.account).toBe(a);
+ });
+});
+
+describe("an account's fair share", () => {
+ it("has at most 4 runs going", async () => {
+ for (let i = 0; i < 4; i++) expect((await run(motion([own().url]))).status).toBe(201);
+ const fifth = await run(motion([own().url]));
+ expect(fifth.status).toBe(429);
+ expect((await fifth.json()).error).toBe("You have 4 runs going. Start the next one when one finishes.");
+ });
+
+ it("sends a small request", async () => {
+ const r = await run(null, JSON.stringify(motion([own().url], { prompt: "x".repeat(1_100_000) })));
+ expect(r.status).toBe(413);
+ });
+
+ it("makes up to 4 results a run, and says so", async () => {
+ const r = await run(motion([own().url], { params: { numOutputs: 8 } }));
+ expect(r.status).toBe(201);
+ const body = await r.json();
+ expect(body.items.length).toBe(4);
+ expect(body.notes).toContain("Runs on your GPU make up to 4 at a time.");
+ });
+
+ it("never reached the install's ComfyUI", () => {
+ // (The runner's own reachability check of the install's ComfyUI, /system_stats, is the owner's background work.)
+ expect(fetched.filter((u) => u.includes("owner-comfy.test") && !u.endsWith("/system_stats"))).toEqual([]);
+ });
+});
diff --git a/tests/account-retention.test.ts b/tests/account-retention.test.ts
new file mode 100644
index 00000000..33c6f9cf
--- /dev/null
+++ b/tests/account-retention.test.ts
@@ -0,0 +1,122 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { TINY_PNG } from "./helpers/fake-comfy-runner";
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-account-retention-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+
+const auth = await import("@/server/auth");
+const { db } = await import("@/server/db");
+const { saveFile, getAsset, absolutePath, scratchDir } = await import("@/server/storage");
+const { sweepAccountFiles, purgeAccount } = await import("@/server/account-sweep");
+const { onAccountDeleted } = await import("@/server/account-files");
+const { DELETE } = await import("@/app/api/generations/[id]/route");
+afterAll(() => {
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+
+const DAY = 24 * 60 * 60_000;
+let a = "";
+beforeAll(() => {
+ auth.setPassword("install password");
+ a = auth.createAccount("[email protected]", "long enough").id;
+});
+
+/** A finished run, made `ageDays` ago, with one output file; its request names `input` when given. */
+function runRow(id: string, account: string | undefined, ageDays: number, input?: string) {
+ const at = Date.now() - ageDays * DAY;
+ db()
+ .prepare(
+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'video', 'fuobe-dop', 'open', 'comfyui', 'i2v', 'video', 'succeeded', ?, '[]', ?, ?)",
+ )
+ .run(id, JSON.stringify({ feature: "video", modelId: "fuobe-dop", ...(account && { account }), ...(input && { inputs: { images: [input] } }) }), at, at);
+ const out = saveFile({ data: TINY_PNG, contentType: "image/png", source: "generation", generationId: id });
+ db().prepare("UPDATE assets SET created_at = ? WHERE id = ?").run(at, out.id);
+ db().prepare("UPDATE generations SET outputs_json = ? WHERE id = ?").run(JSON.stringify([{ url: out.url, kind: "image", assetId: out.id }]), id);
+ return out;
+}
+
+function upload(account: string | undefined, ageDays: number) {
+ const f = saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload", ...(account && { accountId: account }) });
+ db().prepare("UPDATE assets SET created_at = ? WHERE id = ?").run(Date.now() - ageDays * DAY, f.id);
+ return f;
+}
+
+const exists = (id: string) => {
+ const asset = getAsset(id);
+ return !!asset && fs.existsSync(absolutePath(asset.relPath));
+};
+const runExists = (id: string) => !!db().prepare("SELECT 1 FROM generations WHERE id = ?").get(id);
+
+describe("what an account keeps goes in time", () => {
+ it("removes uploads after 14 days (even when a run names them) and runs after 30, never the owner's", async () => {
+ const oldUpload = upload(a, 15);
+ const newUpload = upload(a, 2);
+ const ownerUpload = upload(undefined, 400);
+ // A recent run still names the old upload: it goes anyway.
+ runRow("recent-run", a, 1, oldUpload.url);
+ const oldOut = runRow("old-run", a, 31);
+ const keptOut = runRow("kept-run", a, 10);
+ const ownerOut = runRow("owner-old-run", undefined, 400);
+ // An upload's temp file left behind an hour ago.
+ const stale = path.join(scratchDir(), "up-stale");
+ fs.writeFileSync(stale, "x");
+ fs.utimesSync(stale, new Date(Date.now() - 2 * 3600_000), new Date(Date.now() - 2 * 3600_000));
+
+ const swept = await sweepAccountFiles();
+ expect(swept.uploads).toBe(1);
+ expect(swept.runs).toBe(1);
+ expect(exists(oldUpload.id)).toBe(false);
+ expect(exists(newUpload.id)).toBe(true);
+ expect(runExists("old-run")).toBe(false);
+ expect(exists(oldOut.id)).toBe(false);
+ expect(runExists("kept-run")).toBe(true);
+ expect(exists(keptOut.id)).toBe(true);
+ expect(runExists("recent-run")).toBe(true);
+ // The owner's files and runs are never the sweep's.
+ expect(exists(ownerUpload.id)).toBe(true);
+ expect(runExists("owner-old-run")).toBe(true);
+ expect(exists(ownerOut.id)).toBe(true);
+ expect(fs.existsSync(stale)).toBe(false);
+ });
+
+ it("removes everything of a deleted account, and runs the cleanups registered for it", async () => {
+ const gone = auth.createAccount("[email protected]", "long enough").id;
+ const up = upload(gone, 0);
+ const out = runRow("gone-run", gone, 0);
+ const seen: string[] = [];
+ onAccountDeleted((id) => void seen.push(id));
+ const r = await purgeAccount(gone);
+ expect(r.runs).toBe(1);
+ expect(runExists("gone-run")).toBe(false);
+ expect(exists(up.id)).toBe(false);
+ expect(exists(out.id)).toBe(false);
+ expect(seen).toContain(gone);
+ // The sweep catches an account deleted without a purge.
+ const later = auth.createAccount("[email protected]", "long enough").id;
+ runRow("later-run", later, 0);
+ const laterUp = upload(later, 0);
+ auth.deleteAccount(later);
+ await sweepAccountFiles();
+ expect(runExists("later-run")).toBe(false);
+ expect(exists(laterUp.id)).toBe(false);
+ });
+
+ it("deletes an account's run for good when it deletes it", async () => {
+ const out = runRow("delete-me", a, 0);
+ const cookie = `${auth.SESSION_COOKIE}=${auth.createSession(a).value}`;
+ const r = await DELETE(new Request("http://localhost:3000/api/generations/delete-me", { method: "DELETE", headers: { cookie, host: "localhost:3000" } }), {
+ params: Promise.resolve({ id: "delete-me" }),
+ } as never);
+ expect(r.status).toBe(204);
+ expect(runExists("delete-me")).toBe(false);
+ expect(db().prepare("SELECT 1 FROM generation_trash WHERE generation_id = 'delete-me'").get()).toBeUndefined();
+ expect(exists(out.id)).toBe(false);
+ });
+});
diff --git a/tests/account-tenant.test.ts b/tests/account-tenant.test.ts
new file mode 100644
index 00000000..7804cb08
--- /dev/null
+++ b/tests/account-tenant.test.ts
@@ -0,0 +1,174 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-account-tenant-"));
+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;
+
+// Every plain fetch is recorded: nothing an account does may reach the install's ComfyUI.
+const realFetch = globalThis.fetch;
+const fetched: string[] = [];
+globalThis.fetch = (async (input: RequestInfo | URL) => {
+ fetched.push(String(input instanceof Request ? input.url : input));
+ return new Response("not stubbed", { status: 599 });
+}) as typeof fetch;
+
+const auth = await import("@/server/auth");
+const { runAsTenant } = await import("@/server/tenant");
+const { readRef, localHead, saveFile, RefError } = await import("@/server/storage");
+const { accountRun, createGenerations, mentionElements } = await import("@/server/generations");
+const { llmTextBackend } = await import("@/server/enhance");
+const { ensureLorasOnComfy, withoutUnreachableCivitai } = await import("@/server/loras");
+const { createElement } = await import("@/server/elements");
+const { db } = await import("@/server/db");
+
+let fake: FakeComfy;
+let a = "";
+let b = "";
+beforeAll(async () => {
+ fake = await startFakeComfy({ loras: [], delayMs: 60_000 });
+ 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 });
+ auth.setAccountGpu(b, { url: fake.url });
+});
+afterAll(async () => {
+ globalThis.fetch = realFetch;
+ globalThis.__fuobeTestGpuPort = undefined;
+ await fake.close();
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+
+const asA = <T,>(fn: () => T) => runAsTenant({ kind: "account", id: a }, fn);
+
+describe("inside an account's work, only its own files", () => {
+ it("reads its own upload and data: URIs; refuses the owner's files, asset ids and links", async () => {
+ const mine = saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload", accountId: a });
+ const owners = saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload" });
+ expect(mine.accountId).toBe(a);
+ expect(owners.accountId).toBeUndefined();
+ await asA(async () => {
+ expect((await readRef(mine.url)).data.equals(TINY_PNG)).toBe(true);
+ expect((await readRef(`data:text/plain;base64,${Buffer.from("hi").toString("base64")}`)).data.toString()).toBe("hi");
+ await expect(readRef(owners.url)).rejects.toThrow(/isn't yours/);
+ await expect(readRef(owners.id)).rejects.toBeInstanceOf(RefError);
+ await expect(readRef("https://example.com/a.png")).rejects.toThrow(/can't fetch links/);
+ await expect(readRef("/api/files/uploads/2020-01-01/nothing.png")).rejects.toThrow(/expired/);
+ });
+ // Another account can't read it either; the owner reads everything.
+ await runAsTenant({ kind: "account", id: b }, async () => expect(readRef(mine.url)).rejects.toThrow(/isn't yours/));
+ expect((await readRef(owners.url)).data.length).toBe(TINY_PNG.length);
+ });
+
+ it("can't even tell whether another's file exists (localHead)", () => {
+ const mine = saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload", accountId: a });
+ const owners = saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload" });
+ asA(() => {
+ expect(localHead(mine.url)).not.toBeNull();
+ expect(localHead(owners.url)).toBeNull();
+ expect(localHead(owners.id)).toBeNull();
+ });
+ expect(localHead(owners.url)).not.toBeNull();
+ runAsTenant({ kind: "guest" }, () => expect(localHead(owners.url)).toBeNull());
+ });
+
+ it("never uses the owner's elements, AI helper or LoRA folder", async () => {
+ const photo = saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload" });
+ createElement({ name: "Maya", kind: "character", references: [photo.url] });
+ expect(mentionElements().map((e) => e.name)).toContain("Maya");
+ asA(() => expect(mentionElements()).toEqual([]));
+ asA(() => expect(llmTextBackend()).toBeNull());
+ const civitai = [{ file: "look.safetensors", url: "https://civitai.com/api/download/models/1" }];
+ expect(withoutUnreachableCivitai(civitai, "fal").loras).toEqual([]);
+ asA(() => expect(withoutUnreachableCivitai(civitai, "fal").loras).toEqual(civitai));
+ await asA(async () => expect(ensureLorasOnComfy(civitai, [])).rejects.toThrow(/never downloaded/));
+ });
+});
+
+describe("every step an account's run starts is its own", () => {
+ const rowsSince = (t: number) =>
+ (db().prepare("SELECT id, request_json, depends_on FROM generations WHERE created_at >= ? ORDER BY created_at").all(t) as { id: string; request_json: string; depends_on: string | null }[]).map((r) => ({
+ id: r.id,
+ account: (JSON.parse(r.request_json) as { account?: string }).account,
+ waits: !!r.depends_on,
+ }));
+ const run = (fn: () => unknown) => {
+ const own = accountRun(a, "comfyui");
+ if (!("run" in own)) throw new Error(own.error);
+ return own.run(fn);
+ };
+
+ it("stamps a multi-shot film's shots and its join", () => {
+ const t = Date.now();
+ run(() => createGenerations({ feature: "video", modelId: "oss-wan22-14b", prompt: "a film", params: { shots: [{ prompt: "a woman walks" }, { prompt: "she turns" }] } } as never));
+ const rows = rowsSince(t);
+ expect(rows.length).toBeGreaterThanOrEqual(3);
+ expect(rows.some((r) => r.waits)).toBe(true);
+ for (const r of rows) expect(r.account, r.id).toBe(a);
+ });
+
+ it("stamps a relight effect's first step and its clip", () => {
+ const mine = saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload", accountId: a });
+ const t = Date.now() + 1;
+ while (Date.now() < t);
+ run(() => createGenerations({ feature: "video", modelId: "fuobe-dop", presetId: "effect-acid", prompt: "", inputs: { images: [mine.url] } } as never));
+ const rows = rowsSince(t);
+ expect(rows.length).toBe(2);
+ for (const r of rows) expect(r.account, r.id).toBe(a);
+ });
+
+ it("refuses a request stamped for another account, and a step that waits for someone else's run", () => {
+ expect(() => run(() => createGenerations({ feature: "video", modelId: "oss-wan22-14b", prompt: "x", account: b } as never))).toThrow(/another account/);
+ db()
+ .prepare(
+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES ('owner-dep', 'image', 'm', 'open', 'comfyui', 't2i', 'image', 'succeeded', '{}', '[]', 1, 1)",
+ )
+ .run();
+ expect(() => run(() => createGenerations({ feature: "video", modelId: "oss-wan22-14b", prompt: "x" } as never, { dependsOn: "owner-dep" }))).toThrow(/isn't yours/);
+ // A visitor's price check never starts a run.
+ expect(() => runAsTenant({ kind: "guest" }, () => createGenerations({ feature: "video", modelId: "oss-wan22-14b", prompt: "x" } as never))).toThrow(/free account/);
+ });
+
+ it("starts the runner outside the run that first needed it, so the owner's polls stay the owner's", async () => {
+ const { outsideRuns } = await import("@/server/generations");
+ const { ownGpu } = await import("@/server/providers/comfyui");
+ const { getSetting } = await import("@/server/settings");
+ const { tenant } = await import("@/server/tenant");
+ const saved = getSetting("demoMode");
+ await run(() => {
+ expect(getSetting("demoMode")).toBe("off");
+ expect(tenant()).toEqual({ kind: "account", id: a });
+ expect(ownGpu()?.url).toBe(fake.url);
+ outsideRuns(() => {
+ expect(tenant()).toBeUndefined();
+ expect(ownGpu()).toBeUndefined();
+ expect(getSetting("demoMode")).toBe(saved);
+ });
+ // A timer started outside the run sees no run.
+ return new Promise<void>((resolve) =>
+ outsideRuns(() =>
+ setTimeout(() => {
+ expect(tenant()).toBeUndefined();
+ expect(ownGpu()).toBeUndefined();
+ resolve();
+ }, 1),
+ ),
+ );
+ });
+ });
+
+ it("never reached the install's ComfyUI", () => {
+ // (The runner's own reachability check of the install's ComfyUI, /system_stats, is the owner's background work.)
+ expect(fetched.filter((u) => u.includes("owner-comfy.test") && !u.endsWith("/system_stats"))).toEqual([]);
+ });
+});
diff --git a/tests/account-tools.test.ts b/tests/account-tools.test.ts
new file mode 100644
index 00000000..0a11c3cc
--- /dev/null
+++ b/tests/account-tools.test.ts
@@ -0,0 +1,238 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { NextRequest } from "next/server";
+import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-account-tools-"));
+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;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+// Plain fetch is the install's own ComfyUI ("owner-comfy.test"): recorded, and answered like a ComfyUI whose job is done.
+const realFetch = globalThis.fetch;
+const fetched: string[] = [];
+globalThis.fetch = (async (input: RequestInfo | URL) => {
+ const url = new URL(String(input instanceof Request ? input.url : input));
+ fetched.push(url.toString());
+ if (url.host !== "owner-comfy.test:8188") return new Response("not stubbed", { status: 599 });
+ if (url.pathname === "/system_stats") return Response.json({ system: { comfyui_version: "owner", ram_total: 1 }, devices: [] });
+ if (url.pathname.startsWith("/history/")) {
+ const id = decodeURIComponent(url.pathname.slice("/history/".length));
+ return Response.json({ [id]: { status: { completed: true, status_str: "success" }, outputs: { "9": { images: [{ filename: "owner_00001_.png", subfolder: "", type: "output" }] } } } });
+ }
+ if (url.pathname === "/view") return new Response(new Uint8Array(TINY_PNG), { headers: { "content-type": "image/png" } });
+ if (url.pathname === "/queue") return Response.json({ queue_running: [], queue_pending: [] });
+ return Response.json({});
+}) as typeof fetch;
+
+const auth = await import("@/server/auth");
+const generationsRoute = await import("@/app/api/generations/route");
+const uploadsRoute = await import("@/app/api/uploads/route");
+const gpuRoute = await import("@/app/api/account/gpu/route");
+const { proxy } = await import("@/proxy");
+const { accountRun, createGenerations, getGeneration } = await import("@/server/generations");
+const { OWN_OUTPUT_LIMITS } = await import("@/server/providers/comfyui");
+const { libraryEntry } = await import("@/lib/catalog/loras");
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const { clearAccountLoras } = await import("@/server/account-loras");
+const { scratchDir } = await import("@/server/storage");
+
+let fake: FakeComfy;
+let a = "";
+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;
+ cookie = `${auth.SESSION_COOKIE}=${auth.createSession(a).value}`;
+});
+afterAll(async () => {
+ globalThis.fetch = realFetch;
+ globalThis.__fuobeTestGpuPort = undefined;
+ globalThis.__fuobeTestDiskFree = 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" });
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running') AND json_extract(request_json, '$.account') IS NOT NULL").run();
+});
+
+const headers = (extra: Record<string, string> = {}) => ({ cookie, host: "localhost:3000", ...extra });
+const json = (url: string, method: string, body: unknown) => {
+ const text = JSON.stringify(body);
+ return new Request(`http://localhost:3000${url}`, { method, headers: headers({ "content-type": "application/json", "content-length": String(Buffer.byteLength(text)) }), body: text });
+};
+
+async function uploadPng(): Promise<{ url: string; id: string }> {
+ const r = await uploadsRoute.POST(new Request("http://localhost:3000/api/uploads", { method: "POST", headers: headers({ "content-type": "image/png", "x-file-name": "me.png", "content-length": String(TINY_PNG.length) }), body: TINY_PNG }));
+ expect(r.status).toBe(201);
+ return r.json();
+}
+
+/** Tick the runner until the row is done (or the time is up). */
+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("an account runs the catalogue on its own ComfyUI", () => {
+ it("connects its ComfyUI, uploads a picture, and runs a camera motion end to end", async () => {
+ const put = await gpuRoute.PUT(json("/api/account/gpu", "PUT", { url: fake.url }));
+ expect(put.status).toBe(200);
+ const pic = await uploadPng();
+ fake.log.length = 0;
+ const r = await generationsRoute.POST(json("/api/generations", "POST", { feature: "video", modelId: "fuobe-dop", presetId: "motion-zoom-in", prompt: "", inputs: { images: [pic.url] } }));
+ expect(r.status).toBe(201);
+ const id = (await r.json()).items[0].id as string;
+ const g = await settle(id);
+ expect(g?.status, g?.error ?? "").toBe("succeeded");
+ // The picture went to its ComfyUI as it was uploaded, then the prompt; the result came back from /view.
+ const paths = fake.log.map((e) => e.path.split("?")[0]);
+ const up = fake.log.find((e) => e.path === "/upload/image");
+ expect(up?.upload?.equals(TINY_PNG)).toBe(true);
+ expect(paths.indexOf("/prompt")).toBeGreaterThan(paths.indexOf("/upload/image"));
+ expect(paths).toContain("/view");
+ expect(paths.filter((p) => !["/models/loras", "/system_stats", "/upload/image", "/prompt", "/history/" + g!.request.account].includes(p) && !p.startsWith("/history/") && p !== "/view" && p !== "/queue")).toEqual([]);
+ // The result is the account's own.
+ expect(g!.request.account).toBe(a);
+ const out = g!.outputs[0];
+ expect(out.url).toMatch(/^\/api\/files\/outputs\//);
+ expect((db().prepare("SELECT account_id FROM assets WHERE id = ?").get(out.assetId) as { account_id: string }).account_id).toBe(a);
+ const read = (c?: string) => proxy(new NextRequest(`http://localhost:3000${out.url}`, { headers: c ? { cookie: c } : {} }));
+ expect(read(cookie).headers.get("x-middleware-next")).toBe("1");
+ const other = auth.createAccount("[email protected]", "long enough");
+ expect(read(`${auth.SESSION_COOKIE}=${auth.createSession(other.id).value}`).status).toBe(403);
+ expect(proxy(new NextRequest(`http://localhost:3000/api/generations/${id}`, { headers: { cookie: `${auth.SESSION_COOKIE}=${auth.createSession(other.id).value}` } })).status).toBe(403);
+ // Nothing of the run reached the install's ComfyUI (its own reachability check, /system_stats, is the owner's).
+ expect(fetched.filter((u) => u.includes("owner-comfy.test") && !u.endsWith("/system_stats"))).toEqual([]);
+ });
+
+ it("runs an app that edits a picture", async () => {
+ fake.opts.output = "image";
+ const pic = await uploadPng();
+ const r = await generationsRoute.POST(json("/api/generations", "POST", { feature: "app", modelId: "oss-qwen-edit", presetId: "app-headshot-generator", prompt: "", inputs: { images: [pic.url] } }));
+ expect(r.status).toBe(201);
+ const g = await settle((await r.json()).items[0].id);
+ expect(g?.status, g?.error ?? "").toBe("succeeded");
+ expect(g!.outputs[0]).toMatchObject({ kind: "image", contentType: "image/png" });
+ });
+
+ it("names a LoRA its ComfyUI doesn't have, with where to get it, before anything is sent", async () => {
+ const pic = await uploadPng();
+ fake.log.length = 0;
+ const r = await generationsRoute.POST(json("/api/generations", "POST", { feature: "video", modelId: "fuobe-dop", presetId: "motion-dolly-in", prompt: "", inputs: { images: [pic.url] } }));
+ expect(r.status).toBe(409);
+ expect(r.headers.get("x-fuobe-gpu-setup")).toBeNull();
+ const body = await r.json();
+ const file = "motionpushin-v5-wan-i2v-14b-720p-400.safetensors";
+ expect(body.code).toBe("comfy_missing_model");
+ // A preset's own LoRA: the link the catalog names, and its Hugging Face page.
+ expect(body.fix.items).toEqual([
+ {
+ folder: "loras",
+ file,
+ url: "https://huggingface.co/lovis93/Motion-Lora-Camera-Push-In-Wan-14B-720p-I2V/resolve/main/motionpushin-v5-wan-i2v-14b-720p-400.safetensors",
+ page: "https://huggingface.co/lovis93/Motion-Lora-Camera-Push-In-Wan-14B-720p-I2V",
+ download: "direct",
+ },
+ ]);
+ expect(body.error).toMatch(/^Your ComfyUI doesn't have a LoRA file this needs\. Download it into ComfyUI\/models\/loras, keep the file name, then press Generate again\.\n• motionpushin/);
+ expect(fake.log.some((e) => e.path === "/upload/image" || e.path === "/prompt")).toBe(false);
+ // LoRAs from Fuobe's library: their link, page and how they download.
+ const orbit = await generationsRoute.POST(json("/api/generations", "POST", { feature: "video", modelId: "fuobe-dop", presetId: "motion-360-orbit", prompt: "", inputs: { images: [pic.url] } }));
+ expect(orbit.status).toBe(409);
+ const { fix, error } = await orbit.json();
+ expect(fix.items).toHaveLength(2);
+ for (const item of fix.items) {
+ const entry = libraryEntry({ file: item.file })!;
+ expect(item).toMatchObject({ folder: "loras", url: entry.url, page: entry.page, download: entry.download });
+ }
+ expect(error).toMatch(/^Your ComfyUI doesn't have 2 LoRA files this needs\. Download each one into ComfyUI\/models\/loras/);
+ });
+
+ it("checks again when a step is handed over, and fails it with the plain message", async () => {
+ const pic = await uploadPng();
+ fake.log.length = 0;
+ const own = accountRun(a, "comfyui");
+ if (!("run" in own)) throw new Error(own.error);
+ const [g] = own.run(() => createGenerations({ feature: "video", modelId: "fuobe-dop", presetId: "motion-dolly-in", prompt: "", inputs: { images: [pic.url] } } as never));
+ const done = await settle(g.id);
+ 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");
+ 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"];
+ clearAccountLoras(a);
+ const [again] = own.run(() => createGenerations({ feature: "video", modelId: "fuobe-dop", presetId: "motion-dolly-in", prompt: "", inputs: { images: [pic.url] } } as never));
+ expect((await settle(again.id))?.status).toBe("succeeded");
+ });
+});
+
+describe("an account's ComfyUI can't hold up the server", () => {
+ it("never holds up the owner's jobs while it drips", async () => {
+ fake.opts.drip = true;
+ const now = Date.now();
+ const insert = (id: string, account?: string) =>
+ db()
+ .prepare(
+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, external_id, external_meta_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'oss-qwen-edit', 'open', 'comfyui', 'edit', 'image', 'running', ?, ?, '{}', '[]', ?, ?)",
+ )
+ .run(id, JSON.stringify({ feature: "image", modelId: "oss-qwen-edit", ...(account && { account }) }), `${id}-job`, now, now);
+ insert("acct-drip", a);
+ insert("owner-job");
+ const t = Date.now();
+ let ticks = 0;
+ while (getGeneration("owner-job")?.status !== "succeeded" && ticks < 5) {
+ await globalThis.__fuobeRunner!.tick();
+ ticks++;
+ }
+ expect(getGeneration("owner-job")?.status).toBe("succeeded");
+ expect(Date.now() - t).toBeLessThan(5000);
+ expect(getGeneration("acct-drip")?.status).toBe("running");
+ });
+
+ it("fails a result that never ends at the cap, and leaves no file behind", async () => {
+ const was = OWN_OUTPUT_LIMITS.maxBytes;
+ OWN_OUTPUT_LIMITS.maxBytes = 2 * 2 ** 20;
+ fake.opts.huge = true;
+ try {
+ const pic = await uploadPng();
+ const r = await generationsRoute.POST(json("/api/generations", "POST", { feature: "video", modelId: "fuobe-dop", presetId: "motion-zoom-in", prompt: "", inputs: { images: [pic.url] } }));
+ const id = (await r.json()).items[0].id as string;
+ const g = await settle(id);
+ expect(g?.status).toBe("failed");
+ expect(g?.error).toMatch(/over 2 MB/);
+ expect(fs.readdirSync(scratchDir()).filter((f) => f.startsWith(`${id}-out-`))).toEqual([]);
+ } finally {
+ OWN_OUTPUT_LIMITS.maxBytes = was;
+ }
+ });
+
+ it("refuses a job id it can't use", async () => {
+ fake.opts.promptId = "../system_stats?";
+ const pic = await uploadPng();
+ const r = await generationsRoute.POST(json("/api/generations", "POST", { feature: "video", modelId: "fuobe-dop", presetId: "motion-zoom-in", prompt: "", inputs: { images: [pic.url] } }));
+ const g = await settle((await r.json()).items[0].id);
+ expect(g?.status).toBe("failed");
+ expect(g?.error).toBe("Your ComfyUI answered with a job id Fuobe can't use.");
+ expect(fake.log.some((e) => e.path.startsWith("/system_stats?"))).toBe(false);
+ });
+});
diff --git a/tests/account-uploads.test.ts b/tests/account-uploads.test.ts
new file mode 100644
index 00000000..03381d92
--- /dev/null
+++ b/tests/account-uploads.test.ts
@@ -0,0 +1,196 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { NextRequest } from "next/server";
+import { TINY_PNG } from "./helpers/fake-comfy-runner";
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-account-uploads-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_ALLOWED_ORIGINS;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const auth = await import("@/server/auth");
+const { POST } = await import("@/app/api/uploads/route");
+const { proxy, config } = await import("@/proxy");
+const { GUEST_HEADER, CONNECT_GPU_HEADER } = await import("@/lib/guest-access");
+const { db } = await import("@/server/db");
+const { hit, resetRates } = await import("@/server/rate");
+afterAll(() => {
+ globalThis.__fuobeTestDiskFree = undefined;
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+
+let a = "";
+let b = "";
+let noGpu = "";
+let cookieA = "";
+let cookieB = "";
+let cookieNoGpu = "";
+let owner = "";
+beforeAll(() => {
+ auth.setPassword("install password");
+ a = auth.createAccount("[email protected]", "long enough").id;
+ b = auth.createAccount("[email protected]", "long enough").id;
+ noGpu = auth.createAccount("[email protected]", "long enough").id;
+ auth.setAccountGpu(a, { url: "https://gpu-a.example" });
+ auth.setAccountGpu(b, { url: "https://gpu-b.example" });
+ cookieA = auth.createSession(a).value;
+ cookieB = auth.createSession(b).value;
+ cookieNoGpu = auth.createSession(noGpu).value;
+ owner = auth.createSession().value;
+});
+beforeEach(() => resetRates());
+
+/** A body stream that fails if anything reads it: the route must answer before. */
+const unread = () =>
+ new ReadableStream<Uint8Array>({
+ pull() {
+ throw new Error("the body was read");
+ },
+ });
+
+function upload(body: BodyInit | null, o: { cookie?: string; type?: string; name?: string; length?: number | null; headers?: Record<string, string> } = {}) {
+ const headers: Record<string, string> = { host: "localhost:3000", ...o.headers };
+ if (o.cookie) headers.cookie = `${auth.SESSION_COOKIE}=${o.cookie}`;
+ if (o.type) headers["content-type"] = o.type;
+ if (o.name) headers["x-file-name"] = encodeURIComponent(o.name);
+ const length = o.length === undefined ? (body instanceof Uint8Array ? body.length : undefined) : o.length;
+ if (length !== null && length !== undefined) headers["content-length"] = String(length);
+ return POST(new Request("http://localhost:3000/api/uploads", { method: "POST", headers, body, duplex: "half" } as RequestInit));
+}
+
+describe("POST /api/uploads checks who is asking itself (the proxy doesn't run on it)", () => {
+ it("is left out of the proxy's matcher, and only that path", () => {
+ const re = new RegExp(`^${config.matcher[0]}$`);
+ expect(re.test("/api/uploads")).toBe(false);
+ expect(re.test("/api/uploadsx")).toBe(true);
+ expect(re.test("/api/uploads/x")).toBe(true);
+ expect(re.test("/api/files/x")).toBe(true);
+ expect(re.test("/motions")).toBe(true);
+ });
+
+ it("asks a guest to sign up", async () => {
+ const r = await upload(TINY_PNG, { type: "image/png" });
+ expect(r.status).toBe(401);
+ expect(r.headers.get(GUEST_HEADER)).toBe("1");
+ expect((await r.json()).error).toMatch(/free account/);
+ });
+
+ it("refuses another website", async () => {
+ const r = await upload(TINY_PNG, { cookie: cookieA, type: "image/png", headers: { origin: "https://evil.example" } });
+ expect(r.status).toBe(403);
+ });
+
+ it("asks an account to connect its GPU first", async () => {
+ const r = await upload(TINY_PNG, { cookie: cookieNoGpu, type: "image/png" });
+ expect(r.status).toBe(403);
+ expect(r.headers.get(CONNECT_GPU_HEADER)).toBe("1");
+ expect((await r.json()).code).toBe("connect-gpu");
+ });
+});
+
+describe("an account's upload", () => {
+ it("stores a picture as its own, typed by its bytes, whatever name it was given", async () => {
+ const r = await upload(TINY_PNG, { cookie: cookieA, type: "image/png", name: "../../x.html" });
+ expect(r.status).toBe(201);
+ const asset = await r.json();
+ expect(asset).toMatchObject({ kind: "image", contentType: "image/png", accountId: a, source: "upload", name: "x.html" });
+ expect(asset.relPath).toMatch(/\.png$/);
+ const row = db().prepare("SELECT account_id FROM assets WHERE id = ?").get(asset.id) as { account_id: string };
+ expect(row.account_id).toBe(a);
+ expect(fs.readFileSync(path.join(dir, "files", asset.relPath)).equals(TINY_PNG)).toBe(true);
+ });
+
+ it("refuses a page that says it is a picture", async () => {
+ const r = await upload(Buffer.from("<!doctype html><script>alert(1)</script>".padEnd(200)), { cookie: cookieA, type: "image/png", name: "x.png" });
+ expect(r.status).toBe(415);
+ expect((await r.json()).error).toMatch(/PNG, JPEG or WebP/);
+ });
+
+ it("refuses an oversized file before reading a byte", async () => {
+ const pic = await upload(unread(), { cookie: cookieA, type: "image/png", name: "big.png", length: 26 * 2 ** 20 });
+ expect(pic.status).toBe(413);
+ expect((await pic.json()).error).toMatch(/over 25 MB/);
+ const clip = await upload(unread(), { cookie: cookieA, type: "video/mp4", name: "big.mp4", length: 96 * 2 ** 20 });
+ expect(clip.status).toBe(413);
+ expect((await clip.json()).error).toMatch(/over 95 MB/);
+ const form = await upload(unread(), { cookie: cookieA, type: "multipart/form-data; boundary=x", length: 27 * 2 ** 20 });
+ expect(form.status).toBe(413);
+ expect((await form.json()).error).toMatch(/Reload the page/);
+ });
+
+ it("needs the file's size", async () => {
+ const r = await upload(unread(), { cookie: cookieA, type: "image/png", length: null });
+ expect(r.status).toBe(411);
+ });
+
+ it("stops at 1 GB of uploads", async () => {
+ db()
+ .prepare("INSERT INTO assets (id, kind, rel_path, content_type, size, source, created_at, account_id) VALUES ('full', 'video', 'uploads/x/full.mp4', 'video/mp4', ?, 'upload', ?, ?)")
+ .run(2 ** 30, Date.now(), a);
+ try {
+ const r = await upload(TINY_PNG, { cookie: cookieA, type: "image/png" });
+ expect(r.status).toBe(413);
+ expect((await r.json()).error).toMatch(/reached 1 GB/);
+ } finally {
+ db().prepare("DELETE FROM assets WHERE id = 'full'").run();
+ }
+ });
+
+ it("allows 60 an hour", async () => {
+ for (let i = 0; i < 60; i++) hit(`up:h:${a}`, 60, 60 * 60_000);
+ const r = await upload(TINY_PNG, { cookie: cookieA, type: "image/png" });
+ expect(r.status).toBe(429);
+ expect(Number(r.headers.get("retry-after"))).toBeGreaterThan(0);
+ });
+
+ it("takes a small multipart form from an older page", async () => {
+ const form = new FormData();
+ form.append("file", new File([TINY_PNG], "old.png", { type: "image/png" }));
+ const req = new Request("http://localhost:3000/api/uploads", { method: "POST", body: form });
+ const length = (await req.clone().arrayBuffer()).byteLength;
+ const r = await upload(form, { cookie: cookieA, type: req.headers.get("content-type")!, length });
+ expect(r.status).toBe(201);
+ expect((await r.json()).accountId).toBe(a);
+ });
+
+ it("is readable by its account only", async () => {
+ const asset = await (await upload(TINY_PNG, { cookie: cookieA, type: "image/png" })).json();
+ const get = (cookie?: string) => proxy(new NextRequest(`http://localhost:3000${asset.url}`, { headers: cookie ? { cookie: `${auth.SESSION_COOKIE}=${cookie}` } : {} }));
+ expect(get(cookieA).headers.get("x-middleware-next")).toBe("1");
+ expect(get(cookieB).status).toBe(403);
+ expect(get().status).toBe(401);
+ expect(get(owner).headers.get("x-middleware-next")).toBe("1");
+ });
+});
+
+describe("the owner's upload", () => {
+ it("still takes a form and a raw file", async () => {
+ const form = new FormData();
+ form.append("file", new File([TINY_PNG], "mine.png", { type: "image/png" }));
+ const viaForm = await POST(new Request("http://localhost:3000/api/uploads", { method: "POST", body: form, headers: { cookie: `${auth.SESSION_COOKIE}=${owner}`, host: "localhost:3000" } }));
+ expect(viaForm.status).toBe(201);
+ expect((await viaForm.json()).accountId).toBeUndefined();
+ const raw = await upload(TINY_PNG, { cookie: owner, type: "image/png", name: "raw.png" });
+ expect(raw.status).toBe(201);
+ expect(await raw.json()).toMatchObject({ kind: "image", name: "raw.png", source: "upload" });
+ const gif = await upload(Buffer.from("GIF89a....."), { cookie: owner, type: "image/gif", name: "a.gif" });
+ expect(gif.status).toBe(201);
+ });
+
+ it("without a password, refuses a host this install doesn't answer to", async () => {
+ auth.setPassword(null);
+ try {
+ const r = await upload(TINY_PNG, { type: "image/png", headers: { host: "rebound.example" } });
+ expect(r.status).toBe(403);
+ expect((await r.json()).error).toMatch(/isn't a local address/);
+ } finally {
+ auth.setPassword("install password");
+ }
+ });
+});
diff --git a/tests/files-route.test.ts b/tests/files-route.test.ts
new file mode 100644
index 00000000..944f7f4d
--- /dev/null
+++ b/tests/files-route.test.ts
@@ -0,0 +1,32 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, describe, expect, it } from "vitest";
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-files-route-"));
+process.env.FUOBE_DATA_DIR = dir;
+const { GET } = await import("@/app/api/files/[...path]/route");
+afterAll(() => {
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+
+const get = (parts: string[]) => GET(new Request(`http://localhost:3000/api/files/${parts.join("/")}`), { params: Promise.resolve({ path: parts }) } as never);
+
+describe("/api/files decodes a path once", () => {
+ it("never turns %2e into a step out of the folder", async () => {
+ // A secret beside the files folder, and a file inside it.
+ fs.mkdirSync(path.join(dir, "files", "uploads"), { recursive: true });
+ fs.writeFileSync(path.join(dir, "secret.txt"), "secret");
+ fs.writeFileSync(path.join(dir, "files", "uploads", "a.txt"), "hello");
+ // Next hands the route each segment decoded once: "%252e%252e" arrives as "%2e%2e", which must stay a name.
+ const r = await get(["uploads", "%2e%2e", "%2e%2e", "secret.txt"]);
+ expect(r.status).toBe(404);
+ expect(await r.text()).not.toContain("secret");
+ expect((await get(["..", "secret.txt"])).status).toBe(400);
+ const ok = await get(["uploads", "a.txt"]);
+ expect(ok.status).toBe(200);
+ expect(await ok.text()).toBe("hello");
+ });
+});
diff --git a/tests/glb-finish-safety.test.ts b/tests/glb-finish-safety.test.ts
index a645c623..82bd2c89 100644
--- a/tests/glb-finish-safety.test.ts
+++ b/tests/glb-finish-safety.test.ts
@@ -6,9 +6,13 @@ import { afterAll, describe, expect, it } from "vitest";
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-glb-safety-"));
process.env.FUOBE_DATA_DIR = path.join(dir, "data");
+process.env.FUOBE_TEST_SECRET = "do-not-pass-this-on";
+const { ACCOUNT_TURNTABLE, finishModel, pendingTurntable, scriptEnv } = await import("@/server/model3d-finish");
+const { saveFile } = await import("@/server/storage");
const { createGenerations } = await import("@/server/generations");
const { OWN_GPU_TOOL_MESSAGE } = await import("@/lib/guest-access");
afterAll(() => {
+ delete process.env.FUOBE_TEST_SECRET;
try {
fs.rmSync(dir, { recursive: true, force: true });
} catch {}
@@ -85,6 +89,29 @@ describe("the 3D finish reads only the model it was given", () => {
expect(r.status, r.stderr).toBe(0);
expect(fs.existsSync(out)).toBe(true);
});
+
+ it("runs the scripts with a short environment, never the server's secrets", () => {
+ const env = scriptEnv();
+ expect(env.FUOBE_TEST_SECRET).toBeUndefined();
+ expect(Object.values(env)).not.toContain("do-not-pass-this-on");
+ expect(env.FUOBE_PARENT_PIPE).toBe("1");
+ expect(Object.keys(env).every((k) => /^(PATH|Path|SYSTEMROOT|SystemRoot|TEMP|TMP|TMPDIR|HOME|USERPROFILE|LOCALAPPDATA|APPDATA|LANG|FFMPEG_PATH|CHROMIUM_PATH|FUOBE_CHROMIUM|PLAYWRIGHT_BROWSERS_PATH|FUOBE_PARENT_PIPE)$/.test(k))).toBe(true);
+ });
+
+ it("gives an account's model its web GLB but no server turntable", async () => {
+ const asset = saveFile({ data: glb(), contentType: "model/gltf-binary", source: "generation", accountId: "acct-3d" });
+ const outputs = [{ url: asset.url, kind: "model3d" as const, contentType: "model/gltf-binary", assetId: asset.id }];
+ const done = await finishModel("gen-3d", outputs, { op: "image-to-3d", provider: "comfyui", account: "acct-3d" });
+ const finish = done[0].meta?.finish as { turntable?: string; webAsset?: string; error?: string };
+ expect(finish.error).toBeUndefined();
+ expect(finish.webAsset).toBeTruthy();
+ expect(finish.turntable).toBe(ACCOUNT_TURNTABLE);
+ expect(pendingTurntable(done)).toBe(-1);
+ // The owner's model still queues one.
+ const own = saveFile({ data: glb(), contentType: "model/gltf-binary", source: "generation" });
+ const mine = await finishModel("gen-3d-owner", [{ url: own.url, kind: "model3d", contentType: "model/gltf-binary", assetId: own.id }], { op: "image-to-3d", provider: "comfyui" });
+ expect(pendingTurntable(mine)).toBe(0);
+ }, 60_000);
});
describe("accounts don't run 3D models yet", () => {
diff --git a/tests/helpers/fake-comfy-runner.ts b/tests/helpers/fake-comfy-runner.ts
new file mode 100644
index 00000000..065554af
--- /dev/null
+++ b/tests/helpers/fake-comfy-runner.ts
@@ -0,0 +1,184 @@
+/**
+ * A ComfyUI stand-in that runs jobs (an account's "Your GPU" in tests and the local smoke): it takes uploads and
+ * prompts, answers the history with a finished output after a delay, and serves the output file. Every request is
+ * logged, so a test can see what reached it (and that nothing else did).
+ *
+ * node tests/helpers/fake-comfy-runner.ts --port 3341 [--loras none|a.safetensors,b.safetensors]
+ *
+ * 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").
+ * This file runs under plain Node too: only erasable TypeScript.
+ */
+import http from "node:http";
+import { randomUUID } from "node:crypto";
+import { pathToFileURL } from "node:url";
+
+export interface FakeComfyOptions {
+ loras?: string[];
+ delayMs?: number;
+ drip?: boolean;
+ huge?: boolean;
+ promptId?: string;
+ missing?: string;
+ output?: "video" | "image";
+}
+
+export interface FakeLogEntry {
+ method: string;
+ path: string;
+ at: number;
+ /** /upload/image: the bytes of the file sent. */
+ upload?: Buffer;
+ /** /prompt: the graph sent. */
+ prompt?: Record<string, unknown>;
+}
+
+export interface FakeComfy {
+ port: number;
+ url: string;
+ log: FakeLogEntry[];
+ opts: FakeComfyOptions;
+ close: () => Promise<void>;
+}
+
+/** A tiny but real PNG (2 × 2, RGBA). */
+export const TINY_PNG = Buffer.from(
+ "89504e470d0a1a0a0000000d494844520000000200000002080600000072b60d240000001149444154789c63381150f11f8419600c005a940a3db632c1b20000000049454e44ae426082",
+ "hex",
+);
+
+/** The start of an MP4 (an ftyp box), enough for the studio to store it as one. */
+export const TINY_MP4 = Buffer.concat([Buffer.from("000000186674797069736f6d0000020069736f6d69736f32", "hex"), Buffer.alloc(64)]);
+
+/** The bytes of the "image" part of a multipart body. */
+function uploadedBytes(body: Buffer, contentType: string): Buffer | undefined {
+ const boundary = /boundary=(?:"([^"]+)"|([^;]+))/.exec(contentType);
+ if (!boundary) return undefined;
+ const marker = Buffer.from(`--${boundary[1] ?? boundary[2]}`);
+ let at = body.indexOf(marker);
+ while (at >= 0) {
+ const next = body.indexOf(marker, at + marker.length);
+ if (next < 0) break;
+ const part = body.subarray(at + marker.length, next);
+ const headEnd = part.indexOf("\r\n\r\n");
+ if (headEnd >= 0 && /name="image"/.test(part.subarray(0, headEnd).toString("latin1"))) {
+ return part.subarray(headEnd + 4, part.length - 2);
+ }
+ at = next;
+ }
+ return undefined;
+}
+
+export function startFakeComfy(opts: FakeComfyOptions = {}, port = 0): Promise<FakeComfy> {
+ const log: FakeLogEntry[] = [];
+ const jobs = new Map<string, number>();
+ const server = http.createServer((req, res) => {
+ const chunks: Buffer[] = [];
+ req.on("data", (c: Buffer) => chunks.push(c));
+ req.on("end", () => {
+ const body = Buffer.concat(chunks);
+ const url = new URL(req.url ?? "/", "http://fake");
+ const entry: FakeLogEntry = { method: req.method ?? "GET", path: url.pathname + url.search, at: Date.now() };
+ log.push(entry);
+ const json = (status: number, value: unknown) => {
+ res.writeHead(status, { "content-type": "application/json" });
+ res.end(JSON.stringify(value));
+ };
+ const p = url.pathname;
+ if (p === "/system_stats") return json(200, { system: { comfyui_version: "0.3.fake", ram_total: 64 * 2 ** 30 }, devices: [{ name: "Fake GPU", vram_total: 24 * 2 ** 30 }] });
+ if (p === "/models/loras") return json(200, opts.loras ?? []);
+ if (p === "/object_info") return json(200, {});
+ if (p === "/upload/image" && req.method === "POST") {
+ entry.upload = uploadedBytes(body, req.headers["content-type"] ?? "");
+ return json(200, { name: `fake_${log.length}.bin`, subfolder: "", type: "input" });
+ }
+ if (p === "/prompt" && req.method === "POST") {
+ try {
+ entry.prompt = (JSON.parse(body.toString("utf8")) as { prompt?: Record<string, unknown> }).prompt;
+ } catch {}
+ if (opts.missing) {
+ return json(400, {
+ error: { type: "prompt_outputs_failed_validation", message: "Prompt outputs failed validation" },
+ node_errors: { "1": { errors: [{ type: "value_not_in_list", message: "Value not in list", details: `lora_name: '${opts.missing}' not in []` }], class_type: "LoraLoaderModelOnly" } },
+ });
+ }
+ const id = opts.promptId ?? randomUUID();
+ jobs.set(id, Date.now());
+ return json(200, { prompt_id: id, number: jobs.size, node_errors: {} });
+ }
+ if (p.startsWith("/history/")) {
+ const id = decodeURIComponent(p.slice("/history/".length));
+ if (opts.drip) {
+ res.writeHead(200, { "content-type": "application/json" });
+ const t = setInterval(() => res.write(" "), 2000);
+ res.on("close", () => clearInterval(t));
+ return;
+ }
+ const started = jobs.get(id);
+ if (started === undefined || Date.now() - started < (opts.delayMs ?? 0)) return json(200, {});
+ 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] } } } });
+ }
+ if (p === "/queue") {
+ if (req.method === "POST") return json(200, {});
+ const running = [...jobs.keys()].map((id, i) => [i, id, {}, {}, []]);
+ return json(200, { queue_running: running, queue_pending: [] });
+ }
+ if (p === "/interrupt") return json(200, {});
+ if (p === "/view") {
+ if (opts.huge) {
+ res.writeHead(200, { "content-type": "video/mp4" });
+ const block = Buffer.alloc(64 * 1024, 7);
+ const pump = () => {
+ while (res.write(block)) {
+ /* fill until the socket pushes back */
+ }
+ };
+ res.on("drain", pump);
+ res.on("close", () => res.off("drain", pump));
+ pump();
+ return;
+ }
+ const png = (url.searchParams.get("filename") ?? "").endsWith(".png");
+ res.writeHead(200, { "content-type": png ? "image/png" : "video/mp4" });
+ return res.end(png ? TINY_PNG : TINY_MP4);
+ }
+ json(404, { error: "not found" });
+ });
+ });
+ return new Promise((resolve) => {
+ server.listen(port, "127.0.0.1", () => {
+ const addr = server.address();
+ const at = typeof addr === "object" && addr ? addr.port : port;
+ resolve({
+ port: at,
+ url: `http://127.0.0.1:${at}`,
+ log,
+ opts,
+ close: () =>
+ new Promise<void>((done) => {
+ server.closeAllConnections?.();
+ server.close(() => done());
+ }),
+ });
+ });
+ });
+}
+
+// Run on its own: node tests/helpers/fake-comfy-runner.ts --port 3341 [--loras none|a,b]
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ const arg = (name: string) => {
+ const i = process.argv.indexOf(`--${name}`);
+ return i > 0 ? process.argv[i + 1] : undefined;
+ };
+ const port = Number(arg("port") ?? 3341);
+ const loras = arg("loras");
+ const fake = await startFakeComfy({ loras: !loras || loras === "none" ? [] : loras.split(","), delayMs: Number(arg("delay") ?? 1500), output: arg("output") === "image" ? "image" : "video" }, port);
+ console.log(`fake ComfyUI on ${fake.url}`);
+ setInterval(() => {
+ const last = fake.log.splice(0);
+ for (const e of last) console.log(`${new Date(e.at).toISOString()} ${e.method} ${e.path}${e.upload ? ` (${e.upload.length} bytes)` : ""}`);
+ }, 500);
+}
diff --git a/tests/png-limits.test.ts b/tests/png-limits.test.ts
new file mode 100644
index 00000000..baf50494
--- /dev/null
+++ b/tests/png-limits.test.ts
@@ -0,0 +1,50 @@
+import zlib from "node:zlib";
+import { describe, expect, it } from "vitest";
+
+const { decodePng, encodePng } = await import("@/server/png");
+
+function crc32(b: Buffer): number {
+ let crc = 0xffffffff;
+ for (const x of b) {
+ crc ^= x;
+ for (let k = 0; k < 8; k++) crc = crc & 1 ? 0xedb88320 ^ (crc >>> 1) : crc >>> 1;
+ }
+ return (crc ^ 0xffffffff) >>> 0;
+}
+
+function chunk(type: string, data: Buffer): Buffer {
+ const len = Buffer.alloc(4);
+ len.writeUInt32BE(data.length);
+ const td = Buffer.concat([Buffer.from(type), data]);
+ const crc = Buffer.alloc(4);
+ crc.writeUInt32BE(crc32(td));
+ return Buffer.concat([len, td, crc]);
+}
+
+function png(width: number, height: number, idat: Buffer): Buffer {
+ const ihdr = Buffer.alloc(13);
+ ihdr.writeUInt32BE(width, 0);
+ ihdr.writeUInt32BE(height, 4);
+ ihdr[8] = 8;
+ ihdr[9] = 6;
+ return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk("IHDR", ihdr), chunk("IDAT", idat), chunk("IEND", Buffer.alloc(0))]);
+}
+
+describe("decodePng has limits", () => {
+ it("refuses a picture over 40 megapixels before inflating anything", () => {
+ const t = Date.now();
+ expect(() => decodePng(png(100_000, 100_000, zlib.deflateSync(Buffer.alloc(10))))).toThrow(/megapixels/);
+ expect(Date.now() - t).toBeLessThan(500);
+ });
+
+ it("stops inflating at what the picture needs (a deflate bomb)", () => {
+ // 4 × 4 RGBA needs 4 × (16 + 1) = 68 bytes; this inflates to 64 MB.
+ const bomb = zlib.deflateSync(Buffer.alloc(64 * 2 ** 20));
+ expect(() => decodePng(png(4, 4, bomb))).toThrow();
+ });
+
+ it("still decodes a normal picture", () => {
+ const img = { width: 3, height: 2, data: Buffer.alloc(3 * 2 * 4, 200) };
+ expect(decodePng(encodePng(img))).toMatchObject({ width: 3, height: 2 });
+ });
+});
diff --git a/tests/public-signup.test.ts b/tests/public-signup.test.ts
index 18d9d7b4..dfcde2f2 100644
--- a/tests/public-signup.test.ts
+++ b/tests/public-signup.test.ts
@@ -253,7 +253,8 @@ describe("accounts never see or change the owner's library", () => {
records: ["/api/generations/g1", "/api/generations/zip?ids=g1"],
changes: [["PATCH", "/api/generations/g1"], ["DELETE", "/api/generations/g1"], ["POST", "/api/generations/bulk"], ["DELETE", "/api/generations/trash"], ["POST", "/api/generations/g1/cancel"]],
},
- files: { lists: ["/api/assets"], records: ["/api/files/outputs/a.png", "/api/assets/a1", "/api/uploads"], changes: [["POST", "/api/uploads"], ["DELETE", "/api/assets/a1"]] },
+ // (POST /api/uploads is the account's own: the route checks it, tests/account-uploads.test.ts.)
+ files: { lists: ["/api/assets"], records: ["/api/files/outputs/a.png", "/api/assets/a1", "/api/uploads"], changes: [["DELETE", "/api/assets/a1"]] },
folders: { lists: ["/api/folders"], records: ["/api/folders/f1", "/api/folders/f1/zip"], changes: [["POST", "/api/folders"], ["PATCH", "/api/folders/f1"], ["DELETE", "/api/folders/f1"]] },
shares: { lists: ["/api/shares"], records: ["/api/shares/s1"], changes: [["POST", "/api/shares"], ["PATCH", "/api/shares/s1"], ["DELETE", "/api/shares/s1"]] },
layers: { lists: ["/api/layers"], records: ["/api/layers/l1"], changes: [["POST", "/api/layers"], ["PATCH", "/api/layers/l1"], ["DELETE", "/api/layers/l1"], ["POST", "/api/layers/l1/versions"]] },
diff --git a/tests/remote-fetch-limits.test.ts b/tests/remote-fetch-limits.test.ts
new file mode 100644
index 00000000..2c054e3e
--- /dev/null
+++ b/tests/remote-fetch-limits.test.ts
@@ -0,0 +1,123 @@
+import http from "node:http";
+import os from "node:os";
+import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
+
+process.env.FUOBE_SELF_ADDRESSES = "93.184.216.99";
+delete process.env.FUOBE_ALLOW_PRIVATE_URLS;
+const { blockedForAccounts, fetchPublic, isPrivateAddress, loopbackGpuPort } = await import("@/server/remote-fetch");
+
+// A server on this machine: what an account's ComfyUI could answer.
+let port = 0;
+const server = http.createServer((req, res) => {
+ if (req.url === "/big") {
+ res.writeHead(200, { "content-type": "application/octet-stream" });
+ const block = Buffer.alloc(256 * 1024, 1);
+ let sent = 0;
+ const pump = () => {
+ while (sent < 4 * 2 ** 20 && res.write(block)) sent += block.length;
+ if (sent >= 4 * 2 ** 20) res.end();
+ };
+ res.on("drain", pump);
+ pump();
+ return;
+ }
+ if (req.url === "/declared") {
+ res.writeHead(200, { "content-length": String(10 * 2 ** 20) });
+ res.write("x");
+ return;
+ }
+ if (req.url === "/drip") {
+ res.writeHead(200, { "content-type": "application/json" });
+ const t = setInterval(() => res.write(" "), 200);
+ res.on("close", () => clearInterval(t));
+ return;
+ }
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end('{"ok":true}');
+});
+
+beforeAll(async () => {
+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", () => r()));
+ port = (server.address() as { port: number }).port;
+ globalThis.__fuobeTestGpuPort = port;
+});
+afterAll(async () => {
+ globalThis.__fuobeTestGpuPort = undefined;
+ server.closeAllConnections();
+ await new Promise<void>((r) => server.close(() => r()));
+});
+afterEach(() => {
+ delete process.env.FUOBE_ALLOW_PRIVATE_URLS;
+});
+
+const base = () => `http://127.0.0.1:${port}`;
+
+describe("fetchPublic: an account's ComfyUI can't freeze or fill the server", () => {
+ it("answers within the caps", async () => {
+ const res = await fetchPublic(`${base()}/ok`);
+ expect(await res.json()).toEqual({ ok: true });
+ });
+
+ it("fails an answer over maxBytes, read as it streams or declared up front", async () => {
+ const res = await fetchPublic(`${base()}/big`, {}, { maxBytes: 2 ** 20 });
+ await expect(res.arrayBuffer()).rejects.toThrow(/over/);
+ await expect(fetchPublic(`${base()}/declared`, {}, { maxBytes: 2 ** 20 })).rejects.toThrow(/over 1 MB/);
+ });
+
+ it("fails an answer that drips past the deadline", async () => {
+ const t = Date.now();
+ const res = await fetchPublic(`${base()}/drip`, {}, { deadlineMs: 1000 });
+ await expect(res.text()).rejects.toThrow(/took over 1 s/);
+ expect(Date.now() - t).toBeLessThan(5000);
+ });
+});
+
+describe("blockedForAccounts: never this machine", () => {
+ it("refuses this machine's own addresses", () => {
+ const own = Object.values(os.networkInterfaces())
+ .flatMap((l) => l ?? [])
+ .map((a) => a.address);
+ expect(own.length).toBeGreaterThan(0);
+ for (const ip of own) expect(blockedForAccounts(ip), ip).toBe(true);
+ expect(blockedForAccounts("93.184.216.99")).toBe(true); // FUOBE_SELF_ADDRESSES
+ expect(blockedForAccounts("93.184.216.34")).toBe(false);
+ });
+
+ it("refuses IPv6 forms that carry an IPv4 address", () => {
+ for (const ip of ["::ffff:127.0.0.1", "::127.0.0.1", "64:ff9b::7f00:1", "64:ff9b:1::a00:1", "2002:7f00:1::1", "2001:0:4136:e378:8000:63bf:80ff:fffe", "::ffff:93.184.216.99"]) {
+ expect(blockedForAccounts(ip), ip).toBe(true);
+ }
+ expect(isPrivateAddress("::127.0.0.1")).toBe(true);
+ expect(blockedForAccounts("2606:4700::6810:84e5")).toBe(false);
+ });
+
+ it("refuses loopback even with FUOBE_ALLOW_PRIVATE_URLS=1, which still allows the LAN", async () => {
+ process.env.FUOBE_ALLOW_PRIVATE_URLS = "1";
+ expect(blockedForAccounts("127.0.0.1")).toBe(true);
+ expect(blockedForAccounts("::1")).toBe(true);
+ expect(blockedForAccounts("192.168.1.5")).toBe(false);
+ await expect(fetchPublic("http://127.0.0.1:9/x")).rejects.toThrow(/won't fetch/);
+ });
+});
+
+describe("the stand-in ComfyUI on this machine (tests and next dev only)", () => {
+ it("is reached at the one port the test names, never another", async () => {
+ expect(loopbackGpuPort()).toBe(port);
+ await expect(fetchPublic(`http://127.0.0.1:${port + 1}/x`)).rejects.toThrow(/won't fetch/);
+ await expect(fetchPublic(`http://localhost:${port}/ok`).then((r) => r.json())).resolves.toEqual({ ok: true });
+ });
+
+ it("is never the real ComfyUI's port, and is off in production", () => {
+ globalThis.__fuobeTestGpuPort = 8188;
+ expect(loopbackGpuPort()).toBeNull();
+ globalThis.__fuobeTestGpuPort = port;
+ const env = process.env as Record<string, string | undefined>;
+ const was = env.NODE_ENV;
+ env.NODE_ENV = "production";
+ try {
+ expect(loopbackGpuPort()).toBeNull();
+ } finally {
+ env.NODE_ENV = was;
+ }
+ });
+});
diff --git a/tests/sniff.test.ts b/tests/sniff.test.ts
new file mode 100644
index 00000000..9d0eb29d
--- /dev/null
+++ b/tests/sniff.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from "vitest";
+import { sniffMedia } from "@/lib/sniff";
+
+const pad = (b: Buffer | string) => Buffer.concat([typeof b === "string" ? Buffer.from(b, "latin1") : b, Buffer.alloc(64)]);
+const riff = (form: string) => pad(Buffer.concat([Buffer.from("RIFF"), Buffer.from([0x24, 0, 0, 0]), Buffer.from(form, "latin1")]));
+const ftyp = (brand: string) => pad(Buffer.concat([Buffer.from([0, 0, 0, 0x18]), Buffer.from("ftyp" + brand, "latin1")]));
+// EBML header with a DocType element (0x42 0x82, size 0x84 = 4 bytes, or 0x88 = 8).
+const ebml = (doc: string) => pad(Buffer.concat([Buffer.from([0x1a, 0x45, 0xdf, 0xa3, 0x9f, 0x42, 0x86, 0x81, 0x01, 0x42, 0x82, 0x80 | doc.length]), Buffer.from(doc, "latin1")]));
+
+describe("sniffMedia: the type of a file is what its bytes say", () => {
+ it("knows pictures", () => {
+ expect(sniffMedia(pad(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])))).toEqual({ contentType: "image/png", kind: "image" });
+ expect(sniffMedia(pad(Buffer.from([0xff, 0xd8, 0xff, 0xe0])))).toEqual({ contentType: "image/jpeg", kind: "image" });
+ expect(sniffMedia(riff("WEBPVP8 "))).toEqual({ contentType: "image/webp", kind: "image" });
+ });
+
+ it("knows clips", () => {
+ expect(sniffMedia(ftyp("isom"))).toEqual({ contentType: "video/mp4", kind: "video" });
+ expect(sniffMedia(ftyp("qt "))).toEqual({ contentType: "video/quicktime", kind: "video" });
+ expect(sniffMedia(ebml("webm"))).toEqual({ contentType: "video/webm", kind: "video" });
+ expect(sniffMedia(ebml("matroska"))).toEqual({ contentType: "video/x-matroska", kind: "video" });
+ expect(sniffMedia(riff("AVI LIST"))).toEqual({ contentType: "video/x-msvideo", kind: "video" });
+ });
+
+ it("knows sound", () => {
+ expect(sniffMedia(ftyp("M4A "))).toEqual({ contentType: "audio/mp4", kind: "audio" });
+ expect(sniffMedia(ebml("webm"), "audio/webm")).toEqual({ contentType: "audio/webm", kind: "audio" });
+ expect(sniffMedia(riff("WAVEfmt "))).toEqual({ contentType: "audio/wav", kind: "audio" });
+ expect(sniffMedia(pad("OggS"))).toEqual({ contentType: "audio/ogg", kind: "audio" });
+ expect(sniffMedia(pad("fLaC"))).toEqual({ contentType: "audio/flac", kind: "audio" });
+ expect(sniffMedia(pad("ID3\x04"))).toEqual({ contentType: "audio/mpeg", kind: "audio" });
+ expect(sniffMedia(pad(Buffer.from([0xff, 0xfb, 0x90, 0x64])))).toEqual({ contentType: "audio/mpeg", kind: "audio" });
+ });
+
+ it("refuses GIF (unless allowed), SVG, HTML and ZIP, whatever the declared type", () => {
+ expect(sniffMedia(pad("GIF89a"), "image/gif")).toBeNull();
+ expect(sniffMedia(pad("GIF89a"), "image/gif", { gif: true })).toEqual({ contentType: "image/gif", kind: "image" });
+ expect(sniffMedia(pad('<svg xmlns="http://www.w3.org/2000/svg">'), "image/svg+xml")).toBeNull();
+ expect(sniffMedia(pad("<!doctype html><script>alert(1)</script>"), "image/png")).toBeNull();
+ expect(sniffMedia(pad("PK\x03\x04"), "video/mp4")).toBeNull();
+ expect(sniffMedia(Buffer.from("ab"))).toBeNull();
+ });
+});