The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Your keys: one function reads a fal.ai or Replicate key
Adarsh1067fcae9c1b
diff --git a/src/server/provider-keys.ts b/src/server/provider-keys.tsnew file mode 100644index 00000000..d3ec632b--- /dev/null+++ b/src/server/provider-keys.ts@@ -0,0 +1,97 @@+import "server-only";+import { addKeyMessage, balanceMessage, CLOUD_KEY, keyRejectedMessage, type CloudProvider } from "@/lib/your-keys";+import { accountKey, markKeyRejected } from "./account-keys";+import { ProviderError } from "./providers/types";+import { getSetting } from "./settings";+import { tenant, tenantAccount } from "./tenant";++/**+ * The fal.ai key or Replicate token a provider call sends: the one place Fuobe reads one (tests/byo-keys-static.test.ts+ * keeps it so).+ *+ * - Inside an account's work (tenant.ts): that account's own key ("Your keys"), or "" when it has none or this server+ * can't open it. Never the studio's key, the environment's, an unsaved "Save & test" value, or another account's.+ * - Inside a guest's work: "".+ * - Otherwise (the owner, the owner's background work): Settings → Paid API configuration, or FAL_KEY /+ * REPLICATE_API_TOKEN.+ */+export function cloudKey(p: CloudProvider): string {+ const t = tenant();+ if (t?.kind === "account") return accountKey(t.id, p) ?? "";+ if (t) return "";+ return getSetting(p === "fal" ? "falKey" : "replicateToken");+}++/** A provider call with no key to send: refused before anything is sent. */+export function missingKeyError(p: CloudProvider): ProviderError {+ return new ProviderError(tenantAccount() ? addKeyMessage(p) : `Add a ${CLOUD_KEY[p].label} key in Settings → Paid API configuration`, 401);+}++/**+ * Text that may hold a key (a provider's error that echoes the request): the key, and each half of a fal.ai+ * key_id:key_secret, become "••••".+ */+export function redactKey(text: string, key: string): string {+ if (!key) return text;+ let out = text.split(key).join("••••");+ for (const half of key.split(":")) if (half.length >= 8) out = out.split(half).join("••••");+ return out;+}++const BALANCE = /exhausted balance|insufficient (credit|balance|funds)|out of credit|top up your balance|payment required/i;++/**+ * 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.+ */+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 (status === 401 || status === 403) {+ if (status === 401) markKeyRejected(account, p, used);+ return new ProviderError(keyRejectedMessage(p), status);+ }+ return undefined;+}++declare global {+ /** Tests only: a stand-in fal.ai (queue and REST) on this machine (see standIn). */+ var __fuobeTestFalUrl: string | undefined;+ /** Tests only: a stand-in Replicate on this machine (see standIn). */+ var __fuobeTestReplicateUrl: string | undefined;+}++/**+ * Tests and `next dev` only: a stand-in fal.ai or Replicate on this machine, so no test or local smoke run ever calls+ * the real (paid) services. vitest: globalThis.__fuobeTestFalUrl / __fuobeTestReplicateUrl; `next dev`:+ * FUOBE_DEV_FAL_URL / FUOBE_DEV_REPLICATE_URL. Only an http://127.0.0.1 or http://localhost origin. `next start` and+ * `next build` run with NODE_ENV=production, so this is always null on a live server.+ */+export function standIn(p: CloudProvider): string | null {+ if (process.env.NODE_ENV === "production") return null;+ const v =+ process.env.VITEST === "true"+ ? p === "fal"+ ? globalThis.__fuobeTestFalUrl+ : globalThis.__fuobeTestReplicateUrl+ : process.env.NODE_ENV === "development"+ ? process.env[p === "fal" ? "FUOBE_DEV_FAL_URL" : "FUOBE_DEV_REPLICATE_URL"]+ : undefined;+ if (!v) return null;+ try {+ const u = new URL(v);+ return u.protocol === "http:" && (u.hostname === "127.0.0.1" || u.hostname === "localhost") ? u.origin : null;+ } catch {+ return null;+ }+}++/** The origin of a URL, or "" for one that can't be read. */+export const originOf = (url: string): string => {+ try {+ return new URL(url).origin;+ } catch {+ return "";+ }+};diff --git a/src/server/providers/fal.ts b/src/server/providers/fal.tsindex 4d1a94d6..45e5938f 100644--- a/src/server/providers/fal.ts+++ b/src/server/providers/fal.ts@@ -2,7 +2,8 @@ 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 { getSetting } from "../settings";+import { accountKeyError, cloudKey, missingKeyError, originOf, redactKey, standIn } from "../provider-keys";+import { tenant } from "../tenant";import { ProviderError, type ProviderAdapter } from "./types";/**@@ -13,17 +14,34 @@ import { ProviderError, type ProviderAdapter } from "./types";* cancel: PUT <cancel_url>* We always use the URLs returned at submit time: for nested endpoint ids* (fal-ai/kling-video/v2.5-turbo/pro/image-to-video) the status/result paths drop the sub-path.+ *+ * The key is the run's own (provider-keys.ts cloudKey: an account's run sends its own key, never the studio's), and it+ * goes to fal.ai's own hosts only.*/const QUEUE = "https://queue.fal.run";+const REST = "https://rest.fal.ai";++/** fal.ai's queue: the real one, or a stand-in on this machine in tests and `next dev` (provider-keys.ts standIn). */+export const falQueue = () => standIn("fal") ?? QUEUE;++/** Where a fal.ai key may go: the queue and the REST API (storage uploads), or the stand-in. */+function keyOrigin(url: string): boolean {+ const o = originOf(url);+ return o === QUEUE || o === REST || (!!o && o === standIn("fal"));+}function key(): string {- return getSetting("falKey");+ return cloudKey("fal");}export async function falFetch(url: string, init: RequestInit = {}): Promise<unknown> {+ const k = key();+ if (!k && tenant()) throw missingKeyError("fal");+ // A status, result or cancel address is the one fal.ai gave at submit: the key goes to fal.ai's own hosts only.+ if (!keyOrigin(url)) throw new ProviderError("fal.ai gave an address outside fal.ai, so Fuobe didn't send the key there");const res = await fetch(url, {...init,- headers: { Authorization: `Key ${key()}`, "Content-Type": "application/json", ...(init.headers ?? {}) },+ headers: { Authorization: `Key ${k}`, "Content-Type": "application/json", ...(init.headers ?? {}) },});const text = await res.text();let body: unknown = text;@@ -31,11 +49,26 @@ export async function falFetch(url: string, init: RequestInit = {}): Promise<unkbody = JSON.parse(text);} catch {}if (!res.ok) {- throw new ProviderError(`fal ${res.status}: ${describeError(body)}`, res.status);+ // A provider's error may echo the request: the key never reaches a message, a row or a log.+ const said = redactKey(`fal ${res.status}: ${describeError(body)}`, k);+ throw accountKeyError("fal", res.status, said, k) ?? new ProviderError(said, res.status);}return body;}+/**+ * The fal client's requests. The client adds the key on calls to fal.ai's REST API only (a file's upload address gets+ * none); this keeps it so. In tests and `next dev` the REST API is the stand-in.+ */+const clientFetch: typeof fetch = (input, init) => {+ const url = input instanceof Request ? input.url : String(input);+ const local = standIn("fal");+ const target = local && url.startsWith(REST) ? local + url.slice(REST.length) : url;+ const headers = new Headers(init?.headers);+ if (!keyOrigin(target)) headers.delete("authorization");+ return fetch(target, { ...init, headers });+};+function describeError(body: unknown): string {if (typeof body === "string") return body.slice(0, 500);const b = body as { detail?: unknown; error?: unknown; message?: unknown };@@ -60,12 +93,21 @@ export const falProvider: ProviderAdapter = {isConfigured: () => !!key(),async prepareFile(data, contentType, name) {- const client = createFalClient({ credentials: key() });+ // Always a key as a string ("" too): left out, the fal client would take FAL_KEY from the environment.+ const k = key();+ if (!k && tenant()) throw missingKeyError("fal");+ const client = createFalClient({ credentials: k, fetch: clientFetch, suppressLocalCredentialsWarning: true });// The file keeps its name (and so its extension): an unnamed blob is stored as "<time>.<subtype>", and// a LoRA mirrored as application/octet-stream would land at ….octet, which loaders that go by the// extension (fal's LTX-2.3 quality takes only .safetensors URLs) refuse.const blob = fileName(name) ? new File([new Uint8Array(data)], fileName(name)!, { type: contentType }) : new Blob([new Uint8Array(data)], { type: contentType });- return client.storage.upload(blob);+ try {+ return await client.storage.upload(blob);+ } catch (e) {+ const status = (e as { status?: number }).status ?? 0;+ const said = redactKey(`fal ${status || "upload"}: ${(e as Error).message}`, k);+ throw accountKeyError("fal", status, said, k) ?? new ProviderError(said, status || undefined);+ }},async submit({ route, input }) {@@ -79,7 +121,7 @@ export const falProvider: ProviderAdapter = {} catch (e) {throw new ProviderError((e as Error).message);}- const res = (await falFetch(`${QUEUE}/${endpoint}`, {+ const res = (await falFetch(`${falQueue()}/${endpoint}`, {method: "POST",body: JSON.stringify(payload),})) as { request_id: string; status_url: string; response_url: string; cancel_url: string };@@ -127,20 +169,31 @@ export const falProvider: ProviderAdapter = {},async test() {- if (!key()) return { ok: false, detail: "No key set" };- // Status lookup of a bogus request id: 401/403 means bad key, 404/422 means the key works.- let res: Response;- try {- res = await fetch(`${QUEUE}/fal-ai/flux/dev/requests/00000000-0000-0000-0000-000000000000/status`, {- headers: { Authorization: `Key ${key()}` },- signal: AbortSignal.timeout(15_000),- });- } catch (e) {- return { ok: false, detail: `Can't reach fal.ai (${(e as Error).message})` };- }- if (res.status === 401 || res.status === 403) return { ok: false, detail: `Key rejected (${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` };+ const { ok, detail } = await testFalKey(key());+ return { ok, detail };},};++/** 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 };++/**+ * 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.+ */+export async function testFalKey(k: string): Promise<KeyCheck> {+ if (!k) return { ok: false, detail: "No key set", reason: "rejected" };+ let res: Response;+ try {+ res = await fetch(`${falQueue()}/fal-ai/flux/dev/requests/00000000-0000-0000-0000-000000000000/status`, {+ headers: { Authorization: `Key ${k}` },+ signal: AbortSignal.timeout(15_000),+ });+ } 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.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.tsindex 80fe229c..862b7d6a 100644--- a/src/server/providers/replicate.ts+++ b/src/server/providers/replicate.ts@@ -1,8 +1,10 @@import "server-only";import { loraEndpointFor } from "@/lib/catalog/loras";import { buildPayload, extractOutputs, noOutputsError } from "@/lib/catalog/payload";-import { getSetting } from "../settings";+import { accountKeyError, cloudKey, missingKeyError, originOf, redactKey, standIn } from "../provider-keys";import { toDataUri } from "../storage";+import { tenant } from "../tenant";+import type { KeyCheck } from "./fal";import { ProviderError, type ProviderAdapter } from "./types";/**@@ -11,17 +13,27 @@ import { ProviderError, type ProviderAdapter } from "./types";* POST /v1/predictions { version, input } (endpoint "owner/name:version")* GET /v1/predictions/{id} → { status: starting|processing|succeeded|failed|canceled, output, error, logs }* POST /v1/predictions/{id}/cancel+ *+ * The token is the run's own (provider-keys.ts cloudKey: an account's run sends its own token, never the studio's), and+ * it goes to Replicate's API only.*/-const API = "https://api.replicate.com/v1";+const HOST = "https://api.replicate.com";++/** Replicate's API: the real one, or a stand-in on this machine in tests and `next dev` (provider-keys.ts standIn). */+const api = () => `${standIn("replicate") ?? HOST}/v1`;function token(): string {- return getSetting("replicateToken");+ return cloudKey("replicate");}async function rFetch(url: string, init: RequestInit = {}): Promise<unknown> {+ const t = token();+ if (!t && tenant()) throw missingKeyError("replicate");+ const origin = originOf(url);+ if (origin !== HOST && origin !== standIn("replicate")) throw new ProviderError("That address is outside Replicate, so Fuobe didn't send the token there");const res = await fetch(url, {...init,- headers: { Authorization: `Bearer ${token()}`, ...(init.body instanceof FormData ? {} : { "Content-Type": "application/json" }), ...(init.headers ?? {}) },+ headers: { Authorization: `Bearer ${t}`, ...(init.body instanceof FormData ? {} : { "Content-Type": "application/json" }), ...(init.headers ?? {}) },});const text = await res.text();let body: unknown = text;@@ -30,7 +42,9 @@ async function rFetch(url: string, init: RequestInit = {}): Promise<unknown> {} catch {}if (!res.ok) {const b = body as { detail?: string; title?: string };- throw new ProviderError(`replicate ${res.status}: ${b?.detail ?? b?.title ?? String(text).slice(0, 300)}`, res.status);+ // A provider's error may echo the request: the token never reaches a message, a row or a log.+ const said = redactKey(`replicate ${res.status}: ${b?.detail ?? b?.title ?? String(text).slice(0, 300)}`, t);+ throw accountKeyError("replicate", res.status, said, t) ?? new ProviderError(said, res.status);}return body;}@@ -44,7 +58,7 @@ export const replicateProvider: ProviderAdapter = {if (data.length < 1_000_000) return toDataUri(data, contentType);const form = new FormData();form.append("content", new Blob([new Uint8Array(data)], { type: contentType }), name);- const file = (await rFetch(`${API}/files`, { method: "POST", body: form })) as { urls: { get: string } };+ const file = (await rFetch(`${api()}/files`, { method: "POST", body: form })) as { urls: { get: string } };return file.urls.get;},@@ -59,15 +73,15 @@ export const replicateProvider: ProviderAdapter = {}const [slug, version] = endpoint.split(":");const res = (await (version- ? rFetch(`${API}/predictions`, { method: "POST", body: JSON.stringify({ version, input: payload }) })- : rFetch(`${API}/models/${slug}/predictions`, { method: "POST", body: JSON.stringify({ input: payload }) }))) as {+ ? rFetch(`${api()}/predictions`, { method: "POST", body: JSON.stringify({ version, input: payload }) })+ : rFetch(`${api()}/models/${slug}/predictions`, { method: "POST", body: JSON.stringify({ input: payload }) }))) as {id: string;};return { externalId: res.id, payload };},async poll({ externalId, route }) {- const p = (await rFetch(`${API}/predictions/${externalId}`)) as {+ const p = (await rFetch(`${api()}/predictions/${externalId}`)) as {status: string;output: unknown;error?: string;@@ -89,16 +103,30 @@ export const replicateProvider: ProviderAdapter = {},async cancel({ externalId }) {- await rFetch(`${API}/predictions/${externalId}/cancel`, { method: "POST" }).catch(() => {});+ await rFetch(`${api()}/predictions/${externalId}/cancel`, { method: "POST" }).catch(() => {});},async test() {- if (!token()) return { ok: false, detail: "No token set" };- try {- const a = (await rFetch(`${API}/account`)) as { username?: string };- return { ok: true, detail: `Signed in as ${a.username ?? "unknown"}` };- } catch (e) {- return { ok: false, detail: (e as Error).message };- }+ const { ok, detail } = await testReplicateKey(token());+ return { ok, detail };},};++/** Check a Replicate token, and only that token (Settings' "Save & test", an account's Your keys): who it signs in as. Free. */+export async function testReplicateKey(t: string): Promise<KeyCheck> {+ if (!t) return { ok: false, detail: "No token set", reason: "rejected" };+ let res: Response;+ try {+ res = await fetch(`${api()}/account`, { headers: { Authorization: `Bearer ${t}` }, signal: AbortSignal.timeout(15_000) });+ } catch (e) {+ return { ok: false, detail: redactKey(`Can't reach Replicate (${(e as Error).message})`, t), reason: "unreachable" };+ }+ const text = await res.text().catch(() => "");+ let body: { username?: string; detail?: string; title?: string } = {};+ try {+ body = JSON.parse(text);+ } 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 };+}diff --git a/src/server/training.ts b/src/server/training.tsindex f92d1942..180fde6a 100644--- a/src/server/training.ts+++ b/src/server/training.ts@@ -31,7 +31,8 @@ import { DEFAULT_AI_TOOLKIT_URL } from "@/lib/connections";import { DATA_DIR, db } from "./db";import { getElement, updateElement } from "./elements";import { keepTrainedLora, lorasPath, ownCopy, recordTrainedMirror } from "./loras";-import { falFetch, falProvider } from "./providers/fal";+import { cloudKey } from "./provider-keys";+import { falFetch, falProvider, falQueue } from "./providers/fal";import { ProviderError } from "./providers/types";import { engineMode, getSetting, isCandidate, savedSetting } from "./settings";import { readRef } from "./storage";@@ -147,7 +148,7 @@ export function trainingBlocker(t: TrainingTarget): string | null {if (mode !== "both" && !fam.lead[mode]) {return `${fam.name} runs only ${mode === "open" ? "in the cloud" : "on your GPU"}, which this install turned off (${ENGINE_MODE_PLACE})`;}- if (t.provider === "fal" && !getSetting("falKey")) return "Add a fal.ai key in Settings";+ if (t.provider === "fal" && !cloudKey("fal")) return "Add a fal.ai key in Settings";if (t.provider === "ai-toolkit" && !getSetting("aiToolkitUrl")) return "Set your AI-Toolkit URL in Settings → Training (or download the training kit)";return null;}@@ -380,7 +381,7 @@ function testDatasetDir(): { ok: boolean; detail: string } {}/** The fal queue URL of a trainer endpoint. */-export const falQueueUrl = (endpoint: string) => `https://queue.fal.run/${endpoint}`;+export const falQueueUrl = (endpoint: string) => `${falQueue()}/${endpoint}`;async function submit(id: string, el: StudioElement, t: TrainingTarget, trigger: string, images: string[]) {const meta = metaOf((db().prepare("SELECT meta_json FROM trainings WHERE id = ?").get(id) as Pick<Row, "meta_json"> | undefined) ?? { meta_json: null });diff --git a/tests/account-keys-providers.test.ts b/tests/account-keys-providers.test.tsnew file mode 100644index 00000000..ec100f29--- /dev/null+++ b/tests/account-keys-providers.test.ts@@ -0,0 +1,234 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";+import type { ModelDef, ModelRoute } from "@/lib/catalog/types";+import { keysSeen, startFakeFal, startFakeReplicate, type FakeCloud } from "./helpers/fake-cloud";++/**+ * Your keys, at every provider call site: inside an account's work fal.ai and Replicate get that account's own key, and+ * never the studio's (Settings, the environment, an unsaved "Save & test" value) or another account's. A guest and an+ * account without a key send nothing at all. The owner's calls still send the owner's key. Against stand-in servers+ * (tests/helpers/fake-cloud.ts): no real key, no paid call.+ */+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-keys-providers-"));+process.env.FUOBE_DATA_DIR = dir;+delete process.env.FUOBE_PASSWORD;+// The owner's keys everywhere they can be: the environment (the fal client's own defaults too) and Settings.+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";++const auth = await import("@/server/auth");+const keys = await import("@/server/account-keys");+const { setSetting, withCandidates } = await import("@/server/settings");+const { runAsTenant } = await import("@/server/tenant");+const { falProvider, falQueue } = await import("@/server/providers/fal");+const { replicateProvider } = await import("@/server/providers/replicate");+const { falQueueUrl } = await import("@/server/training");++let fal: FakeCloud;+let rep: FakeCloud;+let A = "";+let B = "";+let C = "";+beforeAll(async () => {+ fal = await startFakeFal();+ rep = await startFakeReplicate();+ globalThis.__fuobeTestFalUrl = fal.url;+ globalThis.__fuobeTestReplicateUrl = rep.url;+ // Every key works at the stand-ins, the owner's too: a leak would succeed, and the log would show it.+ for (const k of ["owner-fal-db", "owner-fal-env", "owner-fal-env-id:owner-fal-env-secret", "owner-cand", "acct-fal-A", "acct-fal-B"]) fal.keys[k] = "good";+ for (const k of ["owner-rep-db", "owner-rep-env", "acct-rep-A"]) 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;+ keys.saveAccountKey(A, "fal", "acct-fal-A");+ keys.saveAccountKey(A, "replicate", "acct-rep-A");+ keys.saveAccountKey(B, "fal", "acct-fal-B");+});+afterAll(async () => {+ globalThis.__fuobeTestFalUrl = undefined;+ globalThis.__fuobeTestReplicateUrl = undefined;+ await fal.close();+ await rep.close();+ try {+ fs.rmSync(dir, { recursive: true, force: true });+ } catch {}+});+beforeEach(() => {+ fal.log.length = 0;+ rep.log.length = 0;+});++const model = { id: "m", name: "M", kind: "image", engine: "cloud", routes: [] } as unknown as ModelDef;+const falRoute = { op: "text-to-image", provider: "fal", endpoint: "fal-ai/nano-banana-pro/edit", map: { prompt: "prompt" } } as unknown as ModelRoute;+const repRoute = { op: "text-to-image", provider: "replicate", endpoint: "google/nano-banana-pro", map: { prompt: "prompt" } } as unknown as ModelRoute;+const repVersion = { ...repRoute, endpoint: "someone/model:0123abcd" } as ModelRoute;+const input = { prompt: "a quiet harbour at dawn" };+const BIG = Buffer.alloc(1_100_000, 7);++const asAccount = <T,>(id: string, fn: () => T) => runAsTenant({ kind: "account", id }, fn);+const asGuest = <T,>(fn: () => T) => runAsTenant({ kind: "guest" }, fn);++/** Every fal.ai call site: upload, submit, status and result, cancel, the key check. */+async function everyFalCall() {+ const file = await falProvider.prepareFile(Buffer.from("png"), "image/png", "in.png");+ const job = await falProvider.submit({ generationId: "g", model, route: falRoute, input: { ...input, images: [file] } });+ const ctx = { externalId: job.externalId, meta: job.meta ?? {}, route: falRoute, model, createdAt: 0 };+ for (let i = 0; i < 3; i++) await falProvider.poll(ctx);+ await falProvider.cancel!(ctx);+ expect((await falProvider.test!()).ok).toBe(true);+}++/** Every Replicate call site: a file over 1 MB, both forms of submit, poll, cancel, the token check. */+async function everyReplicateCall() {+ await replicateProvider.prepareFile(BIG, "image/png", "in.png");+ await replicateProvider.submit({ generationId: "g", model, route: repVersion, input });+ const job = await replicateProvider.submit({ generationId: "g", model, route: repRoute, input });+ const ctx = { externalId: job.externalId, meta: {}, route: repRoute, model, createdAt: 0 };+ for (let i = 0; i < 3; i++) await replicateProvider.poll(ctx);+ await replicateProvider.cancel!(ctx);+ expect((await replicateProvider.test!()).ok).toBe(true);+}++describe("an account's work sends only its own key", () => {+ it("fal.ai: every call carries the account's key (none on the file's upload address)", async () => {+ await asAccount(A, everyFalCall);+ const keyed = fal.log.filter((r) => !r.path.startsWith("/upload/"));+ expect(keysSeen(keyed)).toEqual(["Key acct-fal-A"]);+ expect(fal.log.filter((r) => r.path.startsWith("/upload/")).map((r) => r.authorization)).toEqual([undefined]);+ expect(fal.log.map((r) => `${r.method} ${r.path.split("?")[0]}`)).toEqual(+ expect.arrayContaining(["POST /storage/upload/initiate", "POST /fal-ai/nano-banana-pro/edit", "PUT /fal-ai/nano-banana-pro/requests/fal-2/cancel"]),+ );+ });++ it("Replicate: every call carries the account's token", async () => {+ await asAccount(A, everyReplicateCall);+ expect(rep.log.length).toBeGreaterThanOrEqual(8);+ expect(keysSeen(rep.log)).toEqual(["Bearer acct-rep-A"]);+ });++ it("another account sends its own key, and nothing for a provider it has no key for", async () => {+ await asAccount(B, everyFalCall);+ expect(keysSeen(fal.log.filter((r) => !r.path.startsWith("/upload/")))).toEqual(["Key acct-fal-B"]);+ asAccount(B, () => expect(replicateProvider.isConfigured()).toBe(false));+ await expect(asAccount(B, () => replicateProvider.submit({ generationId: "g", model, route: repRoute, input }))).rejects.toThrow(/Add your Replicate key/);+ expect(rep.log).toEqual([]);+ });++ it("an account without a key, and a guest, send nothing at all", async () => {+ for (const run of [<T,>(fn: () => T) => asAccount(C, fn), asGuest]) {+ run(() => expect([falProvider.isConfigured(), replicateProvider.isConfigured()]).toEqual([false, false]));+ await expect(run(() => falProvider.prepareFile(Buffer.from("png"), "image/png", "in.png"))).rejects.toThrow();+ await expect(run(() => falProvider.submit({ generationId: "g", model, route: falRoute, input }))).rejects.toThrow();+ await expect(run(() => falProvider.poll({ externalId: "x", meta: { statusUrl: `${fal.url}/fal-ai/x/requests/x/status` }, route: falRoute, model, createdAt: 0 }))).rejects.toThrow();+ await expect(run(() => replicateProvider.submit({ generationId: "g", model, route: repRoute, input }))).rejects.toThrow();+ await expect(run(() => replicateProvider.prepareFile(BIG, "image/png", "in.png"))).rejects.toThrow();+ expect((await run(() => falProvider.test!())).ok).toBe(false);+ }+ expect(fal.log).toEqual([]);+ expect(rep.log).toEqual([]);+ });++ it("an unsaved value never stands in for an account's key (an empty one would fall through to FAL_KEY)", async () => {+ await asAccount(A, () => withCandidates({ falKey: "" }, () => falProvider.submit({ generationId: "g", model, route: falRoute, input })));+ await asAccount(A, () => withCandidates({ falKey: "owner-cand" }, () => falProvider.submit({ generationId: "g", model, route: falRoute, input })));+ await asAccount(C, () => withCandidates({ falKey: "owner-cand" }, () => expect(falProvider.isConfigured()).toBe(false)));+ expect(keysSeen(fal.log)).toEqual(["Key acct-fal-A"]);+ });++ it("a key this server can't open is no key (never the studio's)", async () => {+ const saved = auth.accountKeyRecord(B, "fal")!;+ // One character of its IV changed: it no longer opens.+ const [v, iv, ...rest] = saved.sealed.split(".");+ auth.setAccountKey(B, "fal", { ...saved, sealed: [v, (iv[0] === "A" ? "B" : "A") + iv.slice(1), ...rest].join(".") });+ try {+ asAccount(B, () => expect(falProvider.isConfigured()).toBe(false));+ await expect(asAccount(B, () => falProvider.submit({ generationId: "g", model, route: falRoute, input }))).rejects.toThrow(/Add your fal\.ai key/);+ expect(fal.log).toEqual([]);+ } finally {+ auth.setAccountKey(B, "fal", saved);+ }+ });+});++describe("the owner's work is as before", () => {+ it("sends the studio's key from Settings (and a Save & test value), never an account's", async () => {+ await everyFalCall();+ await everyReplicateCall();+ expect(keysSeen(fal.log.filter((r) => !r.path.startsWith("/upload/")))).toEqual(["Key owner-fal-db"]);+ expect(keysSeen(rep.log)).toEqual(["Bearer owner-rep-db"]);+ fal.log.length = 0;+ await withCandidates({ falKey: "owner-cand" }, () => falProvider.submit({ generationId: "g", model, route: falRoute, input }));+ expect(keysSeen(fal.log)).toEqual(["Key owner-cand"]);+ // Training's queue is fal.ai's (the stand-in here) and goes through the same key.+ expect(falQueueUrl("fal-ai/flux-lora-portrait-trainer")).toBe(`${falQueue()}/fal-ai/flux-lora-portrait-trainer`);+ });++ it("falls back to the environment's key when Settings has none", async () => {+ setSetting("falKey", "");+ try {+ await falProvider.submit({ generationId: "g", model, route: falRoute, input });+ expect(keysSeen(fal.log)).toEqual(["Key owner-fal-env"]);+ } finally {+ setSetting("falKey", "owner-fal-db");+ }+ });+});++describe("overlapping calls keep their own keys", () => {+ it("owner, A and B submitting and polling at once: each request carries only its own key", async () => {+ let release!: () => void;+ fal.holdSubmits = new Promise<void>((r) => (release = r));+ const submitAs = (who: string | null) => {+ const go = () => falProvider.submit({ generationId: who ?? "owner", model, route: falRoute, input: { prompt: `from ${who ?? "owner"}` } });+ return who ? asAccount(who, go) : go();+ };+ const pending = [submitAs(A), submitAs(null), submitAs(B), submitAs(A), submitAs(null), submitAs(B)];+ // Every submit is in flight at the stand-in before any answers.+ while (fal.log.length < pending.length) await new Promise((r) => setTimeout(r, 5));+ release();+ fal.holdSubmits = null;+ const jobs = await Promise.all(pending);+ const who = [A, null, B, A, null, B];+ await Promise.all(+ jobs.map((j, i) => {+ const poll = () => falProvider.poll({ externalId: j.externalId, meta: j.meta ?? {}, route: falRoute, model, createdAt: 0 });+ return who[i] ? asAccount(who[i]!, poll) : poll();+ }),+ );+ const expected = { [`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(expected[JSON.parse(r.body).prompt as string]);+ expect(new Set(fal.log.map((r) => r.authorization))).toEqual(new Set(["Key acct-fal-A", "Key owner-fal-db", "Key acct-fal-B"]));+ });+});++describe("a key goes to its provider's own hosts only", () => {+ it("refuses a status or cancel address outside fal.ai, and a Replicate address outside Replicate", async () => {+ 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.startsWith("http://127.0.0.1")) {+ elsewhere.push(url);+ return new Response("{}", { status: 200 });+ }+ return real(u, init);+ }) as typeof fetch;+ try {+ const evil = { statusUrl: "https://collector.example/fal/status", responseUrl: "https://collector.example/fal", cancelUrl: "https://collector.example/fal/cancel" };+ const ctx = { externalId: "x", meta: evil, route: falRoute, model, createdAt: 0 };+ await expect(asAccount(A, () => falProvider.poll(ctx))).rejects.toThrow(/outside fal\.ai/);+ await expect(falProvider.poll(ctx)).rejects.toThrow(/outside fal\.ai/);+ await asAccount(A, () => falProvider.cancel!(ctx));+ expect(elsewhere).toEqual([]);+ } finally {+ globalThis.fetch = real;+ }+ });+});diff --git a/tests/account-keys-redaction.test.ts b/tests/account-keys-redaction.test.tsnew file mode 100644index 00000000..e8326c3d--- /dev/null+++ b/tests/account-keys-redaction.test.ts@@ -0,0 +1,125 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import type { ModelDef, ModelRoute } from "@/lib/catalog/types";+import { startFakeFal, startFakeReplicate, type FakeCloud } from "./helpers/fake-cloud";++/**+ * Your keys: a key never shows up in an error. The stand-ins here refuse with a body that repeats the request's+ * Authorization header (as some proxies do): the message Fuobe keeps holds neither the key nor either half of a fal.ai+ * key_id:key_secret. An account's refused key, or empty balance, is said the way to fix it.+ */+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-keys-redaction-"));+process.env.FUOBE_DATA_DIR = dir;+delete process.env.FUOBE_PASSWORD;++const auth = await import("@/server/auth");+const keys = await import("@/server/account-keys");+const { setSetting } = await import("@/server/settings");+const { runAsTenant } = await import("@/server/tenant");+const { falProvider } = await import("@/server/providers/fal");+const { replicateProvider } = await import("@/server/providers/replicate");+const { redactKey } = await import("@/server/provider-keys");++const ECHO_FAL = "echo-key-id-1234:echo-key-secret-5678";+const ECHO_REP = "r8_echoTokenThatLeaks";+const BROKE_FAL = "broke-key-id-9999:broke-key-secret-0000";++let fal: FakeCloud;+let rep: FakeCloud;+let A = "";+beforeAll(async () => {+ fal = await startFakeFal();+ rep = await startFakeReplicate();+ globalThis.__fuobeTestFalUrl = fal.url;+ globalThis.__fuobeTestReplicateUrl = rep.url;+ fal.keys[ECHO_FAL] = "echo";+ fal.keys[BROKE_FAL] = "broke";+ rep.keys[ECHO_REP] = "echo";+ rep.keys["r8_brokeToken"] = "broke";+ auth.setPassword("install password");+ A = auth.createAccount("[email protected]", "long enough").id;+});+afterAll(async () => {+ globalThis.__fuobeTestFalUrl = undefined;+ globalThis.__fuobeTestReplicateUrl = undefined;+ await fal.close();+ await rep.close();+ try {+ fs.rmSync(dir, { recursive: true, force: true });+ } catch {}+});++const model = { id: "m", name: "M", kind: "image", engine: "cloud", routes: [] } as unknown as ModelDef;+const falRoute = { op: "text-to-image", provider: "fal", endpoint: "fal-ai/flux/dev", map: { prompt: "prompt" } } as unknown as ModelRoute;+const repRoute = { op: "text-to-image", provider: "replicate", endpoint: "black-forest-labs/flux-dev", map: { prompt: "prompt" } } as unknown as ModelRoute;+const input = { prompt: "x" };++const failure = async (fn: () => Promise<unknown>) => {+ try {+ await fn();+ } catch (e) {+ return (e as Error).message;+ }+ throw new Error("expected a failure");+};+const clean = (text: string, key: string) => {+ expect(text).not.toContain(key);+ for (const half of key.split(":")) expect(text).not.toContain(half);+};++describe("a key never shows up in an error", () => {+ it("redacts the key and each half of a fal.ai key", () => {+ expect(redactKey(`Key ${ECHO_FAL} and echo-key-secret-5678 alone`, ECHO_FAL)).toBe("Key •••• and •••• alone");+ expect(redactKey("nothing here", "")).toBe("nothing here");+ });++ it("the owner's refused key: the error is kept, the key isn't", async () => {+ setSetting("falKey", ECHO_FAL);+ setSetting("replicateToken", ECHO_REP);+ try {+ const f = await failure(() => falProvider.submit({ generationId: "g", model, route: falRoute, input }));+ expect(f).toMatch(/^fal 401: Invalid credentials: Key ••••/);+ clean(f, ECHO_FAL);+ const r = await failure(() => replicateProvider.submit({ generationId: "g", model, route: repRoute, input }));+ expect(r).toMatch(/^replicate 401: Invalid credentials: Bearer ••••/);+ clean(r, ECHO_REP);+ const check = await falProvider.test!();+ clean(check.detail, ECHO_FAL);+ const repCheck = await replicateProvider.test!();+ expect(repCheck.ok).toBe(false);+ clean(repCheck.detail, ECHO_REP);+ } finally {+ setSetting("falKey", "");+ setSetting("replicateToken", "");+ }+ });++ it("an account's refused key: said the way to fix it, and Settings says the provider stopped accepting it", async () => {+ keys.saveAccountKey(A, "fal", ECHO_FAL);+ keys.saveAccountKey(A, "replicate", ECHO_REP);+ const f = await runAsTenant({ kind: "account", id: A }, () => failure(() => falProvider.submit({ generationId: "g", model, route: falRoute, input })));+ expect(f).toBe("fal.ai didn't accept your key. Check it in Settings → Your keys.");+ const r = await runAsTenant({ kind: "account", id: A }, () => failure(() => replicateProvider.submit({ generationId: "g", model, route: repRoute, input })));+ expect(r).toBe("Replicate didn't accept your key. Check it in Settings → Your keys.");+ expect(keys.accountKeyInfo(A).fal?.rejectedAt).toEqual(expect.any(Number));+ expect(keys.accountKeyInfo(A).replicate?.rejectedAt).toEqual(expect.any(Number));+ // A poll that is refused fails with the same words.+ const poll = await runAsTenant({ kind: "account", id: A }, () =>+ failure(() => falProvider.poll({ externalId: "x", meta: { statusUrl: `${fal.url}/fal-ai/flux/requests/x/status` }, route: falRoute, model, createdAt: 0 })),+ );+ expect(poll).toMatch(/didn't accept your key/);+ });++ it("an account's empty balance: top it up", async () => {+ keys.saveAccountKey(A, "fal", BROKE_FAL);+ keys.saveAccountKey(A, "replicate", "r8_brokeToken");+ const f = await runAsTenant({ kind: "account", id: A }, () => failure(() => falProvider.submit({ generationId: "g", model, route: falRoute, input })));+ expect(f).toBe("Your fal.ai balance has run out. Top it up on fal.ai, then run again.");+ const r = await runAsTenant({ kind: "account", id: A }, () => failure(() => replicateProvider.submit({ generationId: "g", model, route: repRoute, input })));+ expect(r).toBe("Your Replicate balance has run out. Top it up on Replicate, then run again.");+ // An empty balance isn't a refused key.+ expect(keys.accountKeyInfo(A).fal?.rejectedAt).toBeUndefined();+ });+});diff --git a/tests/byo-keys-static.test.ts b/tests/byo-keys-static.test.tsnew file mode 100644index 00000000..b4ca85a1--- /dev/null+++ b/tests/byo-keys-static.test.ts@@ -0,0 +1,67 @@+import fs from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";++/**+ * Your keys: only one place reads a fal.ai key or Replicate token (src/server/provider-keys.ts cloudKey), so inside an+ * account's work no other code path can reach the studio's keys. A scan of the source, so a change that adds another+ * way in fails here first.+ */+const SRC = path.resolve(__dirname, "../src");++function files(dir = SRC): string[] {+ return fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => {+ const f = path.join(dir, e.name);+ return e.isDirectory() ? files(f) : /\.(ts|tsx)$/.test(e.name) ? [f] : [];+ });+}++const rel = (f: string) => path.relative(SRC, f).split(path.sep).join("/");+const sources = files().map((f) => ({ file: rel(f), text: fs.readFileSync(f, "utf8") }));+/** The source without its comments, so a comment that names a host or a variable doesn't count. */+const code = (text: string) => text.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:"'`])\/\/.*$/gm, "$1");++/** The files (outside `allowed`) whose code matches `re`. */+const offenders = (re: RegExp, allowed: string[]) => sources.filter((s) => !allowed.includes(s.file) && re.test(code(s.text))).map((s) => s.file);++describe("nothing else reads the studio's fal.ai or Replicate key", () => {+ it("reads the settings only in provider-keys.ts", () => {+ expect(offenders(/\b(getSetting|savedSetting)\(\s*["'`](falKey|replicateToken)["'`]/, ["server/provider-keys.ts"])).toEqual([]);+ expect(offenders(/\b(getSetting|savedSetting)\([^)]*["'`](falKey|replicateToken)["'`]/, ["server/provider-keys.ts"])).toEqual([]);+ // The one read there is the owner's branch of cloudKey.+ const pk = code(sources.find((s) => s.file === "server/provider-keys.ts")!.text);+ expect(pk.match(/getSetting\(/g)).toHaveLength(1);+ });++ it("names the environment's keys only in settings.ts", () => {+ expect(offenders(/\b(FAL_KEY|FAL_KEY_ID|FAL_KEY_SECRET|REPLICATE_API_TOKEN)\b/, ["server/settings.ts"])).toEqual([]);+ });++ it("makes the fal client only in fal.ts, always with a key, and never uses its default instance", () => {+ expect(offenders(/createFalClient\s*\(/, ["server/providers/fal.ts"])).toEqual([]);+ const fal = code(sources.find((s) => s.file === "server/providers/fal.ts")!.text);+ const calls = [...fal.matchAll(/createFalClient\s*\(\s*\{([^}]*)\}/g)];+ expect(calls.length).toBeGreaterThan(0);+ for (const c of calls) expect(c[1]).toMatch(/credentials:\s*k\b/);+ expect(offenders(/from\s+["']@fal-ai\/client["']/, ["server/providers/fal.ts"])).toEqual([]);+ expect(fal).not.toMatch(/import\s*\{[^}]*\bfal\b[^}]*\}\s*from\s*["']@fal-ai\/client["']/);+ });++ it("names fal.ai's and Replicate's API hosts only in their adapters", () => {+ expect(offenders(/queue\.fal\.run|rest\.fal\.ai|api\.replicate\.com/, ["server/providers/fal.ts", "server/providers/replicate.ts"])).toEqual([]);+ expect(offenders(/`Key \$\{/, ["server/providers/fal.ts"])).toEqual([]);+ });++ it("reads keys in the adapters only through cloudKey", () => {+ for (const f of ["server/providers/fal.ts", "server/providers/replicate.ts", "server/training.ts"]) {+ const text = code(sources.find((s) => s.file === f)!.text);+ expect(text, f).not.toMatch(/getSetting\(\s*["'`](falKey|replicateToken)/);+ }+ expect(code(sources.find((s) => s.file === "server/providers/fal.ts")!.text)).toMatch(/cloudKey\("fal"\)/);+ expect(code(sources.find((s) => s.file === "server/providers/replicate.ts")!.text)).toMatch(/cloudKey\("replicate"\)/);+ });++ 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([]);+ });+});diff --git a/tests/helpers/fake-cloud.ts b/tests/helpers/fake-cloud.tsnew file mode 100644index 00000000..4d55449a--- /dev/null+++ b/tests/helpers/fake-cloud.ts@@ -0,0 +1,162 @@+import http from "node:http";++/**+ * Stand-in fal.ai and Replicate servers on 127.0.0.1, for Your keys (an account's own key). Every request is logged+ * with the Authorization header it carried, so a test can prove which key reached the provider, and that the studio's+ * never did for an account. No real key, no paid call. Plain Node and type annotations only, so a smoke script can run+ * it with `node --experimental-strip-types`.+ *+ * What a key gets is scripted per key: "good" (works), "broke" (its balance has run out), "echo" (refused, and the+ * error repeats the request's Authorization header, like a proxy that echoes it). Any other key is refused (401).+ */++export type KeyMode = "good" | "broke" | "echo";++export interface CloudRequest {+ method: string;+ path: string;+ authorization?: string;+ body: string;+}++export interface FakeCloud {+ url: string;+ port: number;+ log: CloudRequest[];+ keys: Record<string, KeyMode>;+ /** Polls a job answers queued/running before it finishes (default 2); Infinity: it never finishes. */+ pollsToFinish: number;+ /** While set, the provider holds every submit until it resolves (a slow hand-over). */+ holdSubmits: Promise<void> | null;+ /** The jobs it was asked to cancel. */+ canceled: string[];+ close(): Promise<void>;+}++/** A 1×1 PNG: what every fake job makes (a data: URI, so an account's result is saved without a download). */+export const PNG_DATA_URI =+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==";++const json = (res: http.ServerResponse, status: number, body: unknown) => {+ res.writeHead(status, { "Content-Type": "application/json" });+ res.end(JSON.stringify(body));+};++async function start(handle: (fake: FakeCloud, req: CloudRequest, res: http.ServerResponse, key: string | null) => Promise<void> | void, scheme: "Key" | "Bearer", port = 0): Promise<FakeCloud> {+ const fake = { log: [], keys: {}, pollsToFinish: 2, holdSubmits: null, canceled: [] } as unknown as FakeCloud;+ const server = http.createServer((req, res) => {+ const chunks: Buffer[] = [];+ req.on("data", (c: Buffer) => chunks.push(c));+ req.on("end", () => {+ const r: CloudRequest = { method: req.method ?? "GET", path: req.url ?? "/", authorization: req.headers.authorization, body: Buffer.concat(chunks).toString("latin1") };+ fake.log.push(r);+ const m = new RegExp(`^${scheme} (.+)$`).exec(r.authorization ?? "");+ Promise.resolve(handle(fake, r, res, m ? m[1] : null)).catch((e) => json(res, 500, { detail: String(e) }));+ });+ });+ await new Promise<void>((resolve) => server.listen(port, "127.0.0.1", resolve));+ const addr = server.address() as { port: number };+ fake.port = addr.port;+ fake.url = `http://127.0.0.1:${addr.port}`;+ fake.close = () =>+ new Promise<void>((resolve) => {+ server.closeAllConnections?.();+ server.close(() => resolve());+ });+ return fake;+}++/** Refuse a request whose key isn't "good": 401, or 403 for an empty balance, or a 401 that echoes the header. */+function refused(fake: FakeCloud, r: CloudRequest, res: http.ServerResponse, key: string | null, broke: { status: number; detail: string }): boolean {+ const mode = key ? fake.keys[key] : undefined;+ if (mode === "good") return false;+ if (mode === "broke") json(res, broke.status, { detail: broke.detail });+ else if (mode === "echo") json(res, 401, { detail: `Invalid credentials: ${r.authorization}` });+ else json(res, 401, { detail: "Unauthorized" });+ return true;+}++const ZERO = "00000000-0000-0000-0000-000000000000";++/** fal.ai: the queue (submit, status, result, cancel) and the REST API's storage upload, on one origin. */+export function startFakeFal(port = 0): Promise<FakeCloud> {+ let n = 0;+ const polls = new Map<string, number>();+ return start(+ async (fake, r, res, key) => {+ const path = r.path.split("?")[0];+ // A file's upload address: the client sends no key there.+ if (r.method === "PUT" && path.startsWith("/upload/")) return json(res, 200, {});+ if (refused(fake, r, res, key, { status: 403, detail: "User is locked. Reason: Exhausted balance. Top up your balance at fal.ai/dashboard/billing." })) return;+ if (path === `/fal-ai/flux/dev/requests/${ZERO}/status`) return json(res, 404, { detail: "Request not found" });+ if (r.method === "POST" && path === "/storage/upload/initiate") {+ const id = ++n;+ return json(res, 200, { upload_url: `${fake.url}/upload/${id}`, file_url: `${fake.url}/files/${id}` });+ }+ const job = /^\/(.+)\/requests\/([^/]+)(\/status|\/cancel)?$/.exec(path);+ if (job) {+ const [, , id, tail] = job;+ if (tail === "/cancel" && r.method === "PUT") {+ fake.canceled.push(id);+ return json(res, 202, { status: "CANCELLATION_REQUESTED" });+ }+ if (tail === "/status") {+ const seen = (polls.get(id) ?? 0) + 1;+ polls.set(id, seen);+ if (seen > fake.pollsToFinish) return json(res, 200, { status: "COMPLETED", logs: [] });+ return json(res, 200, seen === 1 ? { status: "IN_QUEUE", queue_position: 0 } : { status: "IN_PROGRESS", logs: [{ message: "50%" }] });+ }+ return json(res, 200, { images: [{ url: PNG_DATA_URI, content_type: "image/png" }] });+ }+ if (r.method === "POST") {+ if (fake.holdSubmits) await fake.holdSubmits;+ const id = `fal-${++n}`;+ // fal's status paths drop an endpoint's sub-path: the app's first two parts.+ const app = path.split("/").slice(1, 3).join("/");+ const base = `${fake.url}/${app}/requests/${id}`;+ return json(res, 200, { request_id: id, status_url: `${base}/status`, response_url: base, cancel_url: `${base}/cancel` });+ }+ json(res, 404, { detail: "Not found" });+ },+ "Key",+ port,+ );+}++/** Replicate: predictions (both forms), polls, cancels, files and the account check. */+export function startFakeReplicate(port = 0): Promise<FakeCloud> {+ let n = 0;+ const polls = new Map<string, number>();+ return start(+ async (fake, r, res, key) => {+ const path = r.path.split("?")[0];+ if (refused(fake, r, res, key, { status: 402, detail: "You have insufficient credit to run this model. Go to https://replicate.com/account/billing to purchase credit." })) return;+ if (r.method === "GET" && path === "/v1/account") return json(res, 200, { type: "user", username: "alice" });+ if (r.method === "POST" && path === "/v1/files") return json(res, 201, { id: `file-${++n}`, urls: { get: `${fake.url}/v1/files/file-${n}` } });+ const cancel = /^\/v1\/predictions\/([^/]+)\/cancel$/.exec(path);+ if (cancel && r.method === "POST") {+ fake.canceled.push(cancel[1]);+ return json(res, 200, { id: cancel[1], status: "canceled" });+ }+ const one = /^\/v1\/predictions\/([^/]+)$/.exec(path);+ if (one && r.method === "GET") {+ const seen = (polls.get(one[1]) ?? 0) + 1;+ polls.set(one[1], seen);+ if (seen > fake.pollsToFinish) return json(res, 200, { id: one[1], status: "succeeded", output: [PNG_DATA_URI] });+ return json(res, 200, seen === 1 ? { id: one[1], status: "starting" } : { id: one[1], status: "processing", logs: "50%" });+ }+ if (r.method === "POST" && (path === "/v1/predictions" || /^\/v1\/models\/[^/]+\/[^/]+\/predictions$/.test(path))) {+ if (fake.holdSubmits) await fake.holdSubmits;+ return json(res, 201, { id: `rep-${++n}`, status: "starting" });+ }+ json(res, 404, { detail: "Not found" });+ },+ "Bearer",+ port,+ );+}++/** Every logged request that carried a key carried one of `allowed` (and the log isn't empty when `some` is set). */+export function keysSeen(log: CloudRequest[]): string[] {+ return [...new Set(log.map((r) => r.authorization ?? "(none)"))];+}diff --git a/tests/soul-id-runtime.test.ts b/tests/soul-id-runtime.test.tsindex 8520ce7c..f625cd8e 100644--- a/tests/soul-id-runtime.test.ts+++ b/tests/soul-id-runtime.test.ts@@ -108,7 +108,7 @@ describe("starting a Soul ID training", () => {});it("sends fal a zip of 001.png + 001.txt pairs with the trainer's fields, priced first", async () => {- routes["https://queue.fal.run/fal-ai/z-image-turbo-trainer-v2"] = () => json({ request_id: "req-1", status_url: "https://queue.fal.test/s/1", response_url: "https://queue.fal.test/r/1" });+ routes["https://queue.fal.run/fal-ai/z-image-turbo-trainer-v2"] = () => json({ request_id: "req-1", status_url: "https://queue.fal.run/test/s/1", response_url: "https://queue.fal.run/test/r/1" });const el = character(6);const t = startTraining(el.id, "fal-z-image", { consent: true });await wait(() => listTrainings(el.id)[0].status === "running");@@ -125,7 +125,7 @@ describe("starting a Soul ID training", () => {});it("trains on a non-commercial base too (licences are information): FLUX's portrait trainer gets images_data_url and the trigger", async () => {- routes["https://queue.fal.run/fal-ai/flux-lora-portrait-trainer"] = () => json({ request_id: "req-f", status_url: "https://queue.fal.test/s/f", response_url: "https://queue.fal.test/r/f" });+ routes["https://queue.fal.run/fal-ai/flux-lora-portrait-trainer"] = () => json({ request_id: "req-f", status_url: "https://queue.fal.run/test/s/f", response_url: "https://queue.fal.run/test/r/f" });const el = character(6);const t = startTraining(el.id, "fal-flux1-portrait", { consent: true });await wait(() => listTrainings(el.id)[0].status === "running");@@ -153,10 +153,10 @@ describe("a finished training", () => {it("keeps fal's LoRA (diffusers_lora_file) on the element for the whole family, with Fuobe's own copy", async () => {const LORA = Buffer.from("safetensors-bytes".repeat(100));- routes["https://queue.fal.test/s/2"] = () => json({ status: "COMPLETED" });- routes["https://queue.fal.test/r/2"] = () => json({ diffusers_lora_file: { url: "https://v3.fal.media/files/maya.safetensors" } });+ routes["https://queue.fal.run/test/s/2"] = () => json({ status: "COMPLETED" });+ routes["https://queue.fal.run/test/r/2"] = () => json({ diffusers_lora_file: { url: "https://v3.fal.media/files/maya.safetensors" } });routes["https://v3.fal.media/files/maya.safetensors"] = (c) => (c.method === "HEAD" ? new Response(null, { status: 200 }) : new Response(LORA, { headers: { "content-length": String(LORA.length) } }));- const { id, el } = running({ target: "fal-z-image", provider: "fal", externalId: "req-2", meta: { statusUrl: "https://queue.fal.test/s/2", responseUrl: "https://queue.fal.test/r/2", family: "z-image-turbo" } });+ const { id, el } = running({ target: "fal-z-image", provider: "fal", externalId: "req-2", meta: { statusUrl: "https://queue.fal.run/test/s/2", responseUrl: "https://queue.fal.run/test/r/2", family: "z-image-turbo" } });await pollTrainings();expect(listTrainings(el.id).find((t) => t.id === id)).toMatchObject({ status: "succeeded", message: null });await trainedCopiesSettled();@@ -172,11 +172,11 @@ describe("a finished training", () => {// A retrain on the same family replaces it; Fuobe Soul HD's LoRA would sit beside it.updateElement(el.id, { loras: [...after.loras, { engine: "cloud", modelId: "fuobe-soul-hd", family: "qwen-image-2512", file: "fuobe/hd.safetensors", url: "https://x/hd", trigger: "t" }] });- routes["https://queue.fal.test/s/3"] = () => json({ status: "COMPLETED" });- routes["https://queue.fal.test/r/3"] = () => json({ diffusers_lora_file: { url: "https://v3.fal.media/files/maya.safetensors" } });+ routes["https://queue.fal.run/test/s/3"] = () => json({ status: "COMPLETED" });+ routes["https://queue.fal.run/test/r/3"] = () => json({ diffusers_lora_file: { url: "https://v3.fal.media/files/maya.safetensors" } });db().prepare(`INSERT INTO trainings (id, element_id, target, provider, status, external_id, meta_json, trigger_word, created_at, updated_at) VALUES ('t2xyz', ?, 'fal-z-image', 'fal', 'running', 'r3', ?, 'mayafz', ?, ?)`)- .run(el.id, JSON.stringify({ statusUrl: "https://queue.fal.test/s/3", responseUrl: "https://queue.fal.test/r/3" }), Date.now(), Date.now());+ .run(el.id, JSON.stringify({ statusUrl: "https://queue.fal.run/test/s/3", responseUrl: "https://queue.fal.run/test/r/3" }), Date.now(), Date.now());await pollTrainings();expect(getElement(el.id)!.loras.map((x) => x.family)).toEqual(["qwen-image-2512", "z-image-turbo"]);});@@ -184,12 +184,12 @@ describe("a finished training", () => {it("finishes a fal training without waiting for Fuobe's copy of the LoRA, which follows in the background", async () => {const LORA = Buffer.from("big-lora".repeat(64));let release = () => {};- routes["https://queue.fal.test/s/bg"] = () => json({ status: "COMPLETED" });- routes["https://queue.fal.test/r/bg"] = () => json({ diffusers_lora_file: { url: "https://v3.fal.media/files/bg.safetensors" } });+ routes["https://queue.fal.run/test/s/bg"] = () => json({ status: "COMPLETED" });+ routes["https://queue.fal.run/test/r/bg"] = () => json({ diffusers_lora_file: { url: "https://v3.fal.media/files/bg.safetensors" } });// The download hangs until released: the runner's poll must not wait on it.routes["https://v3.fal.media/files/bg.safetensors"] = (c) =>c.method === "HEAD" ? new Response(null, { status: 200 }) : (new Promise<Response>((resolve) => (release = () => resolve(new Response(LORA, { headers: { "content-length": String(LORA.length) } })))) as unknown as Response);- const { id, el } = running({ target: "fal-flux2-dev", provider: "fal", externalId: "req-bg", meta: { statusUrl: "https://queue.fal.test/s/bg", responseUrl: "https://queue.fal.test/r/bg", family: "flux2-dev" } });+ const { id, el } = running({ target: "fal-flux2-dev", provider: "fal", externalId: "req-bg", meta: { statusUrl: "https://queue.fal.run/test/s/bg", responseUrl: "https://queue.fal.run/test/r/bg", family: "flux2-dev" } });await pollTrainings();expect(listTrainings(el.id).find((t) => t.id === id)).toMatchObject({ status: "succeeded" });expect(getElement(el.id)!.status).toBe("ready");@@ -237,10 +237,10 @@ describe("a finished training", () => {});it("reads Krea 2's LoRA from lora_file and records it for Krea 2's hosted LoRA model", async () => {- routes["https://queue.fal.test/s/k"] = () => json({ status: "COMPLETED" });- routes["https://queue.fal.test/r/k"] = () => json({ lora_file: { url: "https://v3.fal.media/files/krea.safetensors" }, config_file: { url: "https://v3.fal.media/files/c.json" } });+ routes["https://queue.fal.run/test/s/k"] = () => json({ status: "COMPLETED" });+ routes["https://queue.fal.run/test/r/k"] = () => json({ lora_file: { url: "https://v3.fal.media/files/krea.safetensors" }, config_file: { url: "https://v3.fal.media/files/c.json" } });routes["https://v3.fal.media/files/krea.safetensors"] = () => new Response(Buffer.from("krea"), { headers: { "content-length": "4" } });- const { el } = running({ target: "fal-krea-2", provider: "fal", externalId: "req-k", meta: { statusUrl: "https://queue.fal.test/s/k", responseUrl: "https://queue.fal.test/r/k", family: "krea-2" } });+ const { el } = running({ target: "fal-krea-2", provider: "fal", externalId: "req-k", meta: { statusUrl: "https://queue.fal.run/test/s/k", responseUrl: "https://queue.fal.run/test/r/k", family: "krea-2" } });await pollTrainings();const l = getElement(el.id)!.loras[0];expect(l).toMatchObject({ family: "krea-2", modelId: "krea-2-turbo-lora-cloud", url: "https://v3.fal.media/files/krea.safetensors" });