Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Your keys: an encrypted place for an account's own fal.ai and Replicate keys

Adarshb9d61e911f6e
diff --git a/src/lib/your-keys.ts b/src/lib/your-keys.ts
new file mode 100644
index 00000000..d3194fa3
--- /dev/null
+++ b/src/lib/your-keys.ts
@@ -0,0 +1,52 @@
+import { FAL_KEYS_URL } from "./connections";
+
+/**
+ * Your keys (public sign-up): an account's own fal.ai key or Replicate token, so it can run paid models billed to its own
+ * account with that provider, never to the studio (src/server/account-keys.ts, src/server/provider-keys.ts). The names,
+ * links and words the server and the browser share. Never a key.
+ */
+
+export type CloudProvider = "fal" | "replicate";
+
+export const CLOUD_PROVIDERS: readonly CloudProvider[] = ["fal", "replicate"];
+
+export const isCloudProvider = (p: unknown): p is CloudProvider => p === "fal" || p === "replicate";
+
+/** Where to make a Replicate API token. */
+export const REPLICATE_TOKENS_URL = "https://replicate.com/account/api-tokens";
+
+export const CLOUD_KEY: Record<
+ CloudProvider,
+ { label: string; field: string; setting: "falKey" | "replicateToken"; placeholder: string; keysUrl: string; getKey: string; blurb: string }
+> = {
+ fal: { label: "fal.ai", field: "fal.ai API key", setting: "falKey", placeholder: "key_id:key_secret", keysUrl: FAL_KEYS_URL, getKey: "Get a key", blurb: "One key runs almost every paid model." },
+ replicate: { label: "Replicate", field: "Replicate API token", setting: "replicateToken", placeholder: "r8_…", keysUrl: REPLICATE_TOKENS_URL, getKey: "Get a token", blurb: "Hosts some of the same models." },
+};
+
+/** What Settings → Your keys shows of a saved key: never the key itself. */
+export interface KeyInfo {
+ last4: string;
+ addedAt: number;
+ /** False when this server can't open it any more (its server key was lost): add it again. */
+ readable: boolean;
+ /** When the provider refused it in a run. */
+ rejectedAt?: number;
+}
+
+/** GET /api/account/keys. */
+export interface YourKeys {
+ keys: Record<CloudProvider, KeyInfo | null>;
+ /** "both" while it has a usable key and the studio isn't open-source only. */
+ engineMode: "open" | "both";
+ /** The studio lets accounts use paid models with their own keys (it isn't open-source only). */
+ paidAllowed: boolean;
+}
+
+/** Set on an account's refused run (its value: fal or replicate): the client opens "Add your key". */
+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.`;
+export const keyRemovedMessage = (p: CloudProvider) => `Your ${CLOUD_KEY[p].label} key was removed, so this run stopped.`;
+export const OPEN_ONLY_MESSAGE = "This studio runs open-source models only right now, so your keys aren't used.";
diff --git a/src/server/account-keys.ts b/src/server/account-keys.ts
new file mode 100644
index 00000000..c5a9d77c
--- /dev/null
+++ b/src/server/account-keys.ts
@@ -0,0 +1,65 @@
+import "server-only";
+import { CLOUD_PROVIDERS, type CloudProvider, type KeyInfo } from "@/lib/your-keys";
+import { accountKeyRecord, setAccountKey } from "./auth";
+import { accountKeyContext, open, seal } from "./secret-box";
+import { savedSetting } from "./settings";
+
+/**
+ * Your keys (public sign-up): an account's own fal.ai key or Replicate token. Sealed on its record in auth.json
+ * (secret-box.ts, bound to the account and the provider), so it goes with the account. Opened on each use and never
+ * kept in plain text, so a removed or replaced key stops at once. Only provider-keys.ts hands one to a provider call;
+ * nothing here ever returns a key to a browser (accountKeyInfo: the last 4 characters).
+ */
+
+/** The account's key for a provider, opened; null when it has none, or this server can't open it (never another key). */
+export function accountKey(id: string, p: CloudProvider): string | null {
+ const record = accountKeyRecord(id, p);
+ return record ? open(record.sealed, accountKeyContext(id, p)) : null;
+}
+
+/** What Settings → Your keys shows, per provider: never the key. */
+export function accountKeyInfo(id: string): Record<CloudProvider, KeyInfo | null> {
+ const info = (p: CloudProvider): KeyInfo | null => {
+ const r = accountKeyRecord(id, p);
+ return r ? { last4: r.last4, addedAt: r.addedAt, readable: accountKey(id, p) !== null, ...(r.rejectedAt && { rejectedAt: r.rejectedAt }) } : null;
+ };
+ return { fal: info("fal"), replicate: info("replicate") };
+}
+
+/** A key as typed, trimmed; null when it can't be one (empty, spaces inside, too long). The provider has the last word. */
+export function cleanKey(raw: unknown): string | null {
+ const key = typeof raw === "string" ? raw.trim() : "";
+ return /^[\x21-\x7e]{8,300}$/.test(key) ? key : null;
+}
+
+/** Seal and save a key the provider accepted (the caller checks it first). */
+export function saveAccountKey(id: string, p: CloudProvider, key: string): KeyInfo {
+ const stored = { sealed: seal(key, accountKeyContext(id, p)), last4: key.slice(-4), addedAt: Date.now() };
+ setAccountKey(id, p, stored);
+ return { last4: stored.last4, addedAt: stored.addedAt, readable: true };
+}
+
+export function removeAccountKey(id: string, p: CloudProvider): void {
+ setAccountKey(id, p, null);
+}
+
+/** The provider refused the key in a run: Settings says so. Only when `used` is still the saved key (not one replaced since). */
+export function markKeyRejected(id: string, p: CloudProvider, used: string): void {
+ const record = accountKeyRecord(id, p);
+ if (!record || record.rejectedAt || accountKey(id, p) !== used) return;
+ setAccountKey(id, p, { ...record, rejectedAt: Date.now() });
+}
+
+/** The studio lets accounts run paid models on their own keys: it isn't open-source only (Settings → Engine mode). */
+export const paidAllowed = () => savedSetting("engineMode") !== "open";
+
+/** The providers the account has a key for that this server can open. */
+export const accountProviders = (id: string): CloudProvider[] => CLOUD_PROVIDERS.filter((p) => accountKey(id, p) !== null);
+
+/**
+ * The engine mode an account's work runs with: "both" (open models on its own GPU, paid ones on its own keys) while it
+ * has a key this server can open and the studio isn't open-source only; otherwise "open".
+ */
+export function accountEngineMode(id: string): "open" | "both" {
+ return paidAllowed() && accountProviders(id).length > 0 ? "both" : "open";
+}
diff --git a/src/server/auth.ts b/src/server/auth.ts
index b31e6189..580e1d84 100644
--- a/src/server/auth.ts
+++ b/src/server/auth.ts
@@ -6,8 +6,9 @@
* Public sign-up (publicSignup: FUOBE_PUBLIC_SIGNUP=1, Settings → Security, or fuobe.com itself)
* opens a password-protected studio a little: guests may browse it read-only, and anyone may make
* an account (email + password, no verification) whose session works across the app. An account
- * never runs on the owner's cloud keys or GPU, and install-wide settings, keys and tokens stay the
- * owner's (the install password's session, or an API token): src/proxy.ts, src/lib/guest-access.ts.
+ * never runs on the owner's cloud keys or GPU (only on its own GPU, or its own fal.ai or Replicate key),
+ * and install-wide settings, keys and tokens stay the owner's (the install password's session, or an
+ * API token): src/proxy.ts, src/lib/guest-access.ts.
*
* Kept in a small JSON file next to the database, not in SQLite, so the proxy's sign-in check
* needs nothing but `fs` and `crypto`. (The proxy does open SQLite, for one primary-key lookup on
@@ -45,6 +46,18 @@ export type AccountGpu = { mode?: "link"; url: string; token?: string } | { mode
/** A GPU reached at a public address (a link), not the person's own computer. */
export const gpuLink = (gpu: AccountGpu | null | undefined): { url: string; token?: string } | null => (gpu && gpu.mode !== "computer" ? gpu : null);
+/** fal.ai or Replicate: the providers an account may bring its own key for (src/lib/your-keys.ts). */
+export type CloudProvider = "fal" | "replicate";
+
+/** An account's own fal.ai key or Replicate token, sealed (src/server/secret-box.ts): never the key itself. */
+export interface StoredKey {
+ sealed: string;
+ last4: string;
+ addedAt: number;
+ /** The provider refused it in a run. */
+ rejectedAt?: number;
+}
+
/** A signed-up visitor (public sign-up). */
export interface Account {
id: string;
@@ -58,6 +71,8 @@ export interface Account {
/** Switched off by the owner (Settings → Accounts): signed out, and can't log in. */
disabled?: boolean;
gpu?: AccountGpu;
+ /** Its own keys ("Your keys"), sealed: src/server/account-keys.ts opens them. */
+ keys?: Partial<Record<CloudProvider, StoredKey>>;
}
interface AuthFile {
@@ -356,11 +371,15 @@ export interface AccountInfo {
disabled: boolean;
/** Its own ComfyUI is connected ("Your GPU"). */
gpu: boolean;
+ /** The providers it saved its own key for ("Your keys"): never a key. */
+ keys: CloudProvider[];
}
+const keysOf = (a: Pick<Account, "keys">): CloudProvider[] => (["fal", "replicate"] as const).filter((p) => !!a.keys?.[p]);
+
export function listAccounts(): AccountInfo[] {
return (read().accounts ?? [])
- .map((a) => ({ id: a.id, email: a.email, createdAt: a.createdAt, lastLoginAt: a.lastLoginAt ?? null, disabled: !!a.disabled, gpu: !!a.gpu }))
+ .map((a) => ({ id: a.id, email: a.email, createdAt: a.createdAt, lastLoginAt: a.lastLoginAt ?? null, disabled: !!a.disabled, gpu: !!a.gpu, keys: keysOf(a) }))
.sort((a, b) => b.createdAt - a.createdAt);
}
@@ -405,7 +424,10 @@ function csvCell(v: string | number | boolean | null): string {
export function accountsCsv(items = listAccounts()): string {
const iso = (t: number | null) => (t ? new Date(t).toISOString() : null);
- const rows = [["email", "created", "last_login", "gpu_connected", "disabled"], ...items.map((a) => [a.email, iso(a.createdAt), iso(a.lastLoginAt), a.gpu, a.disabled])];
+ const rows = [
+ ["email", "created", "last_login", "gpu_connected", "fal_key", "replicate_key", "disabled"],
+ ...items.map((a) => [a.email, iso(a.createdAt), iso(a.lastLoginAt), a.gpu, a.keys.includes("fal"), a.keys.includes("replicate"), a.disabled]),
+ ];
return rows.map((r) => r.map(csvCell).join(",")).join("\r\n") + "\r\n";
}
@@ -431,6 +453,30 @@ export function setAccountGpu(id: string, gpu: AccountGpu | null): void {
write({ ...d, accounts: d.accounts.map((a) => (a.id !== id ? a : gpu ? { ...a, gpu: kept(gpu) } : withoutGpu(a))) });
}
+/** It saved a key of its own for fal.ai or Replicate (whether this server can still open it is account-keys.ts's to say). */
+export const hasCloudKey = (a: Pick<Account, "keys">): boolean => !!(a.keys?.fal || a.keys?.replicate);
+
+/** The account's sealed key for a provider, switched off or not (its runs still finish or stop on it), or null. */
+export const accountKeyRecord = (id: string, p: CloudProvider): StoredKey | null => accountById(id)?.keys?.[p] ?? null;
+
+/** Save (or with null, forget) the account's own key for a provider, sealed by the caller (src/server/account-keys.ts). */
+export function setAccountKey(id: string, p: CloudProvider, key: StoredKey | null): void {
+ const d = read();
+ if (!d.accounts?.some((a) => a.id === id)) throw new AccountError("No such account", 404);
+ write({
+ ...d,
+ accounts: d.accounts.map((a) => {
+ if (a.id !== id) return a;
+ const keys = { ...a.keys };
+ if (key) keys[p] = { sealed: key.sealed, last4: key.last4, addedAt: key.addedAt, ...(key.rejectedAt && { rejectedAt: key.rejectedAt }) };
+ else delete keys[p];
+ const copy: Account = { ...a, keys };
+ if (!keys.fal && !keys.replicate) delete copy.keys;
+ return copy;
+ }),
+ });
+}
+
/** Who is asking: the owner (also everyone while no password is set), an account (public sign-up on), or a guest. */
export type RequestViewer = { kind: "owner" } | { kind: "account"; account: Account } | { kind: "guest" };
diff --git a/src/server/secret-box.ts b/src/server/secret-box.ts
new file mode 100644
index 00000000..4d10864d
--- /dev/null
+++ b/src/server/secret-box.ts
@@ -0,0 +1,110 @@
+import "server-only";
+import crypto from "node:crypto";
+import fs from "node:fs";
+import path from "node:path";
+import { DATA_DIR } from "./db";
+
+/**
+ * Secrets sealed at rest: an account's own fal.ai key or Replicate token (src/server/account-keys.ts). AES-256-GCM under a
+ * server key in data/secrets.key: 32 random bytes made the first time something is sealed, never derived from the
+ * sign-in secret (a new password or "Sign everyone out" leaves sealed values readable). Each value is bound to its
+ * context (the account and the provider), so a sealed value copied to another account or provider doesn't open.
+ *
+ * Fails closed: a key file that can't be read or isn't a key seals nothing and opens nothing, and is never written
+ * over. Back it up with auth.json: without it, the saved keys must be added again.
+ */
+
+const VERSION = "v1";
+
+export class SecretBoxError extends Error {}
+
+/** What an account's key is sealed for: that account and that provider. */
+export const accountKeyContext = (accountId: string, provider: string) => `fuobe:account-key:v1:${accountId}:${provider}`;
+
+declare global {
+ /** The server key as last read, by the file's path and modification time (dev reloads share it). */
+ var __fuobeSecretKey: { file: string; mtimeMs: number; key: Buffer } | undefined;
+ var __fuobeSecretKeyWarned: number | undefined;
+}
+
+const keyFile = () => path.join(DATA_DIR, "secrets.key");
+
+function warnBroken(file: string, why: string): void {
+ if (Date.now() - (globalThis.__fuobeSecretKeyWarned ?? 0) < 60 * 60_000) return;
+ globalThis.__fuobeSecretKeyWarned = Date.now();
+ console.warn(`[fuobe] ${file} isn't a usable key (${why}): accounts' saved keys can't be opened or saved until it is restored.`);
+}
+
+/** The server key: null when there is none yet, or the file is broken (warned). */
+function readKey(): Buffer | null {
+ const file = keyFile();
+ let mtimeMs: number;
+ try {
+ mtimeMs = fs.statSync(file).mtimeMs;
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code !== "ENOENT") warnBroken(file, (e as NodeJS.ErrnoException).code ?? "can't be read");
+ return null;
+ }
+ const cached = globalThis.__fuobeSecretKey;
+ if (cached?.file === file && cached.mtimeMs === mtimeMs) return cached.key;
+ let hex: string;
+ try {
+ hex = fs.readFileSync(file, "utf8").trim();
+ } catch (e) {
+ warnBroken(file, (e as NodeJS.ErrnoException).code ?? "can't be read");
+ return null;
+ }
+ if (!/^[0-9a-f]{64}$/i.test(hex)) {
+ warnBroken(file, "not 64 hex characters");
+ return null;
+ }
+ const key = Buffer.from(hex, "hex");
+ globalThis.__fuobeSecretKey = { file, mtimeMs, key };
+ return key;
+}
+
+/** The server key, made once when there is no file yet. Throws when the file is there but broken. */
+function keyForSealing(): Buffer {
+ const key = readKey();
+ if (key) return key;
+ const file = keyFile();
+ if (fs.existsSync(file)) throw new SecretBoxError("Keys can't be saved on this studio right now. Try again later.");
+ fs.mkdirSync(DATA_DIR, { recursive: true });
+ try {
+ // "wx": only when no other process made it first; then that one is read.
+ fs.writeFileSync(file, crypto.randomBytes(32).toString("hex"), { flag: "wx", mode: 0o600 });
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code !== "EEXIST") throw new SecretBoxError("Keys can't be saved on this studio right now. Try again later.");
+ }
+ const made = readKey();
+ if (!made) throw new SecretBoxError("Keys can't be saved on this studio right now. Try again later.");
+ return made;
+}
+
+/** Seal a value for a context: "v1.<iv>.<tag>.<ciphertext>" (base64url). */
+export function seal(plain: string, context: string): string {
+ const key = keyForSealing();
+ const iv = crypto.randomBytes(12);
+ const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
+ cipher.setAAD(Buffer.from(context));
+ const ct = Buffer.concat([cipher.update(plain, "utf8"), cipher.final()]);
+ return [VERSION, iv.toString("base64url"), cipher.getAuthTag().toString("base64url"), ct.toString("base64url")].join(".");
+}
+
+/** The value sealed for this context, or null: another context, a changed value, no server key or a broken one. */
+export function open(sealed: string, context: string): string | null {
+ const parts = sealed.split(".");
+ if (parts.length !== 4 || parts[0] !== VERSION) return null;
+ const key = readKey();
+ if (!key) return null;
+ try {
+ const [, iv, tag, ct] = parts.map((p, i) => (i ? Buffer.from(p, "base64url") : Buffer.alloc(0)));
+ if (iv.length !== 12 || tag.length !== 16) return null;
+ const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
+ decipher.setAAD(Buffer.from(context));
+ decipher.setAuthTag(tag);
+ return Buffer.concat([decipher.update(ct), decipher.final()]).toString("utf8");
+ } catch {
+ return null;
+ }
+}
diff --git a/tests/account-keys.test.ts b/tests/account-keys.test.ts
new file mode 100644
index 00000000..d3e10407
--- /dev/null
+++ b/tests/account-keys.test.ts
@@ -0,0 +1,132 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+/**
+ * Your keys: where an account's own fal.ai key or Replicate token is kept. Sealed on its record in auth.json, never in
+ * plain text in any file of the data folder, shown only by its last 4 characters, gone with the account.
+ */
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-account-keys-"));
+process.env.FUOBE_DATA_DIR = dir;
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_ENGINE_MODE;
+
+const auth = await import("@/server/auth");
+const keys = await import("@/server/account-keys");
+const { setSetting } = await import("@/server/settings");
+
+const FAL = "acct-fal-key-id:acct-fal-secret-9f3a";
+const REP = "r8_acctReplicateToken7c21";
+
+/** Every file in the data folder, as raw bytes. */
+function dataFiles(): { file: string; text: string }[] {
+ const out: { file: string; text: string }[] = [];
+ const walk = (d: string) => {
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {
+ const f = path.join(d, e.name);
+ if (e.isDirectory()) walk(f);
+ else out.push({ file: f, text: fs.readFileSync(f).toString("latin1") });
+ }
+ };
+ walk(dir);
+ return out;
+}
+
+let a = "";
+let b = "";
+beforeAll(() => {
+ auth.setPassword("install password");
+ a = auth.createAccount("[email protected]", "long enough").id;
+ b = auth.createAccount("[email protected]", "long enough").id;
+});
+afterAll(() => {
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+
+describe("an account's own keys, at rest", () => {
+ it("are sealed on its record: auth.json holds the sealed value and the last 4 characters, never the key", () => {
+ const info = keys.saveAccountKey(a, "fal", FAL);
+ expect(info).toEqual({ last4: "9f3a", addedAt: expect.any(Number), readable: true });
+ keys.saveAccountKey(a, "replicate", REP);
+ const record = JSON.parse(fs.readFileSync(path.join(dir, "auth.json"), "utf8")).accounts.find((x: { id: string }) => x.id === a);
+ expect(record.keys.fal).toEqual({ sealed: expect.stringMatching(/^v1\./), last4: "9f3a", addedAt: expect.any(Number) });
+ expect(record.keys.replicate.last4).toBe("7c21");
+ expect(keys.accountKey(a, "fal")).toBe(FAL);
+ expect(keys.accountKey(a, "replicate")).toBe(REP);
+ for (const f of dataFiles()) {
+ expect(f.text.includes(FAL), f.file).toBe(false);
+ expect(f.text.includes("acct-fal-secret"), f.file).toBe(false);
+ expect(f.text.includes(REP), f.file).toBe(false);
+ }
+ });
+
+ it("opens only for its own account: a sealed value copied to another account is no key", () => {
+ const sealed = auth.accountKeyRecord(a, "fal")!;
+ auth.setAccountKey(b, "fal", sealed);
+ expect(keys.accountKey(b, "fal")).toBeNull();
+ expect(keys.accountKeyInfo(b).fal).toEqual({ last4: "9f3a", addedAt: sealed.addedAt, readable: false });
+ keys.removeAccountKey(b, "fal");
+ expect(auth.accountById(b)).not.toHaveProperty("keys");
+ });
+
+ it("shows the owner and Settings which providers, never a key or its sealed value", () => {
+ const listed = auth.listAccounts().find((x) => x.id === a)!;
+ expect(listed.keys).toEqual(["fal", "replicate"]);
+ expect(auth.listAccounts().find((x) => x.id === b)!.keys).toEqual([]);
+ const csv = auth.accountsCsv();
+ expect(csv.split("\r\n")[0]).toBe("email,created,last_login,gpu_connected,fal_key,replicate_key,disabled");
+ expect(csv).toMatch(/keys-a@example\.com,[^,]+,[^,]+,false,true,true,false/);
+ const sealed = auth.accountKeyRecord(a, "fal")!.sealed;
+ for (const text of [JSON.stringify(auth.listAccounts()), csv, JSON.stringify(keys.accountKeyInfo(a))]) {
+ expect(text).not.toContain(FAL);
+ expect(text).not.toContain(REP);
+ expect(text).not.toContain(sealed);
+ }
+ expect(keys.accountKeyInfo(a)).toEqual({
+ fal: { last4: "9f3a", addedAt: expect.any(Number), readable: true },
+ replicate: { last4: "7c21", addedAt: expect.any(Number), readable: true },
+ });
+ });
+
+ it("says when the provider refused it, only for the key still saved", () => {
+ keys.markKeyRejected(a, "fal", "an older key");
+ expect(keys.accountKeyInfo(a).fal?.rejectedAt).toBeUndefined();
+ keys.markKeyRejected(a, "fal", FAL);
+ expect(keys.accountKeyInfo(a).fal?.rejectedAt).toEqual(expect.any(Number));
+ // A key saved again starts afresh.
+ keys.saveAccountKey(a, "fal", FAL);
+ expect(keys.accountKeyInfo(a).fal?.rejectedAt).toBeUndefined();
+ });
+
+ it("takes a key as typed, trimmed, and refuses what can't be one", () => {
+ expect(keys.cleanKey(` ${FAL}\n`)).toBe(FAL);
+ for (const bad of ["", "short", "has a space inside", "x".repeat(301), 42, null]) expect(keys.cleanKey(bad), String(bad)).toBeNull();
+ });
+
+ it("gives the account paid models only while the studio isn't open-source only", () => {
+ expect(keys.accountEngineMode(a)).toBe("both");
+ expect(keys.accountEngineMode(b)).toBe("open");
+ setSetting("engineMode", "cloud");
+ expect(keys.accountEngineMode(a)).toBe("both");
+ setSetting("engineMode", "open");
+ expect(keys.accountEngineMode(a)).toBe("open");
+ expect(keys.paidAllowed()).toBe(false);
+ setSetting("engineMode", "");
+ });
+
+ it("are gone with the account, and with the server key a saved key stops opening (never another key)", () => {
+ const c = auth.createAccount("[email protected]", "long enough").id;
+ keys.saveAccountKey(c, "fal", "acct-fal-c-key:secret-c");
+ auth.deleteAccount(c);
+ expect(auth.accountKeyRecord(c, "fal")).toBeNull();
+ expect(fs.readFileSync(path.join(dir, "auth.json"), "utf8")).not.toContain("[email protected]");
+ // secrets.key lost (a restore without it): the account's keys stop, the record stays to say "add it again".
+ fs.rmSync(path.join(dir, "secrets.key"));
+ expect(keys.accountKey(a, "fal")).toBeNull();
+ expect(keys.accountKeyInfo(a).fal?.readable).toBe(false);
+ expect(keys.accountEngineMode(a)).toBe("open");
+ });
+});
diff --git a/tests/account-runs-admin.test.ts b/tests/account-runs-admin.test.ts
index 2daec27c..590f819c 100644
--- a/tests/account-runs-admin.test.ts
+++ b/tests/account-runs-admin.test.ts
@@ -193,7 +193,7 @@ describe("Settings → Accounts: what accounts make", () => {
expect(body.items.find((a) => a.id === A)).toMatchObject({ email: "[email protected]", runs: 5, failedWeek: 1, bytes: accountUsage(A).total });
expect(body.totals).toMatchObject({ accounts: 3, runsDay: 3, runsWeek: 5, running: 1 });
const csv = await (await accountsRoute.GET(direct("/api/admin/accounts?format=csv", "GET", { cookie: cookies.owner }))).text();
- expect(csv.split("\r\n")[0]).toBe("email,created,last_login,gpu_connected,disabled");
+ expect(csv.split("\r\n")[0]).toBe("email,created,last_login,gpu_connected,fal_key,replicate_key,disabled");
});
it("reads its numbers and lists through the indexes", () => {
diff --git a/tests/accounts-admin.test.ts b/tests/accounts-admin.test.ts
index bad8b022..e9137876 100644
--- a/tests/accounts-admin.test.ts
+++ b/tests/accounts-admin.test.ts
@@ -39,7 +39,7 @@ describe("Settings → Accounts", () => {
it("exports CSV that a spreadsheet can't read as a formula", () => {
auth.createAccount("[email protected]", "long enough");
const csv = auth.accountsCsv();
- expect(csv.split("\r\n")[0]).toBe("email,created,last_login,gpu_connected,disabled");
+ expect(csv.split("\r\n")[0]).toBe("email,created,last_login,gpu_connected,fal_key,replicate_key,disabled");
expect(csv).toContain("'[email protected]");
expect(csv).not.toContain("hash");
});
diff --git a/tests/secret-box.test.ts b/tests/secret-box.test.ts
new file mode 100644
index 00000000..8a6267c3
--- /dev/null
+++ b/tests/secret-box.test.ts
@@ -0,0 +1,122 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, describe, expect, it, vi } from "vitest";
+
+/**
+ * Your keys: the box that seals an account's fal.ai key or Replicate token at rest (src/server/secret-box.ts). AES-256-GCM
+ * under a server key in data/secrets.key, made once, never derived from the sign-in secret, bound to the account and the
+ * provider. A broken key file fails closed: nothing is sealed, nothing opens, and the file is never written over.
+ */
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-secret-box-"));
+process.env.FUOBE_DATA_DIR = dir;
+delete process.env.FUOBE_PASSWORD;
+
+const box = await import("@/server/secret-box");
+const auth = await import("@/server/auth");
+const keyFile = path.join(dir, "secrets.key");
+
+afterAll(() => {
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+
+/** Replace the key file's content, with a new modification time so the server reads it again. */
+function rewrite(content: string) {
+ fs.writeFileSync(keyFile, content);
+ const later = new Date(Date.now() + 5_000);
+ fs.utimesSync(keyFile, later, later);
+}
+
+describe("the secret box", () => {
+ it("makes no key file until something is sealed, and opens nothing without one", () => {
+ expect(fs.existsSync(keyFile)).toBe(false);
+ expect(box.open("v1.a.b.c", "ctx")).toBeNull();
+ expect(fs.existsSync(keyFile)).toBe(false);
+ });
+
+ it("opens what it sealed, for the same context only", () => {
+ const ctx = box.accountKeyContext("acct-1", "fal");
+ const sealed = box.seal("fal-key-id:fal-key-secret", ctx);
+ expect(sealed).toMatch(/^v1\.[\w-]+\.[\w-]+\.[\w-]+$/);
+ expect(sealed).not.toContain("fal-key");
+ expect(box.open(sealed, ctx)).toBe("fal-key-id:fal-key-secret");
+ // Another account, another provider: never opens.
+ expect(box.open(sealed, box.accountKeyContext("acct-2", "fal"))).toBeNull();
+ expect(box.open(sealed, box.accountKeyContext("acct-1", "replicate"))).toBeNull();
+ // Two seals of one value differ (a fresh IV each time).
+ expect(box.seal("same", ctx)).not.toBe(box.seal("same", ctx));
+ });
+
+ it("refuses a changed IV, tag or text, and an unknown version", () => {
+ const ctx = box.accountKeyContext("acct-1", "replicate");
+ const sealed = box.seal("r8_secret_token_value", ctx);
+ const [v, iv, tag, ct] = sealed.split(".");
+ const flip = (s: string) => (s[0] === "A" ? "B" : "A") + s.slice(1);
+ for (const bad of [`${v}.${flip(iv)}.${tag}.${ct}`, `${v}.${iv}.${flip(tag)}.${ct}`, `${v}.${iv}.${tag}.${flip(ct)}`, `v2.${iv}.${tag}.${ct}`, "v1.x", "", "plain text"]) {
+ expect(box.open(bad, ctx), bad).toBeNull();
+ }
+ });
+
+ it("keeps one server key in data/secrets.key: 32 random bytes, private to the server", () => {
+ const hex = fs.readFileSync(keyFile, "utf8").trim();
+ expect(hex).toMatch(/^[0-9a-f]{64}$/);
+ if (process.platform !== "win32") expect(fs.statSync(keyFile).mode & 0o777).toBe(0o600);
+ // Sealing again uses the same file.
+ box.seal("again", "ctx");
+ expect(fs.readFileSync(keyFile, "utf8").trim()).toBe(hex);
+ });
+
+ it("is never derived from the sign-in secret: a new password or signing everyone out changes nothing", () => {
+ const ctx = box.accountKeyContext("acct-1", "fal");
+ const sealed = box.seal("stays readable", ctx);
+ auth.setPassword("a first password");
+ auth.signOutEveryone({ tokens: true });
+ auth.setPassword("a second password");
+ expect(box.open(sealed, ctx)).toBe("stays readable");
+ });
+
+ it("fails closed on a broken key file: seal throws, open gives null, the file stays and the warning never shows it", () => {
+ const ctx = box.accountKeyContext("acct-1", "fal");
+ const sealed = box.seal("before", ctx);
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ try {
+ rewrite("not-a-key-but-secret-looking-content");
+ expect(() => box.seal("x", ctx)).toThrow(box.SecretBoxError);
+ expect(box.open(sealed, ctx)).toBeNull();
+ expect(fs.readFileSync(keyFile, "utf8")).toBe("not-a-key-but-secret-looking-content");
+ const said = warn.mock.calls.flat().join(" ");
+ expect(said).toContain("secrets.key");
+ expect(said).not.toContain("secret-looking");
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ it("opens nothing sealed under another server key (secrets.key replaced)", () => {
+ rewrite("ab".repeat(32));
+ const ctx = box.accountKeyContext("acct-1", "fal");
+ const sealed = box.seal("under the new key", ctx);
+ expect(box.open(sealed, ctx)).toBe("under the new key");
+ rewrite("cd".repeat(32));
+ expect(box.open(sealed, ctx)).toBeNull();
+ });
+
+ it("makes the key file once, even when two seals race for it", async () => {
+ fs.rmSync(keyFile);
+ const { spawnSync } = await import("node:child_process");
+ // Two fresh processes write the file with the same "only if it isn't there" flag the box uses: one wins, both read it.
+ const script = `const fs=require("fs");const f=${JSON.stringify(keyFile)};try{fs.writeFileSync(f,require("crypto").randomBytes(32).toString("hex"),{flag:"wx",mode:0o600})}catch(e){if(e.code!=="EEXIST")throw e}process.stdout.write(fs.readFileSync(f,"utf8"))`;
+ const runs = [spawnSync(process.execPath, ["-e", script], { encoding: "utf8" }), spawnSync(process.execPath, ["-e", script], { encoding: "utf8" })];
+ expect(runs[0].stdout).toMatch(/^[0-9a-f]{64}$/);
+ expect(runs[1].stdout).toBe(runs[0].stdout);
+ // The box reads the file that is there, never a key of its own.
+ const later = new Date(Date.now() + 10_000);
+ fs.utimesSync(keyFile, later, later);
+ const ctx = box.accountKeyContext("acct-1", "fal");
+ const sealed = box.seal("after the race", ctx);
+ expect(fs.readFileSync(keyFile, "utf8")).toBe(runs[0].stdout);
+ expect(box.open(sealed, ctx)).toBe("after the race");
+ });
+});