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: fixes from the review, on the server

Adarsh5328f0649c46
diff --git a/src/app/api/account/keys/[provider]/route.ts b/src/app/api/account/keys/[provider]/route.ts
index ca00a016..e6b9ad2d 100644
--- a/src/app/api/account/keys/[provider]/route.ts
+++ b/src/app/api/account/keys/[provider]/route.ts
@@ -1,7 +1,7 @@
import { z } from "zod";
import { isCloudProvider, NOT_ACCOUNT_KEYS, type CloudProvider } from "@/lib/your-keys";
import { accountKeyInfo, cleanKey, removeAccountKey, saveAccountKey } from "@/server/account-keys";
-import { accountKeyRecord, requestAccount } from "@/server/auth";
+import { accountKeyRecord, LoginGuard, requestAccount } from "@/server/auth";
import { hit, unhit } from "@/server/rate";
import { SecretBoxError } from "@/server/secret-box";
import { checkKey, runsGoingMessage, runsOnKey, stopRunsOnKey } from "@/server/your-keys";
@@ -15,10 +15,35 @@ import { checkKey, runsGoingMessage, runsOnKey, stopRunsOnKey } from "@/server/y
const NO_STORE = { "Cache-Control": "no-store" };
const answer = (status: number, body: Record<string, unknown>, headers: Record<string, string> = {}) => Response.json(body, { status, headers: { ...NO_STORE, ...headers } });
-/** Checks a minute: per account, and for every account together (the server is no key checker for stolen keys). */
+/**
+ * Checks a minute: per account, per address (behind a trusted proxy: one person with many accounts), and for every
+ * account together (the server is no key checker for stolen keys). Only a check that reaches the provider counts.
+ */
const CHECKS_PER_MINUTE = 10;
+const CHECKS_PER_MINUTE_ADDRESS = 20;
const CHECKS_PER_MINUTE_ALL = 120;
+/** Count a check in every bucket, or in none: one that's full gives the others their count back. */
+function countCheck(id: string, headers: Headers): { ok: true } | { ok: false; retryAfterS: number } {
+ const client = LoginGuard.clientKey(headers);
+ const buckets: [string, number][] = [
+ [`keys:${id}`, CHECKS_PER_MINUTE],
+ // Without a trusted proxy every visitor shares one address: the per-account and global counts do the work.
+ ...(client === LoginGuard.DIRECT ? [] : ([[`keys:ip:${client}`, CHECKS_PER_MINUTE_ADDRESS]] as [string, number][])),
+ ["keys:all", CHECKS_PER_MINUTE_ALL],
+ ];
+ const counted: string[] = [];
+ for (const [key, limit] of buckets) {
+ const h = hit(key, limit, 60_000);
+ if (!h.ok) {
+ for (const k of counted) unhit(k);
+ return { ok: false, retryAfterS: h.retryAfterS };
+ }
+ counted.push(key);
+ }
+ return { ok: true };
+}
+
const Body = z.object({ key: z.string().max(400), stopRuns: z.boolean().optional() });
/** The account asking and the provider named, or the answer for anyone else. */
@@ -34,25 +59,22 @@ export async function PUT(request: Request, ctx: RouteContext<"/api/account/keys
const w = await who(request, ctx);
if ("refused" in w) return w.refused;
const { id, provider } = w;
- const mine = hit(`keys:${id}`, CHECKS_PER_MINUTE, 60_000);
- const all = mine.ok ? hit("keys:all", CHECKS_PER_MINUTE_ALL, 60_000) : mine;
- if (!all.ok) {
- if (mine.ok) unhit(`keys:${id}`);
- return answer(429, { error: "Too many checks. Wait a minute." }, { "Retry-After": String(all.retryAfterS) });
- }
const parsed = Body.safeParse(await request.json().catch(() => null));
const key = parsed.success ? cleanKey(parsed.data.key) : null;
if (!parsed.success || !key) return answer(400, { error: "Paste the whole key, without spaces." });
+ const counted = countCheck(id, request.headers);
+ if (!counted.ok) return answer(429, { error: "Too many checks. Wait a minute." }, { "Retry-After": String(counted.retryAfterS) });
const check = await checkKey(provider, key);
if (!check.ok) return answer(check.status, { error: check.error });
- if (new URL(request.url).searchParams.get("test") === "1") return answer(200, { provider, ok: true, detail: check.detail });
+ const said = { detail: check.detail, ...(check.note && { note: check.note }) };
+ if (new URL(request.url).searchParams.get("test") === "1") return answer(200, { provider, ok: true, ...said });
// Replacing a key runs are going on: they stop first, with the key they were sent with.
const going = accountKeyRecord(id, provider) ? runsOnKey(id, provider) : [];
if (going.length && !parsed.data.stopRuns) return answer(409, { code: "runs-going", count: going.length, error: runsGoingMessage(going.length, true) });
if (going.length) await stopRunsOnKey(id, provider);
try {
const info = saveAccountKey(id, provider, key);
- return answer(200, { provider, ...info, detail: check.detail });
+ return answer(200, { provider, ...info, ...said });
} catch (e) {
if (e instanceof SecretBoxError) return answer(503, { error: e.message });
throw e;
diff --git a/src/app/api/account/keys/route.ts b/src/app/api/account/keys/route.ts
index 3a8c5af2..64052f69 100644
--- a/src/app/api/account/keys/route.ts
+++ b/src/app/api/account/keys/route.ts
@@ -1,5 +1,6 @@
import { connection } from "next/server";
import { NOT_ACCOUNT_KEYS, type YourKeys } from "@/lib/your-keys";
+import { ACCOUNT_LIMITS, accountTotalBytes } from "@/server/account-files";
import { accountEngineMode, accountKeyInfo, paidAllowed } from "@/server/account-keys";
import { requestAccount } from "@/server/auth";
@@ -12,6 +13,16 @@ export async function GET(request: Request) {
await connection();
const a = requestAccount(request);
if (!a) return Response.json({ error: NOT_ACCOUNT_KEYS }, { status: 400, headers: { "Cache-Control": "no-store" } });
- const body: YourKeys = { keys: accountKeyInfo(a.id), engineMode: accountEngineMode(a.id), paidAllowed: paidAllowed() };
+ const body: YourKeys = { keys: accountKeyInfo(a.id), engineMode: accountEngineMode(a.id), paidAllowed: paidAllowed(), limits: limitsLine(a.id) };
return Response.json(body, { headers: { "Cache-Control": "no-store" } });
}
+
+const gb = (bytes: number) => `${Math.round(bytes / 2 ** 30)} GB`;
+
+/** The account limits a paid run still counts against, as this account has them now (a new account keeps less). */
+function limitsLine(id: string): string {
+ const L = ACCOUNT_LIMITS;
+ const space = accountTotalBytes(id);
+ const files = space < L.totalBytes ? `${gb(space)} of files in your first week, then ${gb(L.totalBytes)}` : `${gb(space)} of files`;
+ return `${L.activeRuns} runs at once, ${L.runsPerHour} an hour, up to ${L.outputsPerRun} pictures a run, ${files}`;
+}
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index 1952972a..1691c4d1 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -1133,6 +1133,8 @@ export interface Generation {
* "Fix it", which opens the GPU pre-flight's guided fix.
*/
fix?: GenerationFix | null;
+ /** Failed or stopped before its paid provider took the job (no external id): the card says "Not billed", not its price. */
+ notBilled?: true;
/**
* What the run leaves out or changes, said when it is created (LoRAs a cloud run can't carry, a clip length
* the API rounds). Only on the answer that creates it; not stored.
diff --git a/src/lib/your-keys.ts b/src/lib/your-keys.ts
index 23303e9c..fdef2e11 100644
--- a/src/lib/your-keys.ts
+++ b/src/lib/your-keys.ts
@@ -40,6 +40,8 @@ export interface YourKeys {
engineMode: "open" | "both";
/** The studio lets accounts use paid models with their own keys (it isn't open-source only). */
paidAllowed: boolean;
+ /** The account limits its paid runs still count against, as it has them now: "4 runs at once, … 1 GB of files in your first week, then 3 GB". */
+ limits: string;
}
/** Set on an account's refused run (its value: fal or replicate): the client opens "Add your key". */
@@ -48,6 +50,9 @@ export const ADD_KEY_HEADER = "x-fuobe-add-key";
export const addKeyMessage = (p: CloudProvider) => `Add your ${CLOUD_KEY[p].label} key to run this. Runs on ${CLOUD_KEY[p].label} are billed to your own ${CLOUD_KEY[p].label} account.`;
export const keyRejectedMessage = (p: CloudProvider) => `${CLOUD_KEY[p].label} didn't accept your key. Check it in Settings → Your keys.`;
export const balanceMessage = (p: CloudProvider) => `Your ${CLOUD_KEY[p].label} balance has run out. Top it up on ${CLOUD_KEY[p].label}, then run again.`;
+/** A key saved that works, on a provider account with nothing on it yet. */
+export const emptyBalanceNote = (p: CloudProvider) =>
+ `Your ${CLOUD_KEY[p].label} key works, but your ${CLOUD_KEY[p].label} balance is empty. Top it up on ${CLOUD_KEY[p].label} before you run.`;
export const keyRemovedMessage = (p: CloudProvider) => `Your ${CLOUD_KEY[p].label} key was removed, so this run stopped.`;
/** The owner (or anyone not signed in as an account) on /api/account/keys. */
export const NOT_ACCOUNT_KEYS = "Your keys are for accounts. The studio's own keys are in Settings → Paid API configuration.";
@@ -93,15 +98,20 @@ const names = (ps: readonly CloudProvider[]) => ps.map((p) => CLOUD_KEY[p].label
/**
* The engine switch for an account: locked on open source (and why, and where to change that), or the words for its two
- * sides. Null for the owner and guests (the switch follows Settings → Engine mode).
+ * sides. Null for the owner and guests (the switch follows Settings → Engine mode). `addKey`: locked only for want of a
+ * key, so the switch opens "Add your key" (and says "Add key" where a phone has no room for the rest).
*/
-export function accountEngine(s: KeyStatus | undefined): { locked: { text: string; tip: string; href: string } } | { tips: { cloud: string; open: string } } | null {
+export function accountEngine(
+ s: KeyStatus | undefined,
+): { locked: { text: string; tip: string; href: string; addKey?: true } } | { tips: { cloud: string; open: string } } | null {
const v = s?.viewer;
if (v?.kind !== "account") return null;
if (v.paidAllowed === false) return { locked: { text: "Open source only", tip: "This studio runs open-source models only.", href: "/settings#your-gpu" } };
const keys = v.keys ?? [];
if (!keys.length) {
- return { locked: { text: "Open source only", tip: "Your runs use your own GPU. Add a fal.ai or Replicate key in Settings → Your keys to use paid models.", href: "/settings#your-keys" } };
+ return {
+ locked: { text: "Open source only", tip: "Your runs use your own GPU. Add a fal.ai or Replicate key to use paid models.", href: "/settings#your-keys", addKey: true },
+ };
}
return {
tips: {
diff --git a/src/server/account-sweep.ts b/src/server/account-sweep.ts
index 4a77c2ae..a3daa5b1 100644
--- a/src/server/account-sweep.ts
+++ b/src/server/account-sweep.ts
@@ -5,6 +5,7 @@ import { RETENTION_MS, runAccountDeletedHooks } from "./account-files";
import { clearAccountLoras } from "./account-loras";
import { deleteAccount, readAccountIds, setAccountDisabled } from "./auth";
import { db } from "./db";
+import { handOversDone } from "./generations";
import { deleteForever } from "./library";
import { deleteAsset, scratchDir } from "./storage";
@@ -47,12 +48,18 @@ export async function purgeAccount(id: string): Promise<{ runs: number; files: n
/**
* 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
+ * there; its runs and files go; a job still being handed over is stopped when its submit lands, with that key too, so
+ * the record waits for it; 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);
+ const going = db()
+ .prepare("SELECT id FROM generations WHERE status IN ('queued', 'running') AND json_extract(request_json, '$.account') = ?")
+ .pluck()
+ .all(id) as string[];
await purgeAccount(id);
+ if (!(await handOversDone(going))) console.warn("[fuobe] account deletion: a run was still being handed to its provider after a minute; the account goes anyway");
deleteAccount(id);
}
diff --git a/src/server/generations.ts b/src/server/generations.ts
index e3a503a4..4e818196 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -166,6 +166,8 @@ export function toGeneration(r: Row): Generation {
pinnedAt: r.pinned_at ?? null,
review: isReviewStatus(r.review) ? r.review : null,
...(r.status === "failed" && r.fix_json && { fix: parseFix(r.fix_json) }),
+ // Failed or stopped before a paid provider took the job (a refused key, an empty balance): nothing was billed.
+ ...((r.status === "failed" || r.status === "canceled") && !r.external_id && (r.provider === "fal" || r.provider === "replicate") && { notBilled: true as const }),
};
}
@@ -1044,6 +1046,20 @@ declare global {
}
const submitting = (): Set<string> => (globalThis.__fuobeSubmitting ??= new Set<string>());
+/**
+ * Wait (at most `ms`) until none of these runs is still being handed to its provider. A run cancelled during its
+ * hand-over is stopped there as soon as its submit lands (submitNow), with the key it was sent with: removing or
+ * replacing that key, or deleting the account, waits for this first. False when one is still going at the end.
+ */
+export async function handOversDone(ids: readonly string[], ms = 60_000): Promise<boolean> {
+ const end = Date.now() + ms;
+ while (ids.some((id) => submitting().has(id))) {
+ if (Date.now() >= end) return false;
+ await new Promise((r) => setTimeout(r, 25));
+ }
+ return true;
+}
+
/**
* A chain runs all for real or all as a demo (a demo join of paid clips, or a paid step fed a demo
* placeholder, helps nobody). Returns the error for a step that can't match its dependencies, and
@@ -1390,6 +1406,8 @@ function submit(id: string, route: ModelRoute, providerId: ProviderId, plan: Ret
const own = accountRun(req.account, providerId, "submit");
if ("error" in own) {
update(id, { status: "failed", error: own.error, completed_at: Date.now(), message: null });
+ // A chained step advanceDependents marked as being handed over isn't any more.
+ submitting().delete(id);
return Promise.resolve();
}
return own.run(() => submitNow(id, route, providerId, plan, req, index));
@@ -2225,7 +2243,8 @@ export async function cancelGeneration(id: string): Promise<void> {
return;
}
const model = getModel(r.model_id);
- // Without an external id the job is still being handed over: submit() cancels it as soon as it lands.
+ // Without an external id the job is still being handed over: submit() cancels it as soon as it lands, with the key it
+ // was sent with (removing that key, or deleting the account, waits for it: handOversDone).
if (r.external_id && model) {
const account = accountOf(r);
// An account's job is stopped with its own key, also when the account is switched off or about to be deleted.
diff --git a/src/server/provider-keys.ts b/src/server/provider-keys.ts
index d3ec632b..7ee0a5e6 100644
--- a/src/server/provider-keys.ts
+++ b/src/server/provider-keys.ts
@@ -40,6 +40,12 @@ export function redactKey(text: string, key: string): string {
const BALANCE = /exhausted balance|insufficient (credit|balance|funds)|out of credit|top up your balance|payment required/i;
+/**
+ * A refusal that is about the provider account's balance, not the key: 402, or fal.ai's 403 "User is locked. Reason:
+ * Exhausted balance". The key itself works.
+ */
+export const balanceRefusal = (status: number, text: string): boolean => status === 402 || ((status === 401 || status === 403) && BALANCE.test(text));
+
/**
* An account's run refused by its provider, said the way to fix it: its key (Settings → Your keys, which then says the
* provider stopped accepting it) or its balance. Undefined for the owner's runs and for any other error.
@@ -47,7 +53,7 @@ const BALANCE = /exhausted balance|insufficient (credit|balance|funds)|out of cr
export function accountKeyError(p: CloudProvider, status: number, text: string, used: string): ProviderError | undefined {
const account = tenantAccount();
if (!account) return undefined;
- if (status === 402 || ((status === 401 || status === 403) && BALANCE.test(text))) return new ProviderError(balanceMessage(p), status);
+ if (balanceRefusal(status, text)) return new ProviderError(balanceMessage(p), status);
if (status === 401 || status === 403) {
if (status === 401) markKeyRejected(account, p, used);
return new ProviderError(keyRejectedMessage(p), status);
diff --git a/src/server/providers/fal.ts b/src/server/providers/fal.ts
index 45e5938f..51b10c3e 100644
--- a/src/server/providers/fal.ts
+++ b/src/server/providers/fal.ts
@@ -2,7 +2,7 @@ import "server-only";
import { createFalClient } from "@fal-ai/client";
import { loraEndpointFor, routeLoraField } from "@/lib/catalog/loras";
import { buildPayload, extractOutputs, noOutputsError } from "@/lib/catalog/payload";
-import { accountKeyError, cloudKey, missingKeyError, originOf, redactKey, standIn } from "../provider-keys";
+import { accountKeyError, balanceRefusal, cloudKey, missingKeyError, originOf, redactKey, standIn } from "../provider-keys";
import { tenant } from "../tenant";
import { ProviderError, type ProviderAdapter } from "./types";
@@ -174,12 +174,16 @@ export const falProvider: ProviderAdapter = {
},
};
-/** What a key check found: accepted, refused by the provider, the provider out of reach, or an answer that says nothing. */
-export type KeyCheck = { ok: true; detail: string } | { ok: false; detail: string; reason: "rejected" | "unreachable" | "odd"; status?: number };
+/**
+ * What a key check found: accepted, refused by the provider, a key that works on an account with no balance left, the
+ * provider out of reach, or an answer that says nothing.
+ */
+export type KeyCheck = { ok: true; detail: string } | { ok: false; detail: string; reason: "rejected" | "balance" | "unreachable" | "odd"; status?: number };
/**
* Check a fal.ai key, and only that key (Settings' "Save & test", an account's Your keys): the status of a request that
- * doesn't exist. Free, and nothing runs: 401/403 means a bad key, 404/422 a key that works.
+ * doesn't exist. Free, and nothing runs: 401/403 means a bad key (or, saying so, an empty balance), 404/422 a key that
+ * works.
*/
export async function testFalKey(k: string): Promise<KeyCheck> {
if (!k) return { ok: false, detail: "No key set", reason: "rejected" };
@@ -192,7 +196,11 @@ export async function testFalKey(k: string): Promise<KeyCheck> {
} catch (e) {
return { ok: false, detail: redactKey(`Can't reach fal.ai (${(e as Error).message})`, k), reason: "unreachable" };
}
- if (res.status === 401 || res.status === 403) return { ok: false, detail: `Key rejected (${res.status})`, reason: "rejected", status: res.status };
+ if (res.status === 401 || res.status === 402 || res.status === 403) {
+ const text = await res.text().catch(() => "");
+ if (balanceRefusal(res.status, text)) return { ok: false, detail: "Key works, but the fal.ai balance is empty: top it up on fal.ai", reason: "balance", status: res.status };
+ return { ok: false, detail: `Key rejected (${res.status})`, reason: "rejected", status: res.status };
+ }
if (res.ok || [400, 404, 422].includes(res.status)) return { ok: true, detail: "Key accepted" };
// A proxy or an outage (405, 407, 5xx) says nothing about the key: don't call it accepted.
return { ok: false, detail: `Couldn't check the key: fal.ai answered ${res.status}. Try again in a moment`, reason: "odd", status: res.status };
diff --git a/src/server/providers/replicate.ts b/src/server/providers/replicate.ts
index 862b7d6a..80e1f20f 100644
--- a/src/server/providers/replicate.ts
+++ b/src/server/providers/replicate.ts
@@ -1,7 +1,7 @@
import "server-only";
import { loraEndpointFor } from "@/lib/catalog/loras";
import { buildPayload, extractOutputs, noOutputsError } from "@/lib/catalog/payload";
-import { accountKeyError, cloudKey, missingKeyError, originOf, redactKey, standIn } from "../provider-keys";
+import { accountKeyError, balanceRefusal, cloudKey, missingKeyError, originOf, redactKey, standIn } from "../provider-keys";
import { toDataUri } from "../storage";
import { tenant } from "../tenant";
import type { KeyCheck } from "./fal";
@@ -128,5 +128,7 @@ export async function testReplicateKey(t: string): Promise<KeyCheck> {
} catch {}
if (res.ok) return { ok: true, detail: `Signed in as ${body.username ?? "unknown"}` };
const said = redactKey(`replicate ${res.status}: ${body.detail ?? body.title ?? text.slice(0, 300)}`, t);
- return { ok: false, detail: said, reason: res.status === 401 || res.status === 403 ? "rejected" : "odd", status: res.status };
+ // No credit left (402): the token works.
+ const reason = balanceRefusal(res.status, text) ? "balance" : res.status === 401 || res.status === 403 ? "rejected" : "odd";
+ return { ok: false, detail: said, reason, status: res.status };
}
diff --git a/src/server/your-keys.ts b/src/server/your-keys.ts
index f04a3fe5..c55a03c7 100644
--- a/src/server/your-keys.ts
+++ b/src/server/your-keys.ts
@@ -1,8 +1,8 @@
import "server-only";
import { settingProblem } from "@/lib/connections";
-import { CLOUD_KEY, type CloudProvider } from "@/lib/your-keys";
+import { CLOUD_KEY, emptyBalanceNote, type CloudProvider } from "@/lib/your-keys";
import { db } from "./db";
-import { cancelGeneration } from "./generations";
+import { cancelGeneration, handOversDone } from "./generations";
import { testFalKey, type KeyCheck } from "./providers/fal";
import { testReplicateKey } from "./providers/replicate";
@@ -11,11 +11,15 @@ import { testReplicateKey } from "./providers/replicate";
* removes or replaces. The key itself is only ever sent to its provider; nothing here logs it or answers with it.
*/
-/** A key checked with its provider before it is saved: a free call that runs nothing, with the typed key only. */
-export async function checkKey(p: CloudProvider, key: string): Promise<{ ok: true; detail: string } | { ok: false; error: string; status: number }> {
+/**
+ * A key checked with its provider before it is saved: a free call that runs nothing, with the typed key only. A key that
+ * works on a provider account with no balance left is saved too, with a note that says to top it up.
+ */
+export async function checkKey(p: CloudProvider, key: string): Promise<{ ok: true; detail: string; note?: string } | { ok: false; error: string; status: number }> {
const { label } = CLOUD_KEY[p];
const check: KeyCheck = p === "fal" ? await testFalKey(key) : await testReplicateKey(key);
if (check.ok) return { ok: true, detail: check.detail };
+ if (check.reason === "balance") return { ok: true, detail: "Key accepted", note: emptyBalanceNote(p) };
if (check.reason === "rejected") {
const hint = settingProblem(CLOUD_KEY[p].setting, key);
return { ok: false, status: 422, error: `${label} didn't accept this key. Copy it again from ${label}'s API keys page.${hint ? ` (${hint}.)` : ""}` };
@@ -32,10 +36,14 @@ export function runsOnKey(accountId: string, p: CloudProvider): string[] {
.all(p, accountId) as string[];
}
-/** Stop the account's runs on a provider, at the provider, with the key still saved (before it is removed or replaced). */
+/**
+ * Stop the account's runs on a provider, at the provider, with the key still saved (before it is removed or replaced).
+ * A run still being handed over is stopped there when its submit lands: that waits too.
+ */
export async function stopRunsOnKey(accountId: string, p: CloudProvider): Promise<number> {
const ids = runsOnKey(accountId, p);
for (const id of ids) await cancelGeneration(id);
+ if (!(await handOversDone(ids))) console.warn(`[fuobe] Your keys: a run was still being handed to ${CLOUD_KEY[p].label} after a minute; the key changes anyway`);
return ids.length;
}
diff --git a/tests/account-keys-isolation.test.ts b/tests/account-keys-isolation.test.ts
index f26155dc..f54eadf5 100644
--- a/tests/account-keys-isolation.test.ts
+++ b/tests/account-keys-isolation.test.ts
@@ -446,3 +446,45 @@ describe("routing for an account", () => {
}
});
});
+
+describe("a run its provider never took", () => {
+ it("says it was not billed (an empty balance at submit); a run fal.ai took keeps its price", async () => {
+ const id = auth.createAccount("[email protected]", "long enough").id;
+ fal.keys["acct-fal-broke"] = "broke";
+ keys.saveAccountKey(id, "fal", "acct-fal-broke");
+ const cookie = `${auth.SESSION_COOKIE}=${auth.createSession(id).value}`;
+ const g = await run(cookie, { modelId: "nano-banana-pro", engine: "cloud" });
+ const failed = await settle(g.id);
+ expect(failed.status).toBe("failed");
+ expect(failed.error).toBe("Your fal.ai balance has run out. Top it up on fal.ai, then run again.");
+ const shown = gens.getGeneration(g.id)!;
+ expect(shown.costUsd).toBeGreaterThan(0);
+ expect(shown.notBilled).toBe(true);
+ const ok = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" });
+ expect((await settle(ok.id)).status).toBe("succeeded");
+ expect(gens.getGeneration(ok.id)!.notBilled).toBeUndefined();
+ });
+});
+
+describe("deleting an account while its run is being handed over", () => {
+ it("stops the job at fal.ai with its key when the submit lands, then the account and its key go", async () => {
+ const id = auth.createAccount("[email protected]", "long enough").id;
+ keys.saveAccountKey(id, "fal", "acct-fal-E");
+ const cookie = `${auth.SESSION_COOKIE}=${auth.createSession(id).value}`;
+ fal.pollsToFinish = Infinity;
+ fal.canceled.length = 0;
+ let release!: () => void;
+ fal.holdSubmits = new Promise((r) => (release = r));
+ const g = await run(cookie, { modelId: "nano-banana-pro", engine: "cloud" });
+ while (!fal.log.some((r) => r.method === "POST" && !r.path.startsWith("/storage"))) await new Promise((r) => setTimeout(r, 5));
+ const pending = adminAccountRoute.DELETE(new Request(`http://localhost:3000/api/admin/accounts/${id}`, { method: "DELETE", headers: { cookie: ownerCookie() } }), { params: Promise.resolve({ id }) });
+ for (let i = 0; i < 200 && db().prepare("SELECT 1 FROM generations WHERE id = ?").get(g.id); i++) await new Promise((r) => setTimeout(r, 10));
+ expect(auth.accountById(id)).toBeDefined();
+ release();
+ expect((await pending).status).toBe(204);
+ expect(fal.canceled).toHaveLength(1);
+ expect(fal.log.find((r) => r.path.endsWith("/cancel"))?.authorization).toBe("Key acct-fal-E");
+ expect(keysSeen(fal.log)).toEqual(["Key acct-fal-E"]);
+ expect(auth.accountById(id)).toBeUndefined();
+ });
+});
diff --git a/tests/account-keys-routes.test.ts b/tests/account-keys-routes.test.ts
index 33cc6acd..97d54ecd 100644
--- a/tests/account-keys-routes.test.ts
+++ b/tests/account-keys-routes.test.ts
@@ -12,6 +12,7 @@ import { keysSeen, startFakeFal, startFakeReplicate, type FakeCloud } from "./he
* stops them with the old key.
*/
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 }) }));
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-keys-routes-"));
process.env.FUOBE_DATA_DIR = dir;
@@ -151,6 +152,8 @@ describe("adding a key", () => {
keys: { fal: { last4: "3f9a", addedAt: expect.any(Number), readable: true }, replicate: { last4: "5c21", addedAt: expect.any(Number), readable: true } },
engineMode: "both",
paidAllowed: true,
+ // A new account keeps 1 GB in its first week: the line says so (never "3 GB" alone).
+ limits: "4 runs at once, 60 an hour, up to 4 pictures a run, 1 GB of files in your first week, then 3 GB",
});
});
@@ -250,3 +253,138 @@ describe("replacing and removing a key with runs going on it", () => {
expect(again.headers.get("x-fuobe-add-key")).toBe("fal");
});
});
+
+describe("a key that works on an empty balance", () => {
+ it("is saved, with a note to top it up (fal.ai's 403 lock, Replicate's 402), never 'copy it again'", async () => {
+ const id = auth.createAccount("[email protected]", "long enough").id;
+ const who = `${auth.SESSION_COOKIE}=${auth.createSession(id).value}`;
+ fal.keys["broke-key-id-5555:broke-key-secret-6a7b"] = "broke";
+ rep.keys["r8_brokeToken8c9d"] = "broke";
+ const f = await put("fal", { key: "broke-key-id-5555:broke-key-secret-6a7b" }, "", who);
+ expect(f.status).toBe(200);
+ expect(await f.json()).toMatchObject({
+ provider: "fal",
+ last4: "6a7b",
+ note: "Your fal.ai key works, but your fal.ai balance is empty. Top it up on fal.ai before you run.",
+ });
+ const r = await put("replicate", { key: "r8_brokeToken8c9d" }, "", who);
+ expect(r.status).toBe(200);
+ expect((await r.json()).note).toBe("Your Replicate key works, but your Replicate balance is empty. Top it up on Replicate before you run.");
+ const test = await put("fal", { key: "broke-key-id-5555:broke-key-secret-6a7b" }, "?test=1", who);
+ expect(await test.json()).toMatchObject({ ok: true, note: expect.stringMatching(/balance is empty/) });
+ const saved = (await keysRoute.GET(req("/api/account/keys", "GET", undefined, who)).then((x) => x.json())).keys;
+ expect(saved.fal).toMatchObject({ last4: "6a7b", readable: true });
+ expect(saved.replicate).toMatchObject({ last4: "8c9d", readable: true });
+ });
+});
+
+describe("the check budget", () => {
+ it("counts only checks that reach the provider: accounts sending junk never block another account's key", async () => {
+ resetRates();
+ const junkers = Array.from({ length: 13 }, (_, i) => `${auth.SESSION_COOKIE}=${auth.createSession(auth.createAccount(`junk-${i}@example.com`, "long enough").id).value}`);
+ for (const who of junkers) for (let i = 0; i < 10; i++) expect((await put("fal", { key: "x" }, "", who)).status).toBe(400);
+ expect(fal.log).toEqual([]);
+ const r = await put("fal", { key: GOOD_FAL }, "?test=1");
+ expect(r.status).toBe(200);
+ });
+
+ it("behind a trusted proxy, one address with many accounts can't use up every account's checks", async () => {
+ resetRates();
+ process.env.FUOBE_TRUST_PROXY = "1";
+ try {
+ const from = (ip: string, who: string) =>
+ keyRoute.PUT(
+ new Request("http://localhost:3000/api/account/keys/fal?test=1", { method: "PUT", headers: { cookie: who, host: "localhost:3000", "content-type": "application/json", "x-forwarded-for": ip }, body: JSON.stringify({ key: BAD_FAL }) }),
+ ctx("fal"),
+ );
+ const many = Array.from({ length: 3 }, (_, i) => `${auth.SESSION_COOKIE}=${auth.createSession(auth.createAccount(`one-address-${i}@example.com`, "long enough").id).value}`);
+ const answers: number[] = [];
+ for (const who of many) for (let i = 0; i < 10; i++) answers.push((await from("203.0.113.7", who)).status);
+ expect(answers.filter((s) => s === 422)).toHaveLength(20);
+ expect(answers.filter((s) => s === 429)).toHaveLength(10);
+ // Someone else, from another address, still gets their check.
+ const other = await keyRoute.PUT(
+ new Request("http://localhost:3000/api/account/keys/fal?test=1", { method: "PUT", headers: { cookie, host: "localhost:3000", "content-type": "application/json", "x-forwarded-for": "198.51.100.4" }, body: JSON.stringify({ key: GOOD_FAL }) }),
+ ctx("fal"),
+ );
+ expect(other.status).toBe(200);
+ } finally {
+ delete process.env.FUOBE_TRUST_PROXY;
+ }
+ });
+});
+
+describe("a run still being handed over when its key goes", () => {
+ const until = async (ok: () => boolean) => {
+ for (let i = 0; i < 300 && !ok(); i++) await new Promise((r) => setTimeout(r, 10));
+ };
+ /** An account with a fal.ai key, and a paid run whose submit fal.ai holds (it has no external id yet). */
+ const heldRun = async (email: string, k: string) => {
+ const id = auth.createAccount(email, "long enough").id;
+ const who = `${auth.SESSION_COOKIE}=${auth.createSession(id).value}`;
+ fal.keys[k] = "good";
+ expect((await put("fal", { key: k }, "", who)).status).toBe(200);
+ fal.pollsToFinish = Infinity;
+ fal.log.length = 0;
+ fal.canceled.length = 0;
+ let release!: () => void;
+ fal.holdSubmits = new Promise<void>((r) => (release = r));
+ const r = await generationsRoute.POST(req("/api/generations", "POST", { feature: "image", modelId: "nano-banana-pro", engine: "cloud", prompt: "a quiet harbour" }, who));
+ expect(r.status).toBe(201);
+ const run = (await r.json()).items[0].id as string;
+ await until(() => fal.log.some((x) => x.method === "POST" && !x.path.startsWith("/storage")));
+ expect(db().prepare("SELECT external_id FROM generations WHERE id = ?").pluck().get(run)).toBeNull();
+ return { id, who, run, release };
+ };
+ const statusOf = (id: string) => db().prepare("SELECT status FROM generations WHERE id = ?").pluck().get(id);
+ const cancelAuth = () => fal.log.filter((x) => x.path.endsWith("/cancel")).map((x) => x.authorization);
+
+ it("removing it stops the job at fal.ai, with that key, when the submit lands", async () => {
+ const k = "held-key-id-1111:held-key-secret-a1a1";
+ const { id, who, run, release } = await heldRun("[email protected]", k);
+ const pending = keyRoute.DELETE(req("/api/account/keys/fal", "DELETE", { stopRuns: true }, who), ctx("fal"));
+ await until(() => statusOf(run) === "canceled");
+ // The key stays until the hand-over is over.
+ await new Promise((r) => setTimeout(r, 50));
+ expect(auth.accountKeyRecord(id, "fal")).not.toBeNull();
+ release();
+ fal.holdSubmits = null;
+ expect((await pending).status).toBe(200);
+ expect(fal.canceled).toHaveLength(1);
+ expect(cancelAuth()).toEqual([`Key ${k}`]);
+ expect(auth.accountKeyRecord(id, "fal")).toBeNull();
+ });
+
+ it("replacing it stops the job with the old key, never the new one", async () => {
+ const k = "held-key-id-2222:held-key-secret-b2b2";
+ const next = "held-key-id-3333:held-key-secret-c3c3";
+ fal.keys[next] = "good";
+ const { id, who, run, release } = await heldRun("[email protected]", k);
+ const pending = put("fal", { key: next, stopRuns: true }, "", who);
+ await until(() => statusOf(run) === "canceled");
+ release();
+ fal.holdSubmits = null;
+ const r = await pending;
+ expect(r.status).toBe(200);
+ expect((await r.json()).last4).toBe("c3c3");
+ expect(fal.canceled).toHaveLength(1);
+ expect(cancelAuth()).toEqual([`Key ${k}`]);
+ expect(keysSeen(fal.log.filter((x) => x.path.endsWith("/cancel") || (x.method === "POST" && !x.path.startsWith("/storage"))))).toEqual([`Key ${k}`]);
+ expect(auth.accountKeyRecord(id, "fal")?.last4).toBe("c3c3");
+ });
+
+ it("deleting the account stops the job with its key before the account and its keys go", async () => {
+ const k = "held-key-id-4444:held-key-secret-d4d4";
+ const { id, who, run, release } = await heldRun("[email protected]", k);
+ const pending = meRoute.DELETE(req("/api/auth/me", "DELETE", { password: "long enough" }, who));
+ await until(() => statusOf(run) === undefined);
+ await new Promise((r) => setTimeout(r, 50));
+ expect(auth.accountById(id)).toBeDefined();
+ release();
+ fal.holdSubmits = null;
+ expect((await pending).status).toBe(204);
+ expect(fal.canceled).toHaveLength(1);
+ expect(cancelAuth()).toEqual([`Key ${k}`]);
+ expect(auth.accountById(id)).toBeUndefined();
+ });
+});
diff --git a/tests/your-keys-ui.test.ts b/tests/your-keys-ui.test.ts
index 94b25dec..bdc183be 100644
--- a/tests/your-keys-ui.test.ts
+++ b/tests/your-keys-ui.test.ts
@@ -53,7 +53,7 @@ describe("which paid models an account can run", () => {
describe("the engine switch for an account", () => {
it("is locked on open source without a key, pointing at Your keys", () => {
expect(accountEngine(account([]))).toEqual({
- locked: { text: "Open source only", tip: "Your runs use your own GPU. Add a fal.ai or Replicate key in Settings → Your keys to use paid models.", href: "/settings#your-keys" },
+ locked: { text: "Open source only", tip: "Your runs use your own GPU. Add a fal.ai or Replicate key to use paid models.", href: "/settings#your-keys", addKey: true },
});
});