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 keys: an account's runs, polls and cancels use only its own key

Adarsha1c2601a41f6
diff --git a/src/app/api/admin/accounts/[id]/route.ts b/src/app/api/admin/accounts/[id]/route.ts
index 0ad86128..7552f0d1 100644
--- a/src/app/api/admin/accounts/[id]/route.ts
+++ b/src/app/api/admin/accounts/[id]/route.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
-import { AccountError, deleteAccount, isOwnerRequest, listAccounts, sessionCookieOf, setAccountDisabled } from "@/server/auth";
-import { purgeAccount } from "@/server/account-sweep";
+import { AccountError, isOwnerRequest, listAccounts, sessionCookieOf, setAccountDisabled } from "@/server/auth";
+import { removeAccount } from "@/server/account-sweep";
async function owner(request: Request): Promise<Response | null> {
return isOwnerRequest(request, sessionCookieOf(request)) ? null : Response.json({ error: "Only the studio's owner manages accounts" }, { status: 403 });
@@ -31,12 +31,11 @@ export async function DELETE(request: Request, ctx: RouteContext<"/api/admin/acc
const denied = await owner(request);
if (denied) return denied;
const { id } = await ctx.params;
+ // Switched off at once, its running jobs stopped (on its own keys), then its runs, files and record go.
try {
- deleteAccount(id);
+ await removeAccount(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 76057c4e..0efe270d 100644
--- a/src/app/api/auth/me/route.ts
+++ b/src/app/api/auth/me/route.ts
@@ -1,10 +1,10 @@
import { cookies } from "next/headers";
import { connection } from "next/server";
import { z } from "zod";
-import { accountGpu, authEnabled, deleteAccount, publicSignup, SESSION_COOKIE, sessionCookieOf, sessionViewer, validToken, verifyAccount } from "@/server/auth";
+import { accountGpu, authEnabled, publicSignup, SESSION_COOKIE, sessionCookieOf, sessionViewer, validToken, verifyAccount } from "@/server/auth";
import { runnerFacts } from "@/server/computer/tasks";
import { getSetting } from "@/server/settings";
-import { purgeAccount } from "@/server/account-sweep";
+import { removeAccount } from "@/server/account-sweep";
import { hit } from "@/server/rate";
/** Who is looking: the owner, an account, or a guest; and whether sign-up is open. Open to everyone. */
@@ -43,9 +43,8 @@ export async function DELETE(request: Request) {
const rate = hit(`delete-me:${session.account.id}`, 5, 60_000);
if (!rate.ok) return Response.json({ error: "Too many tries. Wait a minute, then try again." }, { status: 429, headers: { "Retry-After": String(rate.retryAfterS) } });
if (!(await verifyAccount(session.account.email, parsed.data.password))) return Response.json({ error: "Wrong password" }, { status: 403 });
- deleteAccount(session.account.id);
+ // Switched off at once, its running jobs stopped (on its own keys), then its runs, files and record go.
+ await removeAccount(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/generations/route.ts b/src/app/api/generations/route.ts
index 97c23b9a..445e1614 100644
--- a/src/app/api/generations/route.ts
+++ b/src/app/api/generations/route.ts
@@ -1,12 +1,14 @@
import { connection } from "next/server";
import { CONNECT_GPU_HEADER, GUEST_RUN_MESSAGE, OWN_GPU_TOOL_MESSAGE } from "@/lib/guest-access";
import { missingFilesMessage } from "@/lib/missing-files";
-import { accountGpu, requestViewer } from "@/server/auth";
+import { ADD_KEY_HEADER } from "@/lib/your-keys";
+import { requestViewer } from "@/server/auth";
+import { accountEngineMode } from "@/server/account-keys";
import { OPERATION_LABELS } from "@/lib/catalog/types";
import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "@/server/account-files";
import { accountInputProblem } from "@/server/account-inputs";
import { db } from "@/server/db";
-import { accountLoraFix, accountRun, asVisitor, createGenerations, listGenerations, outputKind, previewGeneration } from "@/server/generations";
+import { accountLoraFix, accountRun, AccountRunError, asAccount, asVisitor, createGenerations, listGenerations, outputKind, previewGeneration, type AccountRunRefusal } from "@/server/generations";
import { ensureTrashPurge, listOptionsFrom } from "@/server/library";
import { hit, unhit } from "@/server/rate";
import { GenerationRequestSchema } from "@/server/request-schema";
@@ -71,15 +73,19 @@ export async function POST(request: Request) {
// A retired model id (an older script, a saved CLI or MCP call) runs on the model that replaced it, and the notes say
// 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.
- let req = account ? { ...asked, account: account.id, engine: "open" as const } : { ...asked, account: undefined };
- const own = account ? accountRun(account.id, "comfyui") : undefined;
- 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, 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));
+ // Public sign-up: an account runs on its own ComfyUI or its own fal.ai or Replicate key, never the install's providers.
+ // Without a key of its own it stays on the open engine; with one, the engine it asked for.
+ let req = account ? { ...asked, account: account.id, engine: accountEngineMode(account.id) === "open" ? ("open" as const) : asked.engine } : { ...asked, account: undefined };
+ const onOwn = <T,>(fn: () => T): T => (account ? asAccount(account.id, fn) : fn());
+ // A visitor's price check: priced as it would run, as that visitor (an account: its own GPU and keys; a guest: the open
+ // engine, no demo).
+ const priced = <T,>(fn: () => T): T => (viewer.kind === "owner" ? fn() : account ? asAccount(account.id, fn) : asVisitor(null, fn));
+ /** An account's run that can't go where it was planned: Connect your GPU, Add your key (the client opens either). */
+ const refused = (r: AccountRunRefusal) => {
+ if (account) unhit(`run:${account.id}`);
+ const headers: Record<string, string> = r.code === "connect-gpu" ? { [CONNECT_GPU_HEADER]: "1" } : r.code === "add-key" && r.provider ? { [ADD_KEY_HEADER]: r.provider } : {};
+ return refuse(403, r.error, { code: r.code, ...(r.provider && { provider: r.provider }) }, headers);
+ };
const notes: string[] = [];
if (account && !preview) {
// Room on the server, room in the account's files, and a fair share of runs.
@@ -111,8 +117,15 @@ export async function POST(request: Request) {
let planned: ReturnType<typeof previewGeneration> | null = null;
try {
planned = onOwn(() => previewGeneration(req));
- } catch {
- // createGenerations says what's wrong with the request.
+ } catch (e) {
+ // A paid model the account has no key for (or a studio that is open-source only).
+ if (e instanceof AccountRunError) return refused(e.refusal);
+ // Otherwise createGenerations says what's wrong with the request.
+ }
+ if (account && planned) {
+ // Where the run goes decides what the account needs: its GPU for ComfyUI, its own key for fal.ai or Replicate.
+ const own = accountRun(account.id, planned.route.provider, "submit");
+ if ("error" in own) return refused(own);
}
if (planned) {
// A 3D model from someone else's ComfyUI is finished on this server (decimate, web GLB, turntable): accounts
@@ -150,7 +163,10 @@ export async function POST(request: Request) {
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 });
+ const refusal = e instanceof AccountRunError ? e.refusal : undefined;
+ // A price check of a paid model the account has no key for says so, without opening "Add your key".
+ if (refusal && !preview) return refused(refusal);
+ if (account && !preview) unhit(`run:${account.id}`);
+ return Response.json({ error: (e as Error).message, ...(refusal && { code: refusal.code, ...(refusal.provider && { provider: refusal.provider }) }) }, { status: 422 });
}
}
diff --git a/src/app/api/models/route.ts b/src/app/api/models/route.ts
index f29fd381..5cee5386 100644
--- a/src/app/api/models/route.ts
+++ b/src/app/api/models/route.ts
@@ -9,7 +9,9 @@ import { rowPrice } from "@/lib/model-rows";
import { AUDIO_STUDIO, DIALOGUE_STUDIO, EDIT_STUDIO, IMAGE_STUDIO, VIDEO_STUDIO } from "@/lib/studios";
import { provider } from "@/server/providers";
import { llmBackends } from "@/server/providers/llm";
-import { offeredDefault, offeredModels } from "@/server/model-access";
+import { offeredDefault, offeredModels, reachableDefault } from "@/server/model-access";
+import { accountEngineMode } from "@/server/account-keys";
+import { asAccount } from "@/server/generations";
import { engineMode, getSetting } from "@/server/settings";
/** A provider for one of its routes is set up. */
@@ -61,28 +63,36 @@ export async function GET(request: Request) {
if (engine && engine !== "open" && engine !== "cloud") return Response.json({ error: "engine is open or cloud" }, { status: 400 });
const op = p.get("op") || undefined;
if (op && !(op in OPERATION_LABELS)) return Response.json({ error: `Unknown operation ${op}` }, { status: 400 });
- // A guest or an account (public sign-up) runs open models on its own GPU: no cloud models, no demo.
- const visitor = requestViewer(request).kind !== "owner";
- const mode = visitor ? "open" : engineMode();
- // A Fuobe Original runs on both engines: on a list for one engine (asked for, or the install's only one) it is
- // that engine's model (its routes, its price), else it is listed once with both.
- const only = (engine as Engine | undefined) ?? (mode === "both" ? undefined : mode);
- // The install's only engine counts as asked for: an Original's operations there are that engine's.
- // Settings → Models & licences: what is switched off isn't listed, and each model lists the routes that are on.
- const list = findModels(offeredModels(MODELS), { kind: kind as MediaKind | undefined, engine: only, op: op as Operation | undefined, q: p.get("q") ?? undefined, hidden: p.get("hidden") === "1" })
- .filter((m) => mode === "both" || runsOn(m, mode))
- .map((m) => (only ? onEngine(m, only) : m));
- // A default that is switched off gives way to the next model that is on and does the same job.
- const pick = (id: string | undefined, e: Engine) => offeredDefault(id, e);
- const defaults = Object.fromEntries(
- Object.entries(DEFAULTS).map(([k, ids]) => [k, { ...(mode !== "open" && ids.cloud && { cloud: pick(ids.cloud, "cloud") }), ...(mode !== "cloud" && ids.open && { open: pick(ids.open, "open") }) }]),
- );
- const demoMode = visitor ? "off" : getSetting("demoMode");
- // The price of the day asked (a launch price while it lasts); the row keeps the launch price and its last day too.
- const now = Date.now();
- const items = list.map((m) => {
- const info = toModelInfo(m);
- return { ...info, price: rowPrice(info, now), connected: visitor || connected(m), runs: visitor ? ("real" as const) : runsAs(m, demoMode) };
- });
- return Response.json({ engineMode: mode, demoMode, defaults, items });
+ // A guest runs open models on its own GPU: no cloud models, no demo. An account too, until it adds its own fal.ai or
+ // Replicate key: then it gets those providers' paid models, each `connected` by its own keys (asAccount).
+ const viewer = requestViewer(request);
+ const account = viewer.kind === "account" ? viewer.account.id : null;
+ const visitor = viewer.kind !== "owner";
+ const list = () => {
+ const mode = account ? accountEngineMode(account) : visitor ? "open" : engineMode();
+ // A Fuobe Original runs on both engines: on a list for one engine (asked for, or the install's only one) it is
+ // that engine's model (its routes, its price), else it is listed once with both.
+ const only = (engine as Engine | undefined) ?? (mode === "both" ? undefined : mode);
+ // The install's only engine counts as asked for: an Original's operations there are that engine's.
+ // Settings → Models & licences: what is switched off isn't listed, and each model lists the routes that are on.
+ const found = findModels(offeredModels(MODELS), { kind: kind as MediaKind | undefined, engine: only, op: op as Operation | undefined, q: p.get("q") ?? undefined, hidden: p.get("hidden") === "1" })
+ .filter((m) => mode === "both" || runsOn(m, mode))
+ .map((m) => (only ? onEngine(m, only) : m));
+ // A default that is switched off gives way to the next model that is on and does the same job; an account's paid
+ // default, to one its own keys can run.
+ const pick = (id: string | undefined, e: Engine) => (account && e === "cloud" ? reachableDefault(offeredDefault(id, e), e, connected) : offeredDefault(id, e));
+ const defaults = Object.fromEntries(
+ Object.entries(DEFAULTS).map(([k, ids]) => [k, { ...(mode !== "open" && ids.cloud && { cloud: pick(ids.cloud, "cloud") }), ...(mode !== "cloud" && ids.open && { open: pick(ids.open, "open") }) }]),
+ );
+ const demoMode = visitor ? "off" : getSetting("demoMode");
+ // The price of the day asked (a launch price while it lasts); the row keeps the launch price and its last day too.
+ const now = Date.now();
+ const items = found.map((m) => {
+ const info = toModelInfo(m);
+ const reach = account ? connected(m) : visitor || connected(m);
+ return { ...info, price: rowPrice(info, now), connected: reach, runs: account ? (reach ? ("real" as const) : ("refused" as const)) : visitor ? ("real" as const) : runsAs(m, demoMode) };
+ });
+ return { engineMode: mode, demoMode, defaults, items };
+ };
+ return Response.json(account ? asAccount(account, list) : list());
}
diff --git a/src/app/api/uploads/route.ts b/src/app/api/uploads/route.ts
index 7fe0e27b..f4f41392 100644
--- a/src/app/api/uploads/route.ts
+++ b/src/app/api/uploads/route.ts
@@ -2,6 +2,7 @@ import fs from "node:fs";
import path from "node:path";
import { nanoid } from "nanoid";
import { CONNECT_GPU_HEADER, CONNECT_GPU_UPLOAD_MESSAGE } from "@/lib/guest-access";
+import { accountProviders } from "@/server/account-keys";
import { imageSize } from "@/lib/image-size";
import { sniffMedia, type SniffKind } from "@/lib/sniff";
import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "@/server/account-files";
@@ -17,7 +18,8 @@ import { adoptFile, contentTypeFor, saveFile, scratchDir } from "@/server/storag
* 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
+ * - An account (public sign-up): only with its own ComfyUI connected or its own fal.ai or Replicate key (something to
+ * run its files on); 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.
*/
@@ -156,7 +158,7 @@ async function ownerUpload(request: Request): Promise<Response> {
// An account
async function accountUpload(request: Request, account: Account): Promise<Response> {
- if (!accountGpu(account.id)) return json(403, { error: CONNECT_GPU_UPLOAD_MESSAGE, code: "connect-gpu" }, { [CONNECT_GPU_HEADER]: "1" });
+ if (!accountGpu(account.id) && !accountProviders(account.id).length) return json(403, { error: CONNECT_GPU_UPLOAD_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);
diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.ts
index 5e6f74bd..fd8a3929 100644
--- a/src/lib/guest-access.ts
+++ b/src/lib/guest-access.ts
@@ -161,11 +161,11 @@ export function accountGeneration(method: string, pathname: string): string | un
/**
* A read of an account's own things, which the route (or the proxy, by accountGeneration) scopes to it:
- * the list of its runs, a stored file (the proxy checks whose it is), its GPU.
+ * the list of its runs, a stored file (the proxy checks whose it is), its GPU, its keys (never a key: their last 4).
*/
export function accountOwnRead(pathname: string): boolean {
if (ACCOUNT_LISTS.has(pathname)) return true;
- return pathname === "/api/generations" || pathname === "/api/account/gpu" || GPU_READS.has(pathname) || COMPUTER_READ.test(pathname);
+ return pathname === "/api/generations" || pathname === "/api/account/gpu" || pathname === "/api/account/keys" || GPU_READS.has(pathname) || COMPUTER_READ.test(pathname);
}
/** The Library's counts and its Uploads (its stored files): each route answers an account with its own only. */
@@ -186,13 +186,14 @@ const COMPUTER_CHANGES: [method: string, path: RegExp][] = [
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, 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).
+ * A change an account may send: signing out, its own GPU and its check, its own fal.ai and Replicate keys, 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;
+ if ((method === "PUT" || method === "DELETE") && /^\/api\/account\/keys\/(fal|replicate)$/.test(pathname)) 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;
// Running its own jobs on its own computer.
@@ -224,10 +225,10 @@ 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, 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.
+ * Runs an account may start once it has connected its own ComfyUI ("Your GPU") or added its own fal.ai or Replicate key
+ * ("Your keys"): the studios' generations, camera motions, effects and apps, which the route sends to that ComfyUI or
+ * that key 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";
@@ -238,8 +239,10 @@ export const OWN_GPU_TOOL_MESSAGE = "This tool doesn't run on your own GPU yet.
/** 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";
export const CONNECT_GPU_MESSAGE = "Connect your GPU to run this. Free accounts run on their own ComfyUI.";
-/** An account's upload without a GPU: its files are kept for runs on its own ComfyUI. */
+/** An account's upload with neither a GPU nor a key of its own: its files are kept for runs on its own ComfyUI or key. */
export const CONNECT_GPU_UPLOAD_MESSAGE = "Connect your GPU to add your own files. A free account uses them on its own ComfyUI.";
+/** An account with neither its own GPU nor its own key (the proxy's answer to a run). */
+export const CONNECT_GPU_OR_KEY_MESSAGE = "Connect your GPU, or add your own fal.ai or Replicate key, to run this.";
/** Install-wide settings, keys and tokens: changes are the owner's (403 for an account). */
const OWNER_WRITES = new Set(["/api/settings", "/api/settings/models", "/api/loras", "/api/llm", "/api/providers/test", "/api/auth/public"]);
diff --git a/src/proxy.ts b/src/proxy.ts
index 8149638d..ea2bba13 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -10,7 +10,7 @@ import {
accountOwnRead,
ASSIST_OWNER_MESSAGE,
CONNECT_GPU_HEADER,
- CONNECT_GPU_MESSAGE,
+ CONNECT_GPU_OR_KEY_MESSAGE,
GUEST_HEADER,
GUEST_LIBRARY_MESSAGE,
GUEST_RUN_MESSAGE,
@@ -23,7 +23,7 @@ import {
ownerOnly,
ownGpuRun,
} from "@/lib/guest-access";
-import { authEnabled, crossSite, hostAllowed, LoginGuard, publicSignup, sessionCookieOf, sessionViewer, validSession, validToken, type Account, type Viewer } from "@/server/auth";
+import { authEnabled, crossSite, hasCloudKey, hostAllowed, LoginGuard, publicSignup, sessionCookieOf, sessionViewer, validSession, validToken, type Account, type Viewer } from "@/server/auth";
import { fileAccount, generationAccount } from "@/server/account-library";
import { hit } from "@/server/rate";
import { recordExists } from "@/server/records";
@@ -191,8 +191,9 @@ function readAsGuest(request: NextRequest, isAccount: boolean): NextResponse {
* owner's library or projects (hidden, and every change to them refused). Its own runs are its own
* (accountGeneration, accountOwnRead: only what it made). Install-wide settings, keys and tokens are
* the owner's, and it never runs on the owner's cloud keys or GPU: with its own ComfyUI connected
- * ("Your GPU") the studios' generations run there, and anything else that would reach a model is
- * refused ("Connect your GPU" until it has one). Assist is the owner's (isAssistChange): a GPU doesn't change that.
+ * ("Your GPU") or its own fal.ai or Replicate key ("Your keys") the studios' generations run there,
+ * and anything else that would reach a model is refused ("Connect your GPU" until it has one).
+ * Assist is the owner's (isAssistChange): a GPU or a key doesn't change that.
*/
const notYours = () => NextResponse.json({ error: ACCOUNT_LIBRARY_MESSAGE }, { status: 403, headers: { "Cache-Control": "no-store" } });
@@ -212,9 +213,10 @@ function account(request: NextRequest, who: Account): NextResponse {
if (accountMayChange(request.method, pathname, search)) return pass(request);
if (isAssistChange(request.method, pathname)) return assistOwner();
if (isLibraryChange(request.method, pathname)) return NextResponse.json({ error: LIBRARY_MESSAGE, code: "library" }, { status: 403 });
- // A tool its own GPU wouldn't run says so first: "Connect your GPU" only for what a GPU unlocks.
+ // A tool its own GPU or key wouldn't run says so first: "Connect your GPU" only for what a GPU or a key unlocks.
if (!ownGpuRun(request.method, pathname)) return NextResponse.json({ error: OWN_GPU_TOOL_MESSAGE, code: "own-gpu-tool" }, { status: 403 });
- if (!who.gpu) return NextResponse.json({ error: CONNECT_GPU_MESSAGE, code: "connect-gpu" }, { status: 403, headers: { [CONNECT_GPU_HEADER]: "1" } });
+ // Neither its own GPU nor its own key: nothing it could run on. (Which one a run needs, the route says.)
+ if (!who.gpu && !hasCloudKey(who)) return NextResponse.json({ error: CONNECT_GPU_OR_KEY_MESSAGE, code: "connect-gpu" }, { status: 403, headers: { [CONNECT_GPU_HEADER]: "1" } });
return pass(request);
}
diff --git a/src/server/account-files.ts b/src/server/account-files.ts
index 6ebe7e9a..920311d4 100644
--- a/src/server/account-files.ts
+++ b/src/server/account-files.ts
@@ -79,7 +79,7 @@ export const ACCOUNT_MESSAGES = {
runRate: "That's a lot of runs this hour. Try again later.",
finishRate: "That's a lot of finished pictures this hour. Try again later.",
finishBusy: "Your last pictures are still being saved. Try again in a moment.",
- outputsCapped: "Runs on your GPU make up to 4 at a time.",
+ outputsCapped: "Account runs make up to 4 at a time.",
bodyTooBig: "That request is too large.",
gpuChecks: "Too many checks. Wait a minute.",
probeRate: "Too many clip checks at once. Wait a moment, then try again.",
diff --git a/src/server/account-gpu.ts b/src/server/account-gpu.ts
index 1173409a..ed24d9c8 100644
--- a/src/server/account-gpu.ts
+++ b/src/server/account-gpu.ts
@@ -1,8 +1,11 @@
import "server-only";
import dns from "node:dns/promises";
import net from "node:net";
+import { isCloudProvider, type CloudProvider } from "@/lib/your-keys";
+import { accountEngineMode, accountProviders, paidAllowed } from "./account-keys";
import { accountGpu, type Account, type AccountGpu } from "./auth";
import { runnerFacts } from "./computer/tasks";
+import { offeredSummary } from "./model-access";
import { PROVIDERS } from "./providers";
import { blockedForAccounts, fetchPublic, isLoopbackGpu } from "./remote-fetch";
import { isInstallHost, REFUSED_ADDRESS } from "./gpu/hosts";
@@ -143,28 +146,40 @@ export interface VisitorView {
kind: "guest" | "account";
/** `mode` "computer": the ComfyUI on the person's own computer, which their Fuobe tab runs. */
gpu: { connected: boolean; mode?: "link" | "computer"; online?: boolean; comfy?: "down" | "no-setting"; device?: string; vramBytes?: number };
+ /** The providers it has its own key for that this server can open ("Your keys"): never a key. */
+ keys: CloudProvider[];
+ /** The studio lets accounts run paid models on their own keys (it isn't open-source only). */
+ paidAllowed: boolean;
}
/**
* GET /api/status for a guest or an account: ComfyUI is its own GPU (taken as there until it has one,
- * so the studios offer Generate and the run asks it to connect one), the open engine, no Demo mode,
- * and nothing of the install's own servers, keys or addresses.
+ * so the studios offer Generate and the run asks it to connect one), fal.ai and Replicate are its own
+ * keys, the engine mode they allow (account-keys.ts), no Demo mode, and nothing of the install's own
+ * servers, keys or addresses.
*/
export async function visitorStatus(account: Account | null) {
const gpu = account ? accountGpu(account.id) : null;
const live = account && gpu ? await gpuState(account.id, gpu) : null;
+ const keys = account ? accountProviders(account.id) : [];
const viewer: VisitorView = {
kind: account ? "account" : "guest",
gpu: gpu
? { connected: true, mode: gpu.mode === "computer" ? "computer" : "link", online: !!live?.online, ...(live?.comfy && { comfy: live.comfy }), ...(live?.device && { device: live.device }), ...(live?.vramBytes && { vramBytes: live.vramBytes }) }
: { connected: false },
+ keys,
+ paidAllowed: paidAllowed(),
};
+ const configured = (id: string) => (id === "comfyui" ? (gpu ? !!live?.online : true) : isCloudProvider(id) && keys.includes(id));
+ const access = keys.length ? offeredSummary() : undefined;
return {
- providers: Object.fromEntries(Object.values(PROVIDERS).map((p) => [p.id, { label: p.id === "comfyui" ? "Your GPU" : p.label, configured: p.id === "comfyui" ? (gpu ? !!live?.online : true) : false }])),
+ providers: Object.fromEntries(Object.values(PROVIDERS).map((p) => [p.id, { label: p.id === "comfyui" ? "Your GPU" : p.label, configured: configured(p.id) }])),
demoMode: "off",
- engineMode: "open",
+ engineMode: account ? accountEngineMode(account.id) : "open",
cloudProvider: "auto",
onboarded: true,
+ // Settings → Models & licences: the paid models the owner switched off stay out of its pickers too.
+ ...(access && { access }),
viewer,
};
}
diff --git a/src/server/account-sweep.ts b/src/server/account-sweep.ts
index a8fd7365..4a77c2ae 100644
--- a/src/server/account-sweep.ts
+++ b/src/server/account-sweep.ts
@@ -3,7 +3,7 @@ import fs from "node:fs";
import path from "node:path";
import { RETENTION_MS, runAccountDeletedHooks } from "./account-files";
import { clearAccountLoras } from "./account-loras";
-import { readAccountIds } from "./auth";
+import { deleteAccount, readAccountIds, setAccountDisabled } from "./auth";
import { db } from "./db";
import { deleteForever } from "./library";
import { deleteAsset, scratchDir } from "./storage";
@@ -44,6 +44,18 @@ export async function purgeAccount(id: string): Promise<{ runs: number; files: n
return { runs, files: files.length };
}
+/**
+ * Delete an account (by itself, or by the owner). In this order: it is switched off (signed out, no new runs); its jobs
+ * still going are stopped, those on its own fal.ai or Replicate key with that key, which is why the record is still
+ * there; its runs and files go; then its record, with its GPU and its keys. If stopping fails it stays switched off and
+ * listed, and can be deleted again.
+ */
+export async function removeAccount(id: string): Promise<void> {
+ setAccountDisabled(id, true);
+ await purgeAccount(id);
+ deleteAccount(id);
+}
+
/** 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.
diff --git a/src/server/generations.ts b/src/server/generations.ts
index c2acc25d..281bed6f 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -55,7 +55,10 @@ import { enhancePrompt, enhanceSoulWords, ideogramCaption } from "./enhance";
import { setResolver, watchGenerations, type LiveEvent } from "./live";
import { provider, PROVIDERS, RETIRED_PROVIDER_ERROR } from "./providers";
import { comfyLoraFiles, computerScope, onOwnGpu, outputFetch, outsideOwnGpu, OWN_OUTPUT_LIMITS, ownGpu, probeComfy, relayFile, type OwnGpu } from "./providers/comfyui";
-import { accountGpu, gpuLink, type AccountGpu } from "./auth";
+import { accountById, accountGpu, gpuLink, type AccountGpu } from "./auth";
+import { accountEngineMode, accountKey, paidAllowed } from "./account-keys";
+import { addKeyMessage, isCloudProvider, keyRemovedMessage, type CloudProvider } from "@/lib/your-keys";
+import type { ProviderAdapter } from "./providers/types";
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";
@@ -499,6 +502,9 @@ export function chooseRoute(candidates: ModelRoute[], images = 0, loras: LoraRef
throw new Error(`This model takes up to ${short.map!.maxImages} images on ${provider(short.provider).label} — remove some${others.length ? `, or connect ${others.join(" or ")} for more` : ""}`);
}
if (demo === "off") {
+ // An account's paid model with no key of its own for any of the model's providers: "Add your key" (fal.ai first).
+ const cloud = tenantAccount() ? routes.map((r) => r.provider).find(isCloudProvider) : undefined;
+ if (cloud) throw new AccountRunError(paidAllowed() ? { error: addKeyMessage(cloud), code: "add-key", provider: cloud } : { error: OPEN_ONLY_RUN, code: "open-only" });
if (routes.every((r) => r.provider === "llm")) throw new Error(llmMissing(routes[0]));
const names = [...new Set(routes.map((r) => provider(r.provider).label))].join(" or ");
throw new Error(`Connect ${names} in Settings to run this model`);
@@ -625,6 +631,9 @@ function prepare(original: GenerationRequest) {
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) {
+ // An account on the open engine has no key of its own that opens (Your keys), or the studio is open-source only.
+ const cloud = mode === "open" && tenantAccount() ? plan.model.routes.map((r) => r.provider).find(isCloudProvider) : undefined;
+ if (cloud) throw new AccountRunError(paidAllowed() ? { error: addKeyMessage(cloud), code: "add-key", provider: cloud } : { error: OPEN_ONLY_RUN, code: "open-only" });
throw new Error(
mode === "open"
? `${plan.model.name} is a paid cloud model, but this install is set to open source only (Settings → Engine mode)`
@@ -764,8 +773,9 @@ const depIds = (v: string | null): string[] => (!v ? [] : v.startsWith("[") ? (J
/**
* 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.
+ * stamped as the account's own: on the open engine, or the engine it asked for while it may use paid models on its own
+ * keys (account-keys.ts accountEngineMode). 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);
@@ -777,7 +787,7 @@ function stampTenant(asked: GenerationRequest, opts: CreateOptions): GenerationR
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" };
+ return { ...asked, account: who, engine: accountEngineMode(who) === "open" ? "open" : asked.engine };
}
export function createGenerations(given: GenerationRequest, opts: CreateOptions = {}): Generation[] {
@@ -1179,11 +1189,11 @@ 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());
+ // An account's step reads its inputs, and is planned, as its run was: as that account, on its own ComfyUI and its own
+ // keys. submit() then checks the step's own provider (its GPU, or its key for that provider).
+ const account = stored.account;
+ const asRun = <T,>(fn: () => T): T => (account ? asAccount(account, 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 asRun(() => Promise.all(outputs.map((o, i) => chainValue(pickOutput(o, slots[i]), slots[i], r.op))));
const missing = values.findIndex((u) => !u);
@@ -1249,22 +1259,63 @@ function recordSubmission(id: string, at: number): void {
}
// ---------------------------------------------------------------------------
-// Public sign-up: an account's runs go to its own ComfyUI ("Your GPU"), never the install's providers
+// Public sign-up: an account's runs go to its own ComfyUI ("Your GPU") or its own fal.ai or Replicate key ("Your
+// keys"), never the install's providers
export const OWN_GPU_ONLY = "Free accounts run only on their own ComfyUI: pick an open-source model.";
+export const OPEN_ONLY_RUN = "This studio runs open-source models only, so paid models don't run here. Pick an open-source model.";
+export const SWITCHED_OFF_RUN = "This account is switched off, so its runs stopped.";
/**
- * How an account's job reaches a provider: inside onOwnGpu (its own ComfyUI, the open engine, no demo
- * outputs), or not at all: no GPU connected, or a provider other than ComfyUI (the install's cloud
- * keys, its local LLM). An unreachable GPU fails the job; it never falls back to the install's.
+ * Everything an account's work runs inside: as the account (tenant.ts: only its own files and runs), on its own ComfyUI
+ * (none yet: an address that reaches nothing), with its own fal.ai and Replicate keys (provider-keys.ts), its engine
+ * mode, fal.ai before Replicate among the keys it has, and no demo outputs.
*/
-export function accountRun(accountId: string, providerId: string): { run: <T>(fn: () => T) => T } | { error: string } {
- const gpu = accountGpu(accountId);
- if (!gpu) return { error: CONNECT_GPU_MESSAGE };
- if (providerId !== "comfyui") return { error: OWN_GPU_ONLY };
- // As the account (tenant.ts: only its own files and runs), on its own ComfyUI, the open engine, no demo outputs.
- const own = ownGpuOf(accountId, gpu);
- return { run: (fn) => runAsTenant({ kind: "account", id: accountId }, () => onOwnGpu(own, () => withCandidates({ engineMode: "open", demoMode: "off" }, fn))) };
+export function asAccount<T>(id: string, fn: () => T): T {
+ const mode = accountEngineMode(id);
+ const gpu = accountGpu(id);
+ return runAsTenant({ kind: "account", id }, () =>
+ onOwnGpu(gpu ? ownGpuOf(id, gpu) : { url: "" }, () => withCandidates({ engineMode: mode, demoMode: "off", cloudProvider: "auto" }, fn)),
+ );
+}
+
+export type AccountRunRefusal = { error: string; code: "connect-gpu" | "add-key" | "own-gpu-tool" | "open-only" | "switched-off"; provider?: CloudProvider };
+
+/**
+ * How an account's job reaches a provider, inside asAccount, or not at all. ComfyUI needs its own GPU; fal.ai and
+ * Replicate need its own key for that provider. Anything else (the install's local LLM, demo outputs) is refused. A
+ * "submit" also needs a live account and a studio that isn't open-source only; a "poll" or "cancel" works for a
+ * switched-off account too, so a job going on its key finishes or stops, never runs on. An unreachable GPU or a refused
+ * key fails the job: it never falls back to the install's.
+ */
+export function accountRun(accountId: string, providerId: string, purpose: "submit" | "poll" | "cancel" = "submit"): { run: <T>(fn: () => T) => T } | AccountRunRefusal {
+ const run = <T,>(fn: () => T): T => asAccount(accountId, fn);
+ if (providerId === "comfyui") return accountGpu(accountId) ? { run } : { error: CONNECT_GPU_MESSAGE, code: "connect-gpu" };
+ if (!isCloudProvider(providerId)) return { error: OWN_GPU_ONLY, code: "own-gpu-tool" };
+ const p = providerId;
+ if (purpose === "submit") {
+ const a = accountById(accountId);
+ if (!a || a.disabled) return { error: SWITCHED_OFF_RUN, code: "switched-off" };
+ if (!paidAllowed()) return { error: OPEN_ONLY_RUN, code: "open-only" };
+ }
+ if (accountKey(accountId, p) === null) return { error: purpose === "submit" ? addKeyMessage(p) : keyRemovedMessage(p), code: "add-key", provider: p };
+ return { run };
+}
+
+/** The account's answer to "who may run this": the route turns it into a 403 the client acts on (Connect your GPU, Add your key). */
+export class AccountRunError extends Error {
+ constructor(readonly refusal: AccountRunRefusal) {
+ super(refusal.error);
+ }
+}
+
+/**
+ * The adapter for a run's provider, only inside its own account's work (none: the owner's). A run that lost its scope
+ * fails here: it never falls into the owner's keys (provider-keys.ts).
+ */
+export function adapterFor(providerId: ProviderId, account: string | undefined): ProviderAdapter {
+ if ((tenantAccount() ?? undefined) !== (account ?? undefined)) throw new Error("This run isn't in its account's scope");
+ return provider(providerId);
}
/** Where an account's ComfyUI is, as the provider takes it: a link, or the person's own computer (its tab runs the jobs). */
@@ -1323,17 +1374,21 @@ export function asVisitor<T>(gpu: AccountGpu | null, fn: () => T, accountId?: st
);
}
+/** A row whose request can't be read: whose it is is unknown, so it is never taken for the owner's (accountOf). */
+const UNREADABLE = "\u0000unreadable";
+
+/** The account a row's run is for; undefined: the owner's. A request that can't be read counts as nobody's (UNREADABLE). */
const accountOf = (r: Pick<Row, "request_json">): string | undefined => {
try {
return (JSON.parse(r.request_json) as GenerationRequest).account;
} catch {
- return undefined;
+ return UNREADABLE;
}
};
function submit(id: string, route: ModelRoute, providerId: ProviderId, plan: ReturnType<typeof planGeneration>, req: GenerationRequest, index: number): Promise<void> {
if (!req.account) return submitNow(id, route, providerId, plan, req, index);
- const own = accountRun(req.account, providerId);
+ const own = accountRun(req.account, providerId, "submit");
if ("error" in own) {
update(id, { status: "failed", error: own.error, completed_at: Date.now(), message: null });
return Promise.resolve();
@@ -1349,11 +1404,12 @@ async function submitNow(
req: GenerationRequest,
index: number,
): Promise<void> {
- const adapter = provider(providerId);
submitting().add(id);
/** Why the run failed, once it has: its files still waiting to be sent are not sent. */
let failed: { error: unknown } | undefined;
try {
+ // An account's run on its own ComfyUI and keys only (asAccount): outside it, nothing is sent.
+ const adapter = adapterFor(providerId, req.account);
// 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);
@@ -1614,7 +1670,12 @@ async function pollGuarded(r: Row): Promise<void> {
polling.add(r.id);
try {
const account = accountOf(r);
- const own = account ? accountRun(account, r.provider) : undefined;
+ // Whose run it is can't be read: never polled as the owner's (with the owner's keys).
+ if (account === UNREADABLE) {
+ update(r.id, { status: "failed", error: "This run's details can't be read, so it was stopped.", completed_at: Date.now(), message: null });
+ return;
+ }
+ const own = account ? accountRun(account, r.provider, "poll") : undefined;
if (own && "error" in own) update(r.id, { status: "failed", error: own.error, completed_at: Date.now(), message: null });
else if (own) await own.run(() => pollOne(r));
else await pollOne(r);
@@ -1716,14 +1777,15 @@ async function pollOne(r: Row): Promise<void> {
// Poll first: a job that finished while the server was asleep or down is collected, not timed out.
let res: PollResult | undefined;
let pollError: unknown;
+ const account = accountOf(r);
try {
- res = await provider(r.provider).poll(ctx);
+ res = await adapterFor(r.provider, account).poll(ctx);
} catch (e) {
pollError = e;
}
- // An account's job waits at most 30 minutes in its own ComfyUI's queue.
- const account = accountOf(r);
+ // An account's job waits at most 30 minutes in its own ComfyUI's queue (or its provider's).
const queueMs = account ? ACCOUNT_LIMITS.queueMs : QUEUE_TIMEOUT_MS;
+ const where = r.provider === "comfyui" ? "your ComfyUI" : provider(r.provider).label;
if (!res || res.state === "queued" || res.state === "running") {
// A job on someone's own computer reached their ComfyUI later than it was handed over (it waited for their tab): its
// queue clock starts then.
@@ -1736,7 +1798,7 @@ async function pollOne(r: Row): Promise<void> {
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)
+ await adapterFor(r.provider, account)
.cancel?.(ctx)
.catch(() => {});
update(r.id, {
@@ -1746,7 +1808,7 @@ async function pollOne(r: Row): Promise<void> {
: res?.state === "queued" && res.timeoutError
? res.timeoutError
: account
- ? `Timed out waiting ${queueMs / 60_000} minutes in your ComfyUI's queue`
+ ? `Timed out waiting ${queueMs / 60_000} minutes in ${where}'s queue`
: `Timed out waiting ${QUEUE_TIMEOUT_MS / 3_600_000} hours in the provider's queue`,
completed_at: now,
message: null,
@@ -1788,7 +1850,7 @@ async function pollOne(r: Row): Promise<void> {
} 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}`;
+ const why = e instanceof AccountFilesFull ? e.message : `Couldn't save a result from ${where}: ${(e as Error).message}`;
update(r.id, { status: "failed", error: why, completed_at: Date.now(), message: null });
return;
}
@@ -1834,7 +1896,7 @@ async function pollOne(r: Row): Promise<void> {
status: "succeeded",
outputs_json: JSON.stringify(outputs),
progress: 1,
- message: dropped ? `Kept the first ${ACCOUNT_LIMITS.outputsPerJob} results (your ComfyUI made ${ACCOUNT_LIMITS.outputsPerJob + dropped})` : null,
+ message: dropped ? `Kept the first ${ACCOUNT_LIMITS.outputsPerJob} results (${where} made ${ACCOUNT_LIMITS.outputsPerJob + dropped})` : null,
completed_at: Date.now(),
});
}
@@ -2167,8 +2229,12 @@ export async function cancelGeneration(id: string): Promise<void> {
// Without an external id the job is still being handed over: submit() cancels it as soon as it lands.
if (r.external_id && model) {
const account = accountOf(r);
- const own = account ? accountRun(account, r.provider) : undefined;
- const cancel = () => Promise.resolve(provider(r.provider).cancel?.(pollContext(r, model))).catch(() => {});
+ // An account's job is stopped with its own key, also when the account is switched off or about to be deleted.
+ const own = account ? accountRun(account, r.provider, "cancel") : undefined;
+ const cancel = () =>
+ Promise.resolve()
+ .then(() => adapterFor(r.provider, account).cancel?.(pollContext(r, model)))
+ .catch(() => {});
if (!own) await cancel();
else if ("run" in own) await own.run(cancel);
}
diff --git a/src/server/loras.ts b/src/server/loras.ts
index 1c332881..534f0e2e 100644
--- a/src/server/loras.ts
+++ b/src/server/loras.ts
@@ -364,6 +364,15 @@ export async function prepareCloudLoras(
for (const l of loras) {
const entry = libraryEntry(l);
const name = loraName(l);
+ // An account's run on its own key: only LoRAs the provider fetches from a public address. Nothing is downloaded or
+ // copied for it (that would use the studio's civitai key and its copies), so a civitai file or a trained one is
+ // refused (withoutUnreachableCivitai leaves civitai files out first).
+ if (tenant()) {
+ const at = cloudPath(l);
+ if (!at || localOnly(l)) throw new LoraError(`${name} can't be sent to ${host} with your key: it runs on your GPU`);
+ out.push(l);
+ continue;
+ }
// Only while the admin keeps GPU-only LoRAs on the GPU (fitLoras has left it out of a cloud run already).
if (localOnly(l)) throw new LoraError(`${name} is licensed for your GPU only, and Settings → Models & licences keeps such LoRAs off the cloud`);
if (l.own && !l.hostedUrl) {
@@ -573,7 +582,17 @@ export function filesInLoraFolder(): { files: Set<string>; problem?: string } {
*/
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: [] };
+ // On its own fal.ai or Replicate key, a civitai file isn't copied for it (that needs the studio's civitai key): it's left out.
+ if (tenant()) {
+ const civitai = target === "comfyui" ? [] : loras.filter((l) => !l.hostedUrl && needsToken(l.url));
+ if (!civitai.length) return { loras, notes: [] };
+ const names = civitai.map(loraName);
+ const list = names.length < 2 ? names.join("") : `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`;
+ return {
+ loras: loras.filter((l) => !civitai.includes(l)),
+ notes: [`${list} ${names.length > 1 ? "download" : "downloads"} from civitai, so runs on your key leave ${names.length > 1 ? "them" : "it"} out`],
+ };
+ }
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;
diff --git a/src/server/model-access.ts b/src/server/model-access.ts
index eb77ff5d..2d990c3a 100644
--- a/src/server/model-access.ts
+++ b/src/server/model-access.ts
@@ -218,6 +218,18 @@ export function offeredDefault(id: string | undefined, engine: Engine): string |
return next?.id ?? id;
}
+/**
+ * A default someone can run (`ready`: an account's own keys reach one of its providers), else the first model that is on,
+ * does the same job on this engine and is ready, else the default itself (its run then asks for the key it needs).
+ */
+export function reachableDefault(id: string | undefined, engine: Engine, ready: (m: ModelDef) => boolean): string | undefined {
+ const own = id ? MODELS.find((m) => m.id === id) : undefined;
+ if (!own || ready(own)) return id;
+ const ops = new Set(onEngine(own, engine).routes.map((r) => r.op));
+ const next = MODELS.find((m) => !m.hidden && m.id !== id && m.kind === own.kind && isOffered(m.id, engine) && ready(m) && onEngine(offeredModel(m)!, engine).routes.some((r) => ops.has(r.op) && providerEngine(r.provider) === engine));
+ return next?.id ?? id;
+}
+
/**
* The summary the browser filters its pickers with (undefined while everything is on). A model whose recipe LoRA is
* switched off counts as off there too (isOffered).
diff --git a/tests/account-gpu.test.ts b/tests/account-gpu.test.ts
index 45ac67fc..b231e981 100644
--- a/tests/account-gpu.test.ts
+++ b/tests/account-gpu.test.ts
@@ -67,12 +67,17 @@ describe("Your GPU: where an account's runs go", () => {
id = auth.createAccount("[email protected]", "long enough").id;
});
- it("refuses an account without a GPU, and any provider but ComfyUI", () => {
+ it("refuses an account without a GPU, fal.ai and Replicate without its own key, and any other provider", () => {
const none = accountRun(id, "comfyui");
expect("error" in none && none.error).toMatch(/Connect your GPU/);
auth.setAccountGpu(id, { url: "https://gpu.example", token: "secret" });
expect(auth.accountGpu(id)).toEqual({ url: "https://gpu.example", token: "secret" });
- for (const p of ["fal", "replicate", "llm", "mock"]) {
+ // fal.ai and Replicate now run on the account's own key (Your keys): without one, "Add your key", never the studio's.
+ for (const p of ["fal", "replicate"]) {
+ const r = accountRun(id, p);
+ expect("error" in r && r, p).toMatchObject({ code: "add-key", provider: p, error: expect.stringMatching(/^Add your (fal\.ai|Replicate) key/) });
+ }
+ for (const p of ["llm", "mock"]) {
const r = accountRun(id, p);
expect("error" in r && r.error, p).toBe(OWN_GPU_ONLY);
}
@@ -160,7 +165,8 @@ describe("the status strip", () => {
const a = auth.createAccount("[email protected]", "long enough");
auth.setAccountGpu(a.id, { url: "http://127.0.0.1:8188" });
const acct = await visitorStatus(auth.accountById(a.id)!);
- expect(acct.viewer).toEqual({ kind: "account", gpu: { connected: true, mode: "link", online: false } });
+ // (keys: the providers it added its own key for, none here; paidAllowed: the studio isn't open-source only.)
+ expect(acct.viewer).toEqual({ kind: "account", gpu: { connected: true, mode: "link", online: false }, keys: [], paidAllowed: true });
expect(acct.providers.comfyui.configured).toBe(false);
expect(JSON.stringify(acct)).not.toContain("owner-comfy.test");
});
diff --git a/tests/account-inputs.test.ts b/tests/account-inputs.test.ts
index baa92823..e2407747 100644
--- a/tests/account-inputs.test.ts
+++ b/tests/account-inputs.test.ts
@@ -113,7 +113,7 @@ describe("an account's fair share", () => {
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.");
+ expect(body.notes).toContain("Account runs make up to 4 at a time.");
});
it("never reached the install's ComfyUI", () => {
diff --git a/tests/account-keys-isolation.test.ts b/tests/account-keys-isolation.test.ts
new file mode 100644
index 00000000..f26155dc
--- /dev/null
+++ b/tests/account-keys-isolation.test.ts
@@ -0,0 +1,448 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { NextRequest } from "next/server";
+import { keysSeen, startFakeFal, startFakeReplicate, type FakeCloud } from "./helpers/fake-cloud";
+import { TINY_PNG } from "./helpers/fake-comfy-runner";
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+vi.mock("next/headers", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/headers")>()), cookies: async () => ({ delete: () => {}, get: () => undefined }) }));
+
+/**
+ * Your keys, end to end through the runs: an account's run, its uploads, polls, cancels (its own, on a timeout, during the
+ * hand-over, the owner's, on deletion) and its chained steps reach fal.ai and Replicate with that account's own key only.
+ * The owner's keys are set in Settings and in the environment all along, and the stand-ins accept them, so any leak
+ * would succeed and show in their logs. An account without a key, or whose key can't be opened, sends nothing.
+ */
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-keys-isolation-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_ENGINE_MODE;
+process.env.FAL_KEY = "owner-fal-env";
+process.env.FAL_KEY_ID = "owner-fal-env-id";
+process.env.FAL_KEY_SECRET = "owner-fal-env-secret";
+process.env.REPLICATE_API_TOKEN = "owner-rep-env";
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const auth = await import("@/server/auth");
+const keys = await import("@/server/account-keys");
+const generationsRoute = await import("@/app/api/generations/route");
+const cancelRoute = await import("@/app/api/generations/[id]/cancel/route");
+const adminRunRoute = await import("@/app/api/admin/generations/[id]/route");
+const adminAccountRoute = await import("@/app/api/admin/accounts/[id]/route");
+const meRoute = await import("@/app/api/auth/me/route");
+const uploadsRoute = await import("@/app/api/uploads/route");
+const statusRoute = await import("@/app/api/status/route");
+const modelsRoute = await import("@/app/api/models/route");
+const { proxy } = await import("@/proxy");
+const gens = await import("@/server/generations");
+const { db } = await import("@/server/db");
+const { setSetting } = await import("@/server/settings");
+const { resetRates, hit } = await import("@/server/rate");
+const { runAsTenant } = await import("@/server/tenant");
+const { MODELS, getModel } = await import("@/lib/catalog");
+const { dualEngine } = await import("@/lib/catalog/engines");
+
+let fal: FakeCloud;
+let rep: FakeCloud;
+let A = "";
+let B = "";
+let C = "";
+let D = "";
+const cookies: Record<string, string> = {};
+const ownerCookie = () => `${auth.SESSION_COOKIE}=${auth.createSession().value}`;
+
+beforeAll(async () => {
+ fal = await startFakeFal();
+ rep = await startFakeReplicate();
+ globalThis.__fuobeTestFalUrl = fal.url;
+ globalThis.__fuobeTestReplicateUrl = rep.url;
+ for (const k of ["owner-fal-db", "owner-fal-env", "owner-fal-env-id:owner-fal-env-secret", "acct-fal-A", "acct-fal-B", "acct-fal-E"]) fal.keys[k] = "good";
+ for (const k of ["owner-rep-db", "owner-rep-env", "acct-rep-A", "acct-rep-D"]) rep.keys[k] = "good";
+ setSetting("falKey", "owner-fal-db");
+ setSetting("replicateToken", "owner-rep-db");
+ auth.setPassword("install password");
+ A = auth.createAccount("[email protected]", "long enough").id;
+ B = auth.createAccount("[email protected]", "long enough").id;
+ C = auth.createAccount("[email protected]", "long enough").id;
+ D = auth.createAccount("[email protected]", "long enough").id;
+ keys.saveAccountKey(A, "fal", "acct-fal-A");
+ keys.saveAccountKey(A, "replicate", "acct-rep-A");
+ keys.saveAccountKey(B, "fal", "acct-fal-B");
+ keys.saveAccountKey(D, "replicate", "acct-rep-D");
+ for (const [n, id] of Object.entries({ A, B, C, D })) cookies[n] = `${auth.SESSION_COOKIE}=${auth.createSession(id).value}`;
+});
+afterAll(async () => {
+ globalThis.__fuobeTestFalUrl = undefined;
+ globalThis.__fuobeTestReplicateUrl = undefined;
+ globalThis.__fuobeTestDiskFree = undefined;
+ await fal.close();
+ await rep.close();
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+beforeEach(async () => {
+ resetRates();
+ fal.holdSubmits = null;
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();
+ // Work still in flight from the last test (a hand-over landing, a poll) ends before the logs start afresh.
+ await new Promise((r) => setTimeout(r, 150));
+ fal.log.length = 0;
+ rep.log.length = 0;
+ fal.pollsToFinish = 2;
+ rep.pollsToFinish = 2;
+});
+
+const post = (cookie: string, body: unknown, url = "/api/generations") => {
+ const text = JSON.stringify(body);
+ return generationsRoute.POST(new Request(`http://localhost:3000${url}`, { method: "POST", headers: { cookie, host: "localhost:3000", "content-type": "application/json", "content-length": String(text.length) }, body: text }));
+};
+const run = async (cookie: string, body: Record<string, unknown>) => {
+ const r = await post(cookie, { feature: "image", prompt: "a quiet harbour at dawn", ...body });
+ const json = await r.json();
+ if (r.status !== 201) throw new Error(`${r.status}: ${JSON.stringify(json)}`);
+ return json.items[0] as { id: string; provider: string };
+};
+const row = (id: string) => db().prepare("SELECT * FROM generations WHERE id = ?").get(id) as { status: string; error: string | null; external_id: string | null; message: string | null; provider: string; outputs_json: string; request_json: string };
+/** Wait for the hand-over to land (an external id), without polling. */
+async function handedOver(id: string) {
+ for (let i = 0; i < 200 && !row(id).external_id && ["queued", "running"].includes(row(id).status); i++) await new Promise((r) => setTimeout(r, 10));
+ return row(id);
+}
+/** Tick the runner until the row is done. */
+async function settle(id: string, ms = 10_000) {
+ const end = Date.now() + ms;
+ await handedOver(id);
+ for (;;) {
+ await globalThis.__fuobeRunner?.tick();
+ const g = row(id);
+ if (!["queued", "running"].includes(g.status) || Date.now() > end) return g;
+ await new Promise((r) => setTimeout(r, 30));
+ }
+}
+const keyed = (f: FakeCloud) => f.log.filter((r) => !r.path.startsWith("/upload/"));
+
+describe("an account's runs reach the provider with its own key only", () => {
+ it("fal.ai: submit, polls (runner and fast lane) and the result", async () => {
+ const g = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" });
+ expect(g.provider).toBe("fal");
+ const done = await settle(g.id);
+ expect(done.status).toBe("succeeded");
+ const outputs = JSON.parse(done.outputs_json) as { url: string }[];
+ expect(outputs[0].url).toMatch(/^\/api\/files\//);
+ expect(keysSeen(fal.log)).toEqual(["Key acct-fal-A"]);
+ expect(rep.log).toEqual([]);
+ // The fast lane polls a job near its end in the same scope.
+ fal.log.length = 0;
+ const g2 = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" });
+ await handedOver(g2.id);
+ db().prepare("UPDATE generations SET status = 'running', progress = 0.95 WHERE id = ?").run(g2.id);
+ await globalThis.__fuobeRunner?.fast?.();
+ // An account's polls run on their own (never holding up the owner's): wait for this one to land.
+ for (let i = 0; i < 100 && !fal.log.some((r) => r.path.split("?")[0].endsWith("/status")); i++) await new Promise((r) => setTimeout(r, 10));
+ expect(keysSeen(fal.log)).toEqual(["Key acct-fal-A"]);
+ expect(fal.log.some((r) => r.path.split("?")[0].endsWith("/status"))).toBe(true);
+ });
+
+ it("fal.ai: its uploaded picture goes up with its key (none on the upload address)", async () => {
+ const up = await uploadsRoute.POST(
+ new Request("http://localhost:3000/api/uploads", { method: "POST", headers: { cookie: cookies.A, host: "localhost:3000", "content-type": "image/png", "x-file-name": "me.png", "content-length": String(TINY_PNG.length) }, body: TINY_PNG }),
+ );
+ expect(up.status).toBe(201);
+ const file = (await up.json()) as { url: string };
+ const g = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud", op: "edit", inputs: { images: [file.url] } });
+ expect((await settle(g.id)).status).toBe("succeeded");
+ expect(fal.log.map((r) => r.path)).toContain("/storage/upload/initiate?storage_type=fal-cdn-v3");
+ expect(keysSeen(keyed(fal))).toEqual(["Key acct-fal-A"]);
+ expect(fal.log.filter((r) => r.path.startsWith("/upload/")).map((r) => r.authorization)).toEqual([undefined]);
+ });
+
+ it("Replicate: an account with only a Replicate key runs there, with its token", async () => {
+ const g = await run(cookies.D, { modelId: "nano-banana-pro", engine: "cloud" });
+ expect(g.provider).toBe("replicate");
+ expect((await settle(g.id)).status).toBe("succeeded");
+ const only = await run(cookies.A, { modelId: "imagen-4", engine: "cloud" });
+ expect(only.provider).toBe("replicate");
+ expect((await settle(only.id)).status).toBe("succeeded");
+ expect(new Set(rep.log.map((r) => r.authorization))).toEqual(new Set(["Bearer acct-rep-D", "Bearer acct-rep-A"]));
+ expect(fal.log).toEqual([]);
+ });
+
+ it("a timeout in the provider's queue cancels there, with the account's key", async () => {
+ fal.pollsToFinish = Infinity;
+ const g = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" });
+ await handedOver(g.id);
+ db().prepare("UPDATE generation_runs SET submitted_at = ? WHERE id = ?").run(Date.now() - 31 * 60_000, g.id);
+ const done = await settle(g.id);
+ expect(done.status).toBe("failed");
+ expect(done.error).toBe("Timed out waiting 30 minutes in fal.ai's queue");
+ const cancel = fal.log.find((r) => r.path.endsWith("/cancel"));
+ expect(cancel?.authorization).toBe("Key acct-fal-A");
+ expect(keysSeen(fal.log)).toEqual(["Key acct-fal-A"]);
+ });
+
+ it("its own cancel, a cancel during the hand-over, and the owner deleting its run: all with its key", async () => {
+ fal.pollsToFinish = Infinity;
+ const a = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" });
+ await handedOver(a.id);
+ await cancelRoute.POST(new Request(`http://localhost:3000/api/generations/${a.id}/cancel`, { method: "POST", headers: { cookie: cookies.A } }), { params: Promise.resolve({ id: a.id }) });
+ expect(row(a.id).status).toBe("canceled");
+ // During the hand-over: the provider holds the submit; the cancel lands first, then the job is stopped there.
+ let release!: () => void;
+ fal.holdSubmits = new Promise((r) => (release = r));
+ const b = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" });
+ while (!fal.log.some((r) => r.method === "POST" && r.body.includes("harbour") && fal.log.indexOf(r) > 1)) await new Promise((r) => setTimeout(r, 5));
+ await gens.cancelGeneration(b.id);
+ release();
+ for (let i = 0; i < 100 && fal.canceled.length < 2; i++) await new Promise((r) => setTimeout(r, 10));
+ expect(row(b.id).status).toBe("canceled");
+ // The owner deletes an account's run, outside any account's scope.
+ fal.holdSubmits = null;
+ const c = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" });
+ await handedOver(c.id);
+ const del = await adminRunRoute.DELETE(new Request(`http://localhost:3000/api/admin/generations/${c.id}`, { method: "DELETE", headers: { cookie: ownerCookie() } }), { params: Promise.resolve({ id: c.id }) });
+ expect(del.status).toBe(204);
+ const cancels = fal.log.filter((r) => r.path.endsWith("/cancel"));
+ expect(cancels).toHaveLength(3);
+ expect(keysSeen(fal.log)).toEqual(["Key acct-fal-A"]);
+ });
+
+ it("a chained step on fal.ai is planned and sent in the account's scope", async () => {
+ const [first] = gens.asAccount(A, () => gens.createGenerations({ feature: "image", modelId: "nano-banana-pro", engine: "cloud", prompt: "first", account: A }));
+ const [second] = gens.asAccount(A, () =>
+ gens.createGenerations({ feature: "image", modelId: "nano-banana-pro", engine: "cloud", op: "edit", prompt: "second", chainFrom: "first", account: A }, { dependsOn: first.id }),
+ );
+ expect((await settle(first.id)).status).toBe("succeeded");
+ expect((await settle(second.id)).status).toBe("succeeded");
+ expect(fal.log.filter((r) => r.method === "POST" && !r.path.startsWith("/storage")).map((r) => JSON.parse(r.body).prompt)).toEqual(["first", "second"]);
+ expect(keysSeen(keyed(fal))).toEqual(["Key acct-fal-A"]);
+ });
+
+ it("the owner's runs in the same process still use the owner's key", async () => {
+ const g = await run(ownerCookie(), { modelId: "nano-banana-pro", engine: "cloud" });
+ expect((await settle(g.id)).status).toBe("succeeded");
+ expect(keysSeen(fal.log)).toEqual(["Key owner-fal-db"]);
+ });
+
+ it("owner, A and B at once: every request carries only its own key, the runner started inside an account's request", async () => {
+ let release!: () => void;
+ fal.holdSubmits = new Promise((r) => (release = r));
+ const runs = await Promise.all([run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud", prompt: "from A" }), run(ownerCookie(), { modelId: "nano-banana-pro", engine: "cloud", prompt: "from owner" }), run(cookies.B, { modelId: "nano-banana-pro", engine: "cloud", prompt: "from B" })]);
+ while (fal.log.filter((r) => r.method === "POST").length < 3) await new Promise((r) => setTimeout(r, 5));
+ release();
+ fal.holdSubmits = null;
+ await Promise.all(runs.map((g) => settle(g.id)));
+ const want: Record<string, string> = { "from A": "Key acct-fal-A", "from owner": "Key owner-fal-db", "from B": "Key acct-fal-B" };
+ for (const r of fal.log.filter((x) => x.method === "POST")) expect(r.authorization).toBe(want[JSON.parse(r.body).prompt]);
+ // Each job's polls carry its own key too.
+ const owners = new Map(runs.map((g) => [db().prepare("SELECT external_id FROM generations WHERE id = ?").pluck().get(g.id) as string, g]));
+ for (const r of fal.log.filter((x) => x.method === "GET")) {
+ const ext = /requests\/([^/]+)/.exec(r.path)?.[1];
+ const g = ext ? owners.get(ext) : undefined;
+ if (!g) continue;
+ const i = runs.indexOf(g);
+ expect(r.authorization).toBe(["Key acct-fal-A", "Key owner-fal-db", "Key acct-fal-B"][i]);
+ }
+ });
+});
+
+describe("no fallback, ever", () => {
+ it("an account without a key gets Add your key for a paid model, and nothing reaches either provider", async () => {
+ auth.setAccountGpu(C, { url: "https://gpu.example" });
+ try {
+ const r = await post(cookies.C, { feature: "image", modelId: "nano-banana-pro", engine: "cloud", prompt: "x" });
+ expect(r.status).toBe(403);
+ expect(r.headers.get("x-fuobe-add-key")).toBe("fal");
+ expect(await r.json()).toMatchObject({ code: "add-key", provider: "fal", error: expect.stringMatching(/^Add your fal\.ai key/) });
+ // A refused run doesn't count against its runs an hour.
+ expect(hit(`run:${C}`, 60, 3_600_000).ok).toBe(true);
+ } finally {
+ auth.setAccountGpu(C, null);
+ }
+ // With neither a GPU nor a key, the proxy answers first.
+ const p = proxy(new NextRequest("http://localhost:3000/api/generations", { method: "POST", headers: { cookie: cookies.C }, body: "{}" }));
+ expect(p.status).toBe(403);
+ expect((await p.json()).error).toMatch(/Connect your GPU, or add your own fal\.ai or Replicate key/);
+ // B has a fal.ai key only: a Replicate-only model asks for a Replicate key.
+ const r = await post(cookies.B, { feature: "image", modelId: "imagen-4", engine: "cloud", prompt: "x" });
+ expect(r.status).toBe(403);
+ expect(r.headers.get("x-fuobe-add-key")).toBe("replicate");
+ expect(fal.log).toEqual([]);
+ expect(rep.log).toEqual([]);
+ });
+
+ it("an account whose key this server can't open (secrets.key replaced) is asked to add it again, with nothing sent", async () => {
+ const file = path.join(dir, "secrets.key");
+ const saved = fs.readFileSync(file);
+ fs.writeFileSync(file, "ef".repeat(32));
+ fs.utimesSync(file, new Date(Date.now() + 60_000), new Date(Date.now() + 60_000));
+ try {
+ const r = await post(cookies.B, { feature: "image", modelId: "nano-banana-pro", engine: "cloud", prompt: "x" });
+ expect(r.status).toBe(403);
+ expect(r.headers.get("x-fuobe-add-key")).toBe("fal");
+ expect(fal.log).toEqual([]);
+ } finally {
+ fs.writeFileSync(file, saved);
+ fs.utimesSync(file, new Date(Date.now() + 120_000), new Date(Date.now() + 120_000));
+ }
+ expect(keys.accountKey(B, "fal")).toBe("acct-fal-B");
+ });
+
+ it("a guest's price check reaches no provider, and no provider counts as connected for it", async () => {
+ const r = await generationsRoute.POST(
+ new Request("http://localhost:3000/api/generations?preview=1", { method: "POST", headers: { host: "localhost:3000", "content-type": "application/json" }, body: JSON.stringify({ feature: "image", modelId: "nano-banana-pro", prompt: "x" }) }),
+ );
+ expect(r.status).toBeLessThan(500);
+ gens.asVisitor(null, () => expect(gens.previewGeneration).toBeDefined());
+ const { falProvider } = await import("@/server/providers/fal");
+ gens.asVisitor(null, () => expect(falProvider.isConfigured()).toBe(false));
+ expect(fal.log).toEqual([]);
+ expect(rep.log).toEqual([]);
+ });
+
+ it("the runner refuses an adapter call outside its run's own account", () => {
+ expect(() => gens.adapterFor("fal", A)).toThrow(/isn't in its account's scope/);
+ runAsTenant({ kind: "account", id: B }, () => expect(() => gens.adapterFor("fal", A)).toThrow(/isn't in its account's scope/));
+ runAsTenant({ kind: "account", id: A }, () => expect(() => gens.adapterFor("fal", undefined)).toThrow(/isn't in its account's scope/));
+ runAsTenant({ kind: "account", id: A }, () => expect(gens.adapterFor("fal", A).id).toBe("fal"));
+ expect(gens.adapterFor("fal", undefined).id).toBe("fal");
+ });
+
+ it("a row whose request can't be read can't be stored (and the runner would fail one, never poll it as the owner's)", () => {
+ const now = Date.now();
+ const insert = () =>
+ db()
+ .prepare(
+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, external_id, external_meta_json, created_at, updated_at) VALUES ('broken-row', 'image', 'nano-banana-pro', 'cloud', 'fal', 't2i', 'image', 'running', '{not json', '[]', 'x', '{}', ?, ?)",
+ )
+ .run(now, now);
+ // The account index reads request_json, so SQLite refuses the row; generations.ts accountOf fails one closed anyway.
+ expect(insert).toThrow(/malformed JSON/);
+ });
+
+ it("a stored address outside fal.ai is never sent the key", async () => {
+ const g = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" });
+ await handedOver(g.id);
+ fal.log.length = 0;
+ db().prepare("UPDATE generations SET external_meta_json = ? WHERE id = ?").run(JSON.stringify({ statusUrl: "https://collector.example/s", responseUrl: "https://collector.example/r", cancelUrl: "https://collector.example/c" }), g.id);
+ const real = globalThis.fetch;
+ const elsewhere: string[] = [];
+ globalThis.fetch = (async (u: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(u instanceof Request ? u.url : u);
+ if (url.includes("collector.example")) elsewhere.push(url);
+ return real(u, init);
+ }) as typeof fetch;
+ try {
+ await globalThis.__fuobeRunner?.tick();
+ await gens.cancelGeneration(g.id);
+ } finally {
+ globalThis.fetch = real;
+ }
+ expect(elsewhere).toEqual([]);
+ });
+});
+
+describe("deleting an account stops its paid runs with its key, then forgets the key", () => {
+ it("by the owner, and by the account itself", async () => {
+ for (const how of ["owner", "self"] as const) {
+ const id = auth.createAccount(`gone-${how}@example.com`, "long enough").id;
+ keys.saveAccountKey(id, "fal", "acct-fal-E");
+ const cookie = `${auth.SESSION_COOKIE}=${auth.createSession(id).value}`;
+ fal.pollsToFinish = Infinity;
+ fal.log.length = 0;
+ const g = await run(cookie, { modelId: "nano-banana-pro", engine: "cloud" });
+ await handedOver(g.id);
+ const res =
+ how === "owner"
+ ? await adminAccountRoute.DELETE(new Request(`http://localhost:3000/api/admin/accounts/${id}`, { method: "DELETE", headers: { cookie: ownerCookie() } }), { params: Promise.resolve({ id }) })
+ : await meRoute.DELETE(new Request("http://localhost:3000/api/auth/me", { method: "DELETE", headers: { cookie, host: "localhost:3000", "content-type": "application/json" }, body: JSON.stringify({ password: "long enough" }) }));
+ expect(res.status, how).toBe(204);
+ const cancel = fal.log.find((r) => r.path.endsWith("/cancel"));
+ expect(cancel?.authorization, how).toBe("Key acct-fal-E");
+ expect(auth.accountById(id), how).toBeUndefined();
+ expect(fs.readFileSync(path.join(dir, "auth.json"), "utf8")).not.toContain(`gone-${how}@example.com`);
+ expect(keysSeen(fal.log)).toEqual(["Key acct-fal-E"]);
+ }
+ });
+});
+
+describe("routing for an account", () => {
+ it("status and models follow its own keys", async () => {
+ const status = async (cookie: string) => (await statusRoute.GET(new Request("http://localhost:3000/api/status", { headers: { cookie, host: "localhost:3000" } }))).json();
+ const a = await status(cookies.A);
+ expect(a).toMatchObject({ engineMode: "both", demoMode: "off", providers: { fal: { configured: true }, replicate: { configured: true } }, viewer: { kind: "account", keys: ["fal", "replicate"], paidAllowed: true } });
+ const c = await status(cookies.C);
+ expect(c).toMatchObject({ engineMode: "open", providers: { fal: { configured: false }, replicate: { configured: false } }, viewer: { keys: [] } });
+ const d = await status(cookies.D);
+ expect(d.viewer.keys).toEqual(["replicate"]);
+ for (const s of [a, c, d]) expect(JSON.stringify(s)).not.toMatch(/acct-|owner-fal|owner-rep|v1\./);
+ const models = async (cookie: string, q: string) => (await modelsRoute.GET(new Request(`http://localhost:3000/api/models?${q}`, { headers: { cookie, host: "localhost:3000" } }))).json();
+ const am = await models(cookies.A, "kind=image&engine=cloud");
+ expect(am.engineMode).toBe("both");
+ expect(am.items.find((m: { id: string }) => m.id === "nano-banana-pro")).toMatchObject({ connected: true, runs: "real" });
+ const bm = await models(cookies.B, "kind=image&engine=cloud");
+ expect(bm.items.find((m: { id: string }) => m.id === "imagen-4")).toMatchObject({ connected: false, runs: "refused" });
+ // A Replicate-only account never starts on a fal.ai-only video default.
+ const dm = await models(cookies.D, "kind=video");
+ const dv = dm.defaults.video.cloud as string | undefined;
+ const repVideo = MODELS.some((m) => !m.hidden && m.kind === "video" && m.routes.some((r) => r.provider === "replicate"));
+ if (repVideo) expect(getModel(dv!)!.routes.some((r) => r.provider === "replicate")).toBe(true);
+ expect((await models(cookies.C, "")).engineMode).toBe("open");
+ });
+
+ it("an account's run keeps the engine it asked for; fal.ai first among its keys, whatever the owner's order", () => {
+ setSetting("cloudProvider", "replicate");
+ try {
+ const route = (id: string, modelId = "nano-banana-pro") => gens.asAccount(id, () => gens.previewGeneration({ feature: "image", modelId, prompt: "x", engine: "cloud", account: id }).route.provider);
+ expect(route(A)).toBe("fal");
+ expect(route(D)).toBe("replicate");
+ // The owner's own runs keep the owner's choice.
+ expect(gens.previewGeneration({ feature: "image", modelId: "nano-banana-pro", prompt: "x", engine: "cloud" }).route.provider).toBe("replicate");
+ } finally {
+ setSetting("cloudProvider", "");
+ }
+ const original = MODELS.find((m) => dualEngine(m) && m.kind === "image" && m.routes.some((r) => r.provider === "fal"));
+ if (original) {
+ const [g] = gens.asAccount(A, () => gens.createGenerations({ feature: "image", modelId: original.id, prompt: "x", engine: "cloud", account: A }));
+ expect(JSON.parse(row(g.id).request_json ?? "{}").engine ?? "cloud").toBe("cloud");
+ void gens.cancelGeneration(g.id);
+ }
+ });
+
+ it("an open-source-only studio keeps an account with a key on open models", async () => {
+ setSetting("engineMode", "open");
+ try {
+ expect(keys.accountEngineMode(A)).toBe("open");
+ const r = await post(cookies.A, { feature: "image", modelId: "nano-banana-pro", engine: "cloud", prompt: "x" });
+ expect(r.status).toBeGreaterThanOrEqual(400);
+ expect(fal.log).toEqual([]);
+ expect(gens.accountRun(A, "fal")).toMatchObject({ code: "open-only" });
+ // A job already going still finishes or stops on its key.
+ expect("run" in gens.accountRun(A, "fal", "poll")).toBe(true);
+ } finally {
+ setSetting("engineMode", "");
+ }
+ });
+
+ it("text steps, the AI helpers, 3D and the other tools stay closed to an account with a key", async () => {
+ expect(gens.accountRun(A, "llm")).toMatchObject({ code: "own-gpu-tool" });
+ const at = (url: string) => proxy(new NextRequest(`http://localhost:3000${url}`, { method: "POST", headers: { cookie: cookies.A }, body: "{}" }));
+ for (const url of ["/api/assist", "/api/enhance", "/api/shorts", "/api/faceless/episodes"]) {
+ const r = at(url);
+ expect(r.status, url).toBe(403);
+ }
+ expect(at("/api/generations").headers.get("x-middleware-next")).toBe("1");
+ // An account switched off: its new runs stop; a job already going finishes or stops on its key.
+ auth.setAccountDisabled(B, true);
+ try {
+ expect(gens.accountRun(B, "fal")).toMatchObject({ code: "switched-off" });
+ expect("run" in gens.accountRun(B, "fal", "cancel")).toBe(true);
+ } finally {
+ auth.setAccountDisabled(B, false);
+ }
+ });
+});
diff --git a/tests/account-keys-limits.test.ts b/tests/account-keys-limits.test.ts
new file mode 100644
index 00000000..a57f59b2
--- /dev/null
+++ b/tests/account-keys-limits.test.ts
@@ -0,0 +1,118 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { startFakeFal, type FakeCloud } from "./helpers/fake-cloud";
+
+/**
+ * Your keys: every account limit applies to runs on its own key too, before anything reaches the provider: runs at
+ * once, runs an hour, outputs a run, its space. A result that doesn't fit its space fails the run and keeps nothing.
+ */
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-keys-limits-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_ENGINE_MODE;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const auth = await import("@/server/auth");
+const keys = await import("@/server/account-keys");
+const generationsRoute = await import("@/app/api/generations/route");
+const { db } = await import("@/server/db");
+const { saveFile } = await import("@/server/storage");
+const { resetRates, hit } = await import("@/server/rate");
+const files = await import("@/server/account-files");
+
+let fal: FakeCloud;
+let A = "";
+let cookie = "";
+beforeAll(async () => {
+ fal = await startFakeFal();
+ globalThis.__fuobeTestFalUrl = fal.url;
+ fal.keys["acct-fal-A"] = "good";
+ auth.setPassword("install password");
+ A = auth.createAccount("[email protected]", "long enough").id;
+ keys.saveAccountKey(A, "fal", "acct-fal-A");
+ cookie = `${auth.SESSION_COOKIE}=${auth.createSession(A).value}`;
+});
+afterAll(async () => {
+ globalThis.__fuobeTestFalUrl = undefined;
+ globalThis.__fuobeTestDiskFree = undefined;
+ await fal.close();
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+beforeEach(async () => {
+ resetRates();
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();
+ db().prepare("DELETE FROM assets WHERE account_id IS NOT NULL").run();
+ await new Promise((r) => setTimeout(r, 100));
+ fal.log.length = 0;
+ fal.pollsToFinish = 2;
+});
+
+const post = (body: Record<string, unknown>) => {
+ const text = JSON.stringify({ feature: "image", modelId: "nano-banana-pro", engine: "cloud", prompt: "a quiet harbour", ...body });
+ return generationsRoute.POST(new Request("http://localhost:3000/api/generations", { method: "POST", headers: { cookie, host: "localhost:3000", "content-type": "application/json", "content-length": String(text.length) }, body: text }));
+};
+const submits = () => fal.log.filter((r) => r.method === "POST").length;
+/** A file of the account that weighs `bytes` (only its row says so). */
+function weigh(bytes: number) {
+ const a = saveFile({ data: Buffer.from("x"), contentType: "image/png", source: "generation", accountId: A });
+ db().prepare("UPDATE assets SET size = ? WHERE id = ?").run(bytes, a.id);
+}
+const row = (id: string) => db().prepare("SELECT status, error FROM generations WHERE id = ?").get(id) as { status: string; error: string | null };
+
+describe("an account's limits hold for runs on its own key", () => {
+ it("4 runs at once: the 5th waits (429), before the provider hears of it", async () => {
+ fal.pollsToFinish = Infinity;
+ for (let i = 0; i < files.ACCOUNT_LIMITS.activeRuns; i++) expect((await post({})).status).toBe(201);
+ for (let i = 0; i < 50 && submits() < 4; i++) await new Promise((r) => setTimeout(r, 10));
+ const fifth = await post({});
+ expect(fifth.status).toBe(429);
+ expect((await fifth.json()).error).toBe(files.ACCOUNT_MESSAGES.activeRuns);
+ expect(submits()).toBe(4);
+ });
+
+ it("60 runs an hour", async () => {
+ for (let i = 0; i < files.ACCOUNT_LIMITS.runsPerHour; i++) hit(`run:${A}`, files.ACCOUNT_LIMITS.runsPerHour, 60 * 60_000);
+ const r = await post({});
+ expect(r.status).toBe(429);
+ expect((await r.json()).error).toBe(files.ACCOUNT_MESSAGES.runRate);
+ expect(fal.log).toEqual([]);
+ });
+
+ it("up to 4 outputs a run, said in the run's notes, and sent as 4 to the provider", async () => {
+ const r = await post({ params: { numOutputs: 8 } });
+ expect(r.status).toBe(201);
+ const body = await r.json();
+ expect(body.notes).toContain("Account runs make up to 4 at a time.");
+ for (let i = 0; i < 50 && submits() < 1; i++) await new Promise((r) => setTimeout(r, 10));
+ const sent = fal.log.find((x) => x.method === "POST");
+ expect(JSON.parse(sent!.body).num_images ?? 4).toBeLessThanOrEqual(4);
+ });
+
+ it("full space: 413 before anything reaches the provider", async () => {
+ weigh(files.accountTotalBytes(A));
+ const r = await post({});
+ expect(r.status).toBe(413);
+ expect(fal.log).toEqual([]);
+ });
+
+ it("a result that doesn't fit its space fails the run and keeps nothing", async () => {
+ const r = await post({});
+ const id = (await r.json()).items[0].id as string;
+ for (let i = 0; i < 100 && !db().prepare("SELECT external_id FROM generations WHERE id = ?").pluck().get(id); i++) await new Promise((r) => setTimeout(r, 10));
+ weigh(files.accountTotalBytes(A) - 10);
+ for (let i = 0; i < 40 && ["queued", "running"].includes(row(id).status); i++) {
+ await globalThis.__fuobeRunner?.tick();
+ await new Promise((r) => setTimeout(r, 20));
+ }
+ expect(row(id).status).toBe("failed");
+ expect(row(id).error).toMatch(/space|full|GB/i);
+ expect(db().prepare("SELECT COUNT(*) FROM assets WHERE generation_id = ?").pluck().get(id)).toBe(0);
+ });
+});
diff --git a/tests/account-tenant.test.ts b/tests/account-tenant.test.ts
index 61519c4a..a3d4a6bf 100644
--- a/tests/account-tenant.test.ts
+++ b/tests/account-tenant.test.ts
@@ -90,7 +90,9 @@ describe("inside an account's work, only its own files", () => {
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));
+ // On the account's own fal.ai key a civitai file is left out (copying it needs the studio's civitai key); its GPU checks its own.
+ asA(() => expect(withoutUnreachableCivitai(civitai, "fal")).toEqual({ loras: [], notes: [expect.stringMatching(/civitai, so runs on your key leave it out/)] }));
+ asA(() => expect(withoutUnreachableCivitai(civitai, "comfyui").loras).toEqual(civitai));
await asA(async () => expect(ensureLorasOnComfy(civitai, [])).rejects.toThrow(/never downloaded/));
});
});
diff --git a/tests/byo-keys-static.test.ts b/tests/byo-keys-static.test.ts
index b4ca85a1..af8b4b74 100644
--- a/tests/byo-keys-static.test.ts
+++ b/tests/byo-keys-static.test.ts
@@ -61,6 +61,13 @@ describe("nothing else reads the studio's fal.ai or Replicate key", () => {
expect(code(sources.find((s) => s.file === "server/providers/replicate.ts")!.text)).toMatch(/cloudKey\("replicate"\)/);
});
+ it("sends a run to its provider only through adapterFor, which checks it runs as the run's own account", () => {
+ const gen = code(sources.find((s) => s.file === "server/generations.ts")!.text);
+ expect(gen).not.toMatch(/\bprovider\([^)]*\)\s*\.\s*(submit|poll|cancel|prepareFile)\b/);
+ expect(gen).not.toMatch(/PROVIDERS\[[^\]]*\]\s*\.\s*(submit|poll|cancel|prepareFile)\b/);
+ expect(gen.match(/adapterFor\(/g)!.length).toBeGreaterThanOrEqual(4);
+ });
+
it("calls the fal.ai and Replicate adapters directly only from training (the owner's)", () => {
expect(offenders(/\b(falProvider|replicateProvider|falFetch)\b/, ["server/providers/fal.ts", "server/providers/replicate.ts", "server/providers/index.ts", "server/training.ts"])).toEqual([]);
});