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
Sign-in data moves from auth.json into the SQLite database
Adarsha59b8fe173ef
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 9d5cd34f..53eb2b63 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -362,7 +362,7 @@ only on those routes; `validToken()` never takes one. See [gpu-workers.md](gpu-w## Security (`src/proxy.ts`, `src/server/auth.ts`, `src/server/remote-fetch.ts`)-- **Sign-in** is off until a password is set in Settings → Security or `FUOBE_PASSWORD`. State lives in `data/auth.json` (not SQLite) so the proxy can check requests with `fs` and `crypto` alone: a scrypt password hash, an HMAC secret for 30-day session cookies (replaced when the password changes), and API tokens stored as SHA-256 hashes (with public sign-up, below, the accounts too). The proxy lets `/login` and `/api/auth/login` through (and, since round 4 part 4, GET and HEAD on a share link's page and files, checked by `openShare`: see Share links), answers other API calls with 401 and redirects pages to `/login?next=…` (`safeNext()` in `src/lib/safe-redirect.ts` keeps it on the same origin). Its matcher leaves out only build assets, `samples/`, `previews/`, `vendor/`, root SVGs and `/api/uploads` (which makes the proxy's checks itself: `src/server/direct-gate.ts`).+- **Sign-in** is off until a password is set in Settings → Security or `FUOBE_PASSWORD`. State lives in SQLite, in `fuobe.db`'s `auth_*` tables (`AUTH_TABLES` in `src/server/db.ts`, read and written through `src/server/auth-store.ts`): a scrypt password hash, an HMAC secret for 30-day session cookies (replaced when the password changes), API tokens stored as SHA-256 hashes, signed-out cookies by their SHA-256, and with public sign-up (below) the accounts: one row each with a unique lower-case email and a scrypt hash, and their GPU links and sealed keys in rows of their own. Every check is a lookup by primary key or by the unique email. An older install's `data/auth.json` moves in on the first start, in one transaction that is checked row by row before it commits; for 10 minutes the file is then kept in step for a server of the older build that may still be running on the same folder, then kept as `auth.json.migrated-<time>`, with a short note that isn't JSON in its place, so an older build fails closed on it. An `auth.json` that can't be read keeps sign-in on with nobody signed in; one whose data can't go in makes the proxy answer 503 to everything, `/login` too. The proxy lets `/login` and `/api/auth/login` through (and, since round 4 part 4, GET and HEAD on a share link's page and files, checked by `openShare`: see Share links), answers other API calls with 401 and redirects pages to `/login?next=…` (`safeNext()` in `src/lib/safe-redirect.ts` keeps it on the same origin). Its matcher leaves out only build assets, `samples/`, `previews/`, `vendor/`, root SVGs and `/api/uploads` (which makes the proxy's checks itself: `src/server/direct-gate.ts`).- **Public sign-up** (the owner's, on main; [`docs/public-signup.md`](public-signup.md) is the whole design). It is off by default and needs a password; `FUOBE_PUBLIC_SIGNUP` or Settings → Security turns it on. `src/lib/guest-access.ts` holds the path rules and `src/proxy.ts` applies them. Guests (signed out) read the pages and catalogs, and every change answers 401. Accounts see a guest view of the owner's library: a change to it or to a project answers 403 `library` (`LIBRARY_CHANGES`), and settings, keys and tokens are the owner's. Price checks stay open to both (`isPriceCheck`: the estimate routes in `ESTIMATES`, `?preview=1` on the run routes in `PREVIEWS`), and `priceAs` (`src/server/visitor.ts`) prices a visitor's run as it would go on its own GPU. The one run an account may start is `POST /api/generations` (`ownGpuRun`), on its own ComfyUI; without one connected, any run answers `connect-gpu`, and with one, every other tool answers `own-gpu-tool`. Round 5 part 2's tools follow these rules. `/api/turnaround?preview=1` is in `PREVIEWS` and `/api/turnaround/estimate` in `ESTIMATES`. Split soundtrack and its remux (`POST /api/audio-tools`), the turnaround and Cinema's `path` and `turnaround` actions answer a guest 401, an account without a GPU `connect-gpu`, and an account with one `own-gpu-tool`. Export mix (`POST /api/audio-tools/export`) is in `LIBRARY_CHANGES`, since it saves into the owner's Library. MOSS-Image runs for an account through `POST /api/generations` on its own ComfyUI, the only new tool an account can run. A turnaround that names a character (`elementId`) answers any visitor 404 "Character not found", whether or not it exists (`requestViewer`, `recordExists`). `tests/public-signup-tools.test.ts` (12 tests) checks these answers through the API; the browser checks ran with public sign-up off.- **Admin tokens** (`src/server/admin-tokens.ts`, [`docs/admin-api.md`](admin-api.md)): `fuobe_adm_…` tokens with scopes, stored in SQLite (`admin_tokens`, SHA-256 only) and made in Settings → Security from the owner's signed-in browser. The proxy lets one through only on `/api/admin/*` (not `/api/admin/tokens`, except `/self`); every admin route checks it with `adminAccess(request, scope)`, which checks a request by its admin token alone, and otherwise asks for the owner as before. `validToken()` never takes one. Per-token limits a minute (120 reads, 30 changes, 600 file views, each counted on its own) and a separate budget for wrong tokens. Changes, a token's reads and file views, and refusals go to `admin_audit` (kept a year). A worker token is made only with `workers:tokens`.- **Host allowlist** (`hostAllowed`), for every method when no password is set, before anything else: IP literals, localhost and `*.localhost`, single-label names, `.local` / `.lan` / `.home.arpa` / `.internal` / `.localdomain`, this machine's hostname, and `FUOBE_ALLOWED_ORIGINS` (`*` allows any). This stops DNS rebinding. `X-Forwarded-Host` is not trusted here.diff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex 52a673bd..de747668 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -43,7 +43,7 @@ Written on 2026-10-30, when PR #15 wrapped up the work so far, and revised the s- before/after reveal clips on 42 apps' preset covers.- **Accounts** are the owner's public sign-up on main. It is off by default, and `FUOBE_PUBLIC_SIGNUP=1` turns it on. With it on:- guests browse read-only- - anyone can sign up with an email; accounts live in `auth.json` with a scrypt hash+ - anyone can sign up with an email; accounts live in SQLite (`fuobe.db`, `auth_accounts`) with a scrypt hash; an older `auth.json` moves in on the first start- accounts see a guest view of the owner's library and can't touch settings, keys or tokens. They upload their own files and run only on their own ComfyUI (Settings → Your GPU, checked on `/connect`).The PR #15 packages acc-1 (the Better Auth identity base) and acc-2 (the actor context on every route, with its integration fix 4e8359f) are dropped. The 55 remaining packages of the old accounts lane (acc-3 to acc-57) are dropped from the queue. The next accounts work starts with a new plan written with the owner, around public sign-up. [`research/accounts-8.md`](research/accounts-8.md) is background research only.diff --git a/docs/SELF-HOSTING.md b/docs/SELF-HOSTING.mdindex ee312368..a68cf55b 100644--- a/docs/SELF-HOSTING.md+++ b/docs/SELF-HOSTING.md@@ -76,6 +76,17 @@ To manage accounts, runs and workers from your own tools without the owner's sigPublic sign-up, guest browsing and connecting your own GPU to a shared install are described in [public-signup.md](public-signup.md).+### Sign-in data++The password, the sign-in secret, API tokens and accounts are kept in the database, `data/fuobe.db`, which only the server's own user can read (on Linux and macOS). Older versions kept them in `data/auth.json`. Upgrading needs no step:++- On the first start of this version, `auth.json` moves into the database in one go, checked before it is saved. A crash part-way changes nothing, and the next start does it again.+- For 10 minutes after that, `auth.json` is kept up to date, in case a server of the older version still runs on the same folder (for example during a deploy that starts the new server before it stops the old one).+- Then it is renamed to `auth.json.migrated-<date and time>`, which is kept as a backup, and a short note takes its place. An older version that finds the note keeps sign-in on with nobody signed in, rather than opening the studio without a password.+- If `auth.json` can't be read, nothing moves and sign-in stays on with nobody signed in until you fix or restore the file. If its data can't be moved (two accounts with the same email, for example), nothing changes, and the server answers every request with 503 and says why in its log.++To back up, copy `fuobe.db` (stop the server first, or use `sqlite3 data/fuobe.db ".backup backup.db"`, which also takes the `-wal` file's changes) together with `secrets.key`. To go back to an older version: stop the server and copy `auth.json.migrated-<…>` over `auth.json`. Changes made since the move (new accounts, a new password) are not in that file.+## Environment variables| Variable | What it does |@@ -84,7 +95,7 @@ Public sign-up, guest browsing and connecting your own GPU to a shared install a| `FUOBE_ALLOWED_ORIGINS` | Extra hosts Fuobe is reached at, comma-separated. Without a password, Fuobe answers only on IP addresses, localhost, single-label and LAN names (`.local`, `.lan`, `.home.arpa`, `.internal`) and the machine's hostname; add any other domain (a reverse proxy, a tunnel, a Tailscale name), or `*` to turn the check off. Also counts as "same site" for the cross-site write check behind a proxy that forwards neither Host nor X-Forwarded-Host || `FUOBE_TRUST_PROXY=1` | Behind a reverse proxy: trust the last `X-Forwarded-For` hop, so wrong passwords, and too many wrong share links, lock out only that visitor (60 s). Without it, everyone shares one limit: passwords are slowed to one attempt every 4 s and never locked, and wrong share links past 100 a minute get 429 while real links still open || `FUOBE_ALLOW_PRIVATE_URLS=1` | Let inputs, product links and project sources be fetched from private / LAN addresses (they are refused by default), and let Assist connectors use plain http beyond localhost (without it a connector needs https unless it is on localhost; a private https address is accepted, with a warning that Claude can only reach it through a public tunnel) |-| `FUOBE_DATA_DIR` | Where the database, files and `auth.json` live (default `./data`). Back up `secrets.key` there with `auth.json`: it opens the fal.ai and Replicate keys accounts saved ([Your keys](public-signup.md#your-keys)), which must be added again without it |+| `FUOBE_DATA_DIR` | Where the database (with the sign-in data) and files live (default `./data`). Back up `secrets.key` there with `fuobe.db`: it opens the fal.ai and Replicate keys accounts saved ([Your keys](public-signup.md#your-keys)), which must be added again without it || `FUOBE_DEMO_MODE` | `off` (default: a run with nothing connected asks you to connect one) or `on` (placeholder results, for a tour: every run makes a labelled placeholder). The old `auto` reads as `off`, and a saved `auto` is cleared on start || `FUOBE_SKILLS_DIR` | Where Assist's built-in skills are read from (default `./skills`) || `FUOBE_ENGINE_MODE`, `FUOBE_CLOUD_PROVIDER`, `FUOBE_ENHANCE_PROVIDER`, `FUOBE_LLM_PROVIDER` | The Settings choices above |diff --git a/docs/public-signup.md b/docs/public-signup.mdindex 3c2d5c2a..be02806d 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -58,8 +58,10 @@ takes an account's GPU type from the status strip's last check and asks the GPUstill works as before: `POST /api/auth/login` with `{ "password" }`, or the owner's sign-in at`/login?owner=1`. The login page links to it only in development, so a public site doesn'tadvertise it.-- Accounts are stored in `auth.json` in the data folder: the email in lower case, a salted scrypt- hash of the password (the same scheme as the install password), and the creation time.+- Accounts are stored in the database (`fuobe.db` in the data folder, table `auth_accounts`): the+ email in lower case (one account per email), a salted scrypt hash of the password (the same scheme+ as the install password), and the creation time. An install from before this kept them in+ `auth.json`, which moves into the database on the first start ([Sign-in data](SELF-HOSTING.md#sign-in-data)).- Sign-up and log-in attempts are rate limited per visitor (set `FUOBE_TRUST_PROXY=1` behind areverse proxy, so that each visitor gets their own limit; an IPv6 address counts by its /64).A visitor gets 30 account log-ins a minute, right or wrong, and 10 a minute for one email. After@@ -220,8 +222,8 @@ cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188- **Saving.** `PUT /api/account/gpu` with `{ "url", "token"? }` checks the address and asks thatComfyUI for `/system_stats` (`?test=1` checks without saving). `DELETE` disconnects. The address- and the optional token (sent as `Authorization: Bearer`) are stored with the account in- `auth.json`, never as the studio's ComfyUI setting.+ and the optional token (sent as `Authorization: Bearer`) are stored with the account in the+ database (`auth_account_gpu`), never as the studio's ComfyUI setting.- **Server-side requests.** Addresses on the server itself, on private networks or link-localaddresses are refused. The check runs again on the address each connection actually uses, so aname that is later pointed at the server can't reach the studio's own ComfyUI. The studio's own@@ -305,8 +307,8 @@ account with that provider. The studio's own keys are never used for an account'reaches the provider counts: 10 a minute per account, 20 per address (behind a trusted proxy),120 for all accounts together.- **Stored encrypted.** The key is sealed with AES-256-GCM under a server key in- `data/secrets.key`, made the first time a key is saved, and kept on the account's record in- `auth.json`. The server key isn't derived from the sign-in secret, so a new password or "Sign+ `data/secrets.key`, made the first time a key is saved, and kept with the account in the+ database (`auth_account_keys`). The server key isn't derived from the sign-in secret, so a new password or "Signeveryone out" leaves saved keys working. Without `secrets.key` (lost, or restored from anotherserver), saved keys can't be opened: accounts are asked to add them again, and the studio's keysare never used instead.diff --git a/src/app/api/admin/accounts/[id]/route.ts b/src/app/api/admin/accounts/[id]/route.tsindex 3bf70236..cf6e1851 100644--- a/src/app/api/admin/accounts/[id]/route.ts+++ b/src/app/api/admin/accounts/[id]/route.ts@@ -2,7 +2,7 @@ import { connection } from "next/server";import { z } from "zod";import { accountsWithStats } from "@/server/account-admin";import { adminAccess, audit, auditRead, type Actor } from "@/server/admin-tokens";-import { AccountError, listAccounts, setAccountDisabled, signOutAccount } from "@/server/auth";+import { AccountError, accountInfo, setAccountDisabled, signOutAccount } from "@/server/auth";import { removeAccount } from "@/server/account-sweep";import { revokeWorkersOf } from "@/server/computer/workers";@@ -24,7 +24,7 @@ export async function GET(request: Request, ctx: RouteContext<"/api/admin/accounconst access = adminAccess(request, "accounts:read", DENIED);if (access instanceof Response) return access;const { id } = await ctx.params;- const account = listAccounts().find((a) => a.id === id);+ const account = accountInfo(id);if (!account) return Response.json({ error: "No such account" }, { status: 404, headers: NO_STORE });auditRead(access.actor, "account.read", null, id);return Response.json(accountsWithStats([account]).items[0], { headers: NO_STORE });@@ -53,7 +53,7 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/admin/accoreturn failed(e, access.actor, action, id);}audit(access.actor, action, id, computers ? { computers } : null, 200);- return Response.json(listAccounts().find((a) => a.id === id), { headers: NO_STORE });+ return Response.json(accountInfo(id), { headers: NO_STORE });}/** Delete an account. */diff --git a/src/instrumentation.ts b/src/instrumentation.tsindex 90b19fd1..867f8e9c 100644--- a/src/instrumentation.ts+++ b/src/instrumentation.ts@@ -9,6 +9,9 @@ export async function register() {if (process.env.NEXT_RUNTIME !== "nodejs" || process.env.NEXT_PHASE === "phase-production-build") return;const { drainOnSignals } = await import("./server/shutdown");drainOnSignals();+ // Sign-in data: an older install's auth.json moves into the database now, before the first request.+ const { ensureAuthStore } = await import("./server/auth-store");+ ensureAuthStore();const { ensureRunner } = await import("./server/generations");ensureRunner();const { ensureTrashPurge } = await import("./server/library");diff --git a/src/proxy.ts b/src/proxy.tsindex 722e2546..898196a8 100644--- a/src/proxy.ts+++ b/src/proxy.ts@@ -33,6 +33,7 @@ import { hit } from "@/server/rate";import { recordExists } from "@/server/records";import { findShare, shareGuard, shareTargetExists } from "@/server/share-access";import { hostedRunsOn } from "@/server/hosted-switch";+import { authStoreFailed } from "@/server/auth-store";/*** Paths that work signed out: the login page and its API (and share links: openShare). Sign-up and@@ -326,6 +327,11 @@ function safeDecode(s: string): string {}export function proxy(request: NextRequest) {+ // Sign-in data that can't be used (the database, or an auth.json that couldn't be moved into it): nothing is served,+ // not even /login, so a new release in this state is never switched to and the studio is never open by mistake.+ if (authStoreFailed()) {+ return new NextResponse("Fuobe can't read its sign-in data. The server log says why.", { status: 503, headers: { "Cache-Control": "no-store", "Retry-After": "30" } });+ }// DNS rebinding: a page whose own name now points at this machine. Every method, reads too. With a// password set the sign-in check below already stops it (the session cookie belongs to the real name).if (!authEnabled() && !hostAllowed(request.headers.get("host") ?? request.nextUrl.host)) {diff --git a/src/server/account-keys.ts b/src/server/account-keys.tsindex c5a9d77c..be17020d 100644--- a/src/server/account-keys.ts+++ b/src/server/account-keys.ts@@ -5,7 +5,7 @@ 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+ * Your keys (public sign-up): an account's own fal.ai key or Replicate token. Sealed on its row in the database* (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).diff --git a/src/server/account-sweep.ts b/src/server/account-sweep.tsindex e7a1418f..9e01d9d9 100644--- a/src/server/account-sweep.ts+++ b/src/server/account-sweep.ts@@ -89,17 +89,17 @@ export async function sweepAccountFiles(now = Date.now()): Promise<{ uploads: nu).all(now - RETENTION_MS.run) as { id: string }[];for (const o of orphans) deleteAsset(o.id);- // Accounts that are gone (deleting one purges it at once: this only catches what that missed). Only when the auth- // file was read whole, and not when it lists no account at all while accounts own files: a file that failed to read,- // or one put back from before the sign-ups, must never wipe everyone's work.+ // Accounts that are gone (deleting one purges it at once: this only catches what that missed). Only when the sign-in+ // data was read whole, and not when it lists no account at all while accounts own files: data that failed to read,+ // or a database put back from before the sign-ups, must never wipe everyone's work.let gone: string[] = [];const owning = owners();- // No account owns anything here (a new install has no auth file yet): nothing to check.+ // No account owns anything here (a new install has no accounts yet): nothing to check.if (owning.length) {try {const live = readAccountIds();if (live.size) gone = owning.filter((id) => !live.has(id));- else console.warn(`[fuobe] account sweep: the auth file lists no accounts, but ${owning.length} own files here; nothing removed`);+ else console.warn(`[fuobe] account sweep: the sign-in data lists no accounts, but ${owning.length} own files here; nothing removed`);} catch (e) {console.warn(`[fuobe] account sweep: skipped removing deleted accounts' files (${(e as Error).message})`);}diff --git a/src/server/auth-store.ts b/src/server/auth-store.tsnew file mode 100644index 00000000..af7525ee--- /dev/null+++ b/src/server/auth-store.ts@@ -0,0 +1,759 @@+/**+ * Where sign-in data lives: tables in the studio's SQLite database (AUTH_TABLES in src/server/db.ts): the install's+ * cookie secret and Settings password, API tokens, accounts with their GPU links and sealed keys, and signed-out+ * cookies. src/server/auth.ts reads and writes them; this file decides whether they can be used, and moves an older+ * install's data/auth.json in.+ *+ * Moving auth.json in, once, on the first start of this build:+ * - Everything goes in inside one transaction that first takes the database's write lock. Inside it the rows are+ * counted and every account, token and setting is read back and compared with the file. The marker row+ * (auth_migration) is written in the same transaction, so a crash leaves either nothing (the next start moves it again)+ * or everything. A second server starting at the same time waits for the lock, then finds the marker.+ * - A file that can't be read or parsed keeps today's safety: sign-in stays on, nobody is signed in, nothing is written.+ * - A file whose data can't go in (two accounts with one email…) changes nothing either; sign-in fails closed and the+ * proxy answers 503, so a new release that can't start cleanly is never switched to.+ *+ * A server of an older build may still be running on the same data folder for a while (a deploy that starts the new+ * server before it stops the old one). Taking auth.json away at once would leave that server with no password at all.+ * So for 10 minutes ("bridge") the database leads and auth.json is kept as an exact copy of it: each change here is+ * also written to the file, and a change the older server makes to the file is read back in. Once the file has been+ * quiet for 3 minutes after that, it is renamed to auth.json.migrated-<UTC time> (kept, never deleted) and a short+ * text file that isn't JSON takes its place, so an older build pointed at this folder later fails closed (sign-in on,+ * nobody signed in) instead of opening the studio. A new install gets that file with its first sign-in change.+ */+import "server-only";+import type Database from "better-sqlite3";+import crypto from "node:crypto";+import fs from "node:fs";+import path from "node:path";+import type { Account, AccountGpu, ApiToken, StoredKey } from "./auth";+import { DATA_DIR, db } from "./db";++export const AUTH_FILE = path.join(DATA_DIR, "auth.json");++/** The file an older build keeps sign-in data in: what is moved in, and what is kept in step during the bridge. */+export interface AuthJson {+ password?: string;+ secret: string;+ tokens: ApiToken[];+ accounts?: Account[];+ publicSignup?: boolean;+ signedOut?: { hash: string; exp: number }[];+ [extra: string]: unknown;+}++/**+ * - fresh: nothing yet (a new install): no password, no accounts; the first change sets the store up.+ * - bridge / done: the database is the store (see above).+ * - unreadable: an auth.json that can't be read or parsed is waiting to be moved in.+ * - failed: the database or the move failed. unreadable and failed both fail closed.+ */+export type AuthStoreMode = "fresh" | "bridge" | "done" | "unreadable" | "failed";++interface Marker {+ source: "auth.json" | "new";+ state: "bridge" | "done";+ started_at: number;+ synced_at: number | null;+ json_stat: string | null;+ json_sha256: string | null;+ counts_json: string | null;+ backup_file: string | null;+ retired_at: number | null;+}++interface Counts {+ accounts: number;+ tokens: number;+ keys: number;+ gpus: number;+ signedOut: number;+}++/** auth.json's data can't be moved in as it is (never says which account: no email or secret goes in a log). */+class DataError extends Error {}++const envMs = (name: string, fallback: number) => {+ const v = Number(process.env[name]);+ return process.env[name]?.trim() && Number.isFinite(v) && v >= 0 ? v : fallback;+};+/** How long auth.json is kept in step after it was moved in (FUOBE_AUTH_BRIDGE_MS, for tests). */+const bridgeMs = () => envMs("FUOBE_AUTH_BRIDGE_MS", 10 * 60_000);+/** How long auth.json must have gone unchanged by anyone else before it is put aside. */+const quietMs = () => Math.min(3 * 60_000, bridgeMs());++declare global {+ /** Tests: the store's clock. */+ var __fuobeAuthClock: (() => number) | undefined;+ /** Tests: called while moving auth.json in, after half the accounts (a crash in the middle). */+ var __fuobeAuthImportFault: (() => void) | undefined;+ var __fuobeAuthStoreTimer: NodeJS.Timeout | undefined;+}++const now = () => globalThis.__fuobeAuthClock?.() ?? Date.now();++const s = {+ done: false,+ finished: false,+ /** The auth.json (by its stat) last found unreadable, or whose data couldn't go in, and when. */+ bad: null as { key: string; mode: "unreadable" | "failed"; at: number; data: boolean } | null,+ /** The database couldn't be used: try again after a moment. */+ dbFailedAt: 0,+ /** In the bridge: an auth.json (by its stat) that couldn't be read back in. */+ bridgeBad: null as string | null,+ retireCheckedAt: 0,+ warned: { unreadable: 0, failed: 0, ignored: 0 },+ writes: 0,+};++const HOUR = 60 * 60_000;++function warnOnce(kind: keyof typeof s.warned, message: string, error = false): void {+ if (Date.now() - s.warned[kind] < HOUR) return;+ s.warned[kind] = Date.now();+ if (error) console.error(`[fuobe] ${message}`);+ else console.warn(`[fuobe] ${message}`);+}++// ---------------------------------------------------------------------------+// Prepared statements++const statements = new WeakMap<Database.Database, Map<string, Database.Statement>>();++/** A prepared statement on the database, made once. */+export function sql(text: string): Database.Statement {+ const d = db();+ let m = statements.get(d);+ if (!m) statements.set(d, (m = new Map()));+ let st = m.get(text);+ if (!st) m.set(text, (st = d.prepare(text)));+ return st;+}++const marker = () => sql("SELECT * FROM auth_migration WHERE id = 1").get() as Marker | undefined;++const hasRows = () =>+ !!(sql("SELECT EXISTS(SELECT 1 FROM auth_install) OR EXISTS(SELECT 1 FROM auth_accounts) OR EXISTS(SELECT 1 FROM auth_tokens) OR EXISTS(SELECT 1 FROM auth_signed_out) AS n").get() as { n: number }).n;++/** A transaction that takes the write lock first. Another server holding it longer than the busy timeout: try again. */+function immediate<T>(fn: () => T): T {+ const d = db();+ for (let i = 0; ; i++) {+ try {+ return d.transaction(fn).immediate();+ } catch (e) {+ if ((e as { code?: string }).code === "SQLITE_BUSY" && i < 5 && !d.inTransaction) continue;+ throw e;+ }+ }+}++// ---------------------------------------------------------------------------+// auth.json on disk++/** Its stat as "mtime:size:inode", null when there is none, "error:<code>" when it can't even be looked at. */+function statKey(): string | null {+ try {+ const st = fs.statSync(AUTH_FILE);+ return `${st.mtimeMs}:${st.size}:${st.ino}`;+ } catch (e) {+ const code = (e as NodeJS.ErrnoException).code;+ return code === "ENOENT" ? null : `error:${code}`;+ }+}++type FileRead = { data: AuthJson; key: string | null; sha: string } | { error: string };++function readFile(): FileRead {+ try {+ const key = statKey();+ const raw = fs.readFileSync(AUTH_FILE);+ let data: AuthJson | null;+ try {+ data = JSON.parse(raw.toString("utf8")) as AuthJson | null;+ } catch {+ // Never the parser's message: it quotes the file.+ return { error: raw.toString("utf8").startsWith(TOMBSTONE_HEAD) ? "tombstone" : "not valid JSON" };+ }+ if (!data || typeof data !== "object" || Array.isArray(data)) return { error: "not an object" };+ return { data, key, sha: crypto.createHash("sha256").update(raw).digest("hex") };+ } catch (e) {+ return { error: (e as NodeJS.ErrnoException).code ?? "can't be read" };+ }+}++const TOMBSTONE_HEAD = "This is not Fuobe's sign-in file any more.";+const TOMBSTONE = `${TOMBSTONE_HEAD}+Sign-in data (the password, accounts and API tokens) is kept in the database, fuobe.db, in this folder.+This file is not JSON on purpose: an older Fuobe build that finds it keeps sign-in on with nobody signed in,+instead of opening the studio without a password. To go back to an older build, see "Sign-in data" in docs/SELF-HOSTING.md.+`;++/** Write a file the way auth.json was always written: a temporary file, then a rename, readable by this user only. */+function writeAtomic(file: string, text: string): void {+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const tmp = `${file}.${process.pid}.tmp`;+ fs.writeFileSync(tmp, text, { mode: 0o600 });+ fs.renameSync(tmp, file);+}++function writeTombstone(): void {+ try {+ if (fs.existsSync(AUTH_FILE) && fs.readFileSync(AUTH_FILE, "utf8") === TOMBSTONE) return;+ writeAtomic(AUTH_FILE, TOMBSTONE);+ } catch (e) {+ console.warn(`[fuobe] Couldn't write the note in place of auth.json (${(e as NodeJS.ErrnoException).code ?? (e as Error).message})`);+ }+}++// ---------------------------------------------------------------------------+// Rows <-> today's shapes++export interface AccountRow {+ id: string;+ email: string;+ password_hash: string;+ created_at: number;+ password_changed_at: number | null;+ last_login_at: number | null;+ disabled: number;+ sessions_after: number | null;+ extra_json: string | null;+}+export interface GpuRow {+ account_id: string;+ mode: "link" | "computer" | null;+ url: string | null;+ token: string | null;+}+export interface KeyRow {+ account_id: string;+ provider: string;+ sealed: string;+ last4: string;+ added_at: number;+ rejected_at: number | null;+}+interface TokenRow {+ id: string;+ name: string;+ hash: string;+ prefix: string;+ created_at: number;+ last_used_at: number | null;+ extra_json: string | null;+}++const extraOf = (json: string | null): Record<string, unknown> => (json ? (JSON.parse(json) as Record<string, unknown>) : {});++export function gpuFrom(g: GpuRow): AccountGpu {+ if (g.mode === "computer") return { mode: "computer" };+ return { ...(g.mode === "link" && { mode: "link" as const }), url: g.url ?? "", ...(g.token !== null && { token: g.token }) };+}++export function keyFrom(k: KeyRow): StoredKey {+ return { sealed: k.sealed, last4: k.last4, addedAt: k.added_at, ...(k.rejected_at !== null && { rejectedAt: k.rejected_at }) };+}++/** An account as auth.json had it: optional fields only when set, `gpu` and `keys` only when there are some. */+export function accountFrom(r: AccountRow, gpu?: GpuRow, keys?: KeyRow[]): Account {+ const a = { ...extraOf(r.extra_json), id: r.id, email: r.email, hash: r.password_hash, createdAt: r.created_at } as Account;+ if (r.password_changed_at !== null) a.passwordChangedAt = r.password_changed_at;+ if (r.last_login_at !== null) a.lastLoginAt = r.last_login_at;+ if (r.disabled) a.disabled = true;+ if (r.sessions_after !== null) a.sessionsAfter = r.sessions_after;+ if (gpu) a.gpu = gpuFrom(gpu);+ if (keys?.length) a.keys = Object.fromEntries(keys.map((k) => [k.provider, keyFrom(k)]));+ return a;+}++const tokenFrom = (t: TokenRow): ApiToken => ({+ ...extraOf(t.extra_json),+ id: t.id,+ name: t.name,+ hash: t.hash,+ prefix: t.prefix,+ createdAt: t.created_at,+ ...(t.last_used_at !== null && { lastUsedAt: t.last_used_at }),+});++const TOP_KNOWN = ["password", "secret", "tokens", "accounts", "publicSignup", "signedOut"];+const ACCOUNT_KNOWN = ["id", "email", "hash", "createdAt", "passwordChangedAt", "lastLoginAt", "disabled", "sessionsAfter", "gpu", "keys"];+const TOKEN_KNOWN = ["id", "name", "hash", "prefix", "createdAt", "lastUsedAt"];++function extraJson(o: object, known: string[]): string | null {+ const rest = Object.fromEntries(Object.entries(o).filter(([k]) => !known.includes(k)));+ return Object.keys(rest).length ? JSON.stringify(rest) : null;+}++/** Everything in the store, as auth.json holds it (accounts and tokens in the order they were added). */+export function exportJson(): AuthJson {+ const inst = sql("SELECT secret, password_hash, public_signup, extra_json FROM auth_install WHERE id = 1").get() as+ | { secret: string; password_hash: string | null; public_signup: number; extra_json: string | null }+ | undefined;+ const gpus = new Map((sql("SELECT * FROM auth_account_gpu").all() as GpuRow[]).map((g) => [g.account_id, g]));+ const keys = new Map<string, KeyRow[]>();+ for (const k of sql("SELECT * FROM auth_account_keys ORDER BY rowid").all() as KeyRow[]) keys.set(k.account_id, [...(keys.get(k.account_id) ?? []), k]);+ const accounts = (sql("SELECT * FROM auth_accounts ORDER BY rowid").all() as AccountRow[]).map((r) => accountFrom(r, gpus.get(r.id), keys.get(r.id)));+ const tokens = (sql("SELECT * FROM auth_tokens ORDER BY rowid").all() as TokenRow[]).map(tokenFrom);+ const signedOut = sql("SELECT hash, exp FROM auth_signed_out ORDER BY rowid").all() as { hash: string; exp: number }[];+ return {+ ...extraOf(inst?.extra_json ?? null),+ ...(inst?.password_hash != null && { password: inst.password_hash }),+ secret: inst?.secret ?? "",+ tokens,+ ...(accounts.length && { accounts }),+ ...(inst?.public_signup && { publicSignup: true }),+ ...(signedOut.length && { signedOut }),+ };+}++/** Signed-out cookies that haven't expired, one per cookie (the latest expiry). */+function liveSignedOut(list: unknown, at: number): { hash: string; exp: number }[] {+ if (list === undefined || list === null) return [];+ if (!Array.isArray(list)) throw new DataError("signedOut is not a list");+ const by = new Map<string, number>();+ for (const e of list as { hash?: unknown; exp?: unknown }[]) {+ if (!e || typeof e.hash !== "string" || typeof e.exp !== "number" || !Number.isFinite(e.exp)) throw new DataError("a signed-out entry is malformed");+ if (e.exp > at) by.set(e.hash, Math.max(e.exp, by.get(e.hash) ?? 0));+ }+ return [...by].map(([hash, exp]) => ({ hash, exp }));+}++const isStr = (v: unknown): v is string => typeof v === "string";+const isNum = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);+const optNum = (v: unknown, what: string): number | null => {+ if (v === undefined || v === null) return null;+ if (!isNum(v)) throw new DataError(`${what} is not a number`);+ return v;+};++/** Put a parsed auth.json in the (empty) tables, checking each value's type. */+function insertAll(data: AuthJson, at: number, version: number): Counts {+ if (data.secret !== undefined && !isStr(data.secret)) throw new DataError("the secret is not text");+ if (data.password !== undefined && data.password !== null && !isStr(data.password)) throw new DataError("the password hash is not text");+ sql("INSERT INTO auth_install (id, secret, password_hash, public_signup, extra_json, version, updated_at) VALUES (1, ?, ?, ?, ?, ?, ?)").run(+ data.secret ?? "",+ data.password ?? null,+ data.publicSignup ? 1 : 0,+ extraJson(data, TOP_KNOWN),+ version,+ at,+ );+ const counts: Counts = { accounts: 0, tokens: 0, keys: 0, gpus: 0, signedOut: 0 };+ const tokens = data.tokens ?? [];+ if (!Array.isArray(tokens)) throw new DataError("tokens is not a list");+ const addToken = sql("INSERT INTO auth_tokens (id, name, hash, prefix, created_at, last_used_at, extra_json) VALUES (?, ?, ?, ?, ?, ?, ?)");+ for (const t of tokens) {+ if (!t || !isStr(t.id) || !isStr(t.name) || !isStr(t.hash) || !isStr(t.prefix) || !isNum(t.createdAt)) throw new DataError("an API token is malformed");+ constrained(() => addToken.run(t.id, t.name, t.hash, t.prefix, t.createdAt, optNum(t.lastUsedAt, "a token's last use"), extraJson(t, TOKEN_KNOWN)), "two API tokens are the same");+ counts.tokens++;+ }+ const accounts = data.accounts ?? [];+ if (!Array.isArray(accounts)) throw new DataError("accounts is not a list");+ const addAccount = sql(+ "INSERT INTO auth_accounts (id, email, password_hash, created_at, password_changed_at, last_login_at, disabled, sessions_after, extra_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",+ );+ const addGpu = sql("INSERT INTO auth_account_gpu (account_id, mode, url, token) VALUES (?, ?, ?, ?)");+ const addKey = sql("INSERT INTO auth_account_keys (account_id, provider, sealed, last4, added_at, rejected_at) VALUES (?, ?, ?, ?, ?, ?)");+ const half = Math.floor(accounts.length / 2);+ accounts.forEach((a, i) => {+ if (i === half) globalThis.__fuobeAuthImportFault?.();+ if (!a || typeof a !== "object" || !isStr(a.id) || !a.id || !isStr(a.hash) || !isNum(a.createdAt)) throw new DataError(`account ${i + 1} is malformed`);+ if (!isStr(a.email) || !a.email || a.email !== a.email.toLowerCase()) throw new DataError(`account ${i + 1} has an email that isn't lower-case`);+ if (a.disabled !== undefined && a.disabled !== null && typeof a.disabled !== "boolean") throw new DataError(`account ${i + 1}'s disabled is not true or false`);+ constrained(+ () =>+ addAccount.run(+ a.id,+ a.email,+ a.hash,+ a.createdAt,+ optNum(a.passwordChangedAt, "a password change time"),+ optNum(a.lastLoginAt, "a log-in time"),+ a.disabled ? 1 : 0,+ optNum(a.sessionsAfter, "a sign-out time"),+ extraJson(a, ACCOUNT_KNOWN),+ ),+ `account ${i + 1} has the id or the email of an account before it`,+ );+ counts.accounts++;+ const g = a.gpu as AccountGpu | null | undefined;+ if (g !== undefined && g !== null) {+ if (typeof g !== "object") throw new DataError(`account ${i + 1}'s GPU is malformed`);+ if (g.mode === "computer") addGpu.run(a.id, "computer", null, null);+ else if ((g.mode === undefined || g.mode === "link") && isStr(g.url) && (g.token === undefined || isStr(g.token))) addGpu.run(a.id, g.mode ?? null, g.url, g.token ?? null);+ else throw new DataError(`account ${i + 1}'s GPU is malformed`);+ counts.gpus++;+ }+ if (a.keys !== undefined && a.keys !== null) {+ if (typeof a.keys !== "object" || Array.isArray(a.keys)) throw new DataError(`account ${i + 1}'s keys are malformed`);+ for (const [p, k] of Object.entries(a.keys as Record<string, StoredKey | null | undefined>)) {+ if (k === undefined || k === null) continue;+ if (!isStr(k.sealed) || !isStr(k.last4) || !isNum(k.addedAt)) throw new DataError(`account ${i + 1}'s ${p} key is malformed`);+ addKey.run(a.id, p, k.sealed, k.last4, k.addedAt, optNum(k.rejectedAt, "a key's refusal time"));+ counts.keys++;+ }+ }+ });+ const addSignedOut = sql("INSERT INTO auth_signed_out (hash, exp) VALUES (?, ?)");+ for (const e of liveSignedOut(data.signedOut, at)) {+ addSignedOut.run(e.hash, e.exp);+ counts.signedOut++;+ }+ return counts;+}++function constrained(fn: () => unknown, what: string): void {+ try {+ fn();+ } catch (e) {+ if (String((e as { code?: string }).code).startsWith("SQLITE_CONSTRAINT")) throw new DataError(what);+ throw e;+ }+}++/** Sorted keys all the way down, so two values compare as text. */+function stable(v: unknown): string {+ return JSON.stringify(v, (_k, x: unknown) =>+ x && typeof x === "object" && !Array.isArray(x) ? Object.fromEntries(Object.entries(x).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) : x,+ );+}++/** What must be the same after a round trip: a missing field and null, false or an empty list mean the same. */+function canon(data: AuthJson, at: number): string {+ const rest = (o: object, known: string[]) => Object.fromEntries(Object.entries(o).filter(([k]) => !known.includes(k)));+ const gpu = (g: AccountGpu | null | undefined) => (!g ? null : g.mode === "computer" ? { mode: "computer" } : { mode: g.mode ?? null, url: g.url, token: g.token ?? null });+ const keys = (k: Account["keys"] | null | undefined) =>+ Object.entries(k ?? {})+ .filter(([, v]) => !!v)+ .map(([p, v]) => ({ p, sealed: v!.sealed, last4: v!.last4, addedAt: v!.addedAt, rejectedAt: v!.rejectedAt ?? null }))+ .sort((a, b) => (a.p < b.p ? -1 : 1));+ return stable({+ extra: rest(data, TOP_KNOWN),+ password: data.password ?? null,+ secret: data.secret ?? "",+ publicSignup: !!data.publicSignup,+ tokens: (data.tokens ?? []).map((t) => ({ ...rest(t, TOKEN_KNOWN), id: t.id, name: t.name, hash: t.hash, prefix: t.prefix, createdAt: t.createdAt, lastUsedAt: t.lastUsedAt ?? null })),+ accounts: (data.accounts ?? []).map((a) => ({+ extra: rest(a, ACCOUNT_KNOWN),+ id: a.id,+ email: a.email,+ hash: a.hash,+ createdAt: a.createdAt,+ passwordChangedAt: a.passwordChangedAt ?? null,+ lastLoginAt: a.lastLoginAt ?? null,+ disabled: !!a.disabled,+ sessionsAfter: a.sessionsAfter ?? null,+ gpu: gpu(a.gpu),+ keys: keys(a.keys),+ })),+ signedOut: liveSignedOut(data.signedOut, at).sort((a, b) => (a.hash < b.hash ? -1 : 1)),+ });+}++/** Inside the transaction: the rows are what the file says, counted and read back. */+function verify(data: AuthJson, counts: Counts, at: number): void {+ const n = (table: string) => (sql(`SELECT COUNT(*) AS n FROM ${table}`).get() as { n: number }).n;+ const have: Counts = { accounts: n("auth_accounts"), tokens: n("auth_tokens"), keys: n("auth_account_keys"), gpus: n("auth_account_gpu"), signedOut: n("auth_signed_out") };+ if (stable(have) !== stable(counts) || counts.accounts !== (data.accounts ?? []).length || counts.tokens !== (data.tokens ?? []).length) {+ throw new DataError("the rows counted after the move differ from the file");+ }+ if (canon(exportJson(), at) !== canon(data, at)) throw new DataError("the data read back differs from the file");+}++function clearAll(): void {+ for (const t of ["auth_account_keys", "auth_account_gpu", "auth_signed_out", "auth_accounts", "auth_tokens", "auth_install"]) sql(`DELETE FROM ${t}`).run();+}++// ---------------------------------------------------------------------------+// Moving auth.json in++function importFile(file: { data: AuthJson; key: string | null; sha: string }): void {+ let counts: Counts | null = null;+ immediate(() => {+ if (marker()) return; // another server moved it in while this one waited for the lock+ if (hasRows()) throw new DataError("the sign-in tables already hold rows, without a record of how they got there");+ const at = now();+ counts = insertAll(file.data, at, 1);+ verify(file.data, counts, at);+ sql(+ "INSERT INTO auth_migration (id, source, state, started_at, synced_at, json_stat, json_sha256, counts_json) VALUES (1, 'auth.json', 'bridge', ?, ?, ?, ?, ?)",+ ).run(at, at, file.key, file.sha, JSON.stringify(counts));+ });+ if (counts) {+ const c = counts as Counts;+ console.info(+ `[fuobe] Sign-in data moved from auth.json into the database: ${c.accounts} accounts, ${c.tokens} API tokens, ${c.keys} saved keys, ${c.gpus} GPU links. auth.json is kept in step for ${Math.round(bridgeMs() / 60_000)} minutes, then kept as auth.json.migrated-<time>.`,+ );+ }+}++/** Write the store to auth.json in its usual format (bridge only), and remember the file as this server left it. */+function exportFile(): void {+ const text = JSON.stringify(exportJson(), null, 2);+ writeAtomic(AUTH_FILE, text);+ sql("UPDATE auth_migration SET json_stat = ?, json_sha256 = ? WHERE id = 1").run(statKey(), crypto.createHash("sha256").update(text).digest("hex"));+}++/**+ * Bridge, inside a write transaction: auth.json is not as this store left it. An older server changed it: read it all+ * back in. It is gone: write it again (that server would otherwise see no password). It can't be read: leave both.+ */+function syncFromFile(m: Marker): void {+ const key = statKey();+ if (key === m.json_stat || (key !== null && key === s.bridgeBad)) return;+ if (key === null) {+ exportFile();+ return;+ }+ const file = readFile();+ if ("error" in file) {+ s.bridgeBad = key;+ console.warn(`[fuobe] auth.json changed and can't be read back in (${file.error}): the database keeps sign-in as it was.`);+ return;+ }+ if (file.sha === m.json_sha256) {+ sql("UPDATE auth_migration SET json_stat = ? WHERE id = 1").run(key);+ return;+ }+ const at = now();+ const version = (sql("SELECT version FROM auth_install WHERE id = 1").get() as { version: number } | undefined)?.version ?? 0;+ try {+ // A savepoint: data that can't go in leaves the rows as they were, and the change that brought us here goes on.+ db().transaction(() => {+ clearAll();+ const counts = insertAll(file.data, at, version + 1);+ verify(file.data, counts, at);+ })();+ } catch (e) {+ if (!(e instanceof DataError)) throw e;+ s.bridgeBad = key;+ console.warn(`[fuobe] auth.json changed but can't be read back in (${e.message}): the database keeps sign-in as it was.`);+ return;+ }+ sql("UPDATE auth_migration SET synced_at = ?, json_stat = ?, json_sha256 = ? WHERE id = 1").run(at, key, file.sha);+}++/** Bridge: catch up with auth.json when it changed, and put it aside once its time is up. */+function bridgeTick(m: Marker): AuthStoreMode {+ const key = statKey();+ if (key !== m.json_stat && (key === null || key !== s.bridgeBad)) {+ try {+ immediate(() => {+ const inner = marker();+ if (inner?.state === "bridge") syncFromFile(inner);+ });+ } catch (e) {+ if (!(e instanceof DataError)) console.warn(`[fuobe] Couldn't catch up with auth.json: ${(e as Error).message}`);+ }+ }+ const t = now();+ if (t - s.retireCheckedAt >= Math.min(60_000, bridgeMs())) {+ s.retireCheckedAt = t;+ const fresh = marker();+ if (fresh?.state === "bridge" && t - fresh.started_at >= bridgeMs() && t - (fresh.synced_at ?? fresh.started_at) >= quietMs()) retire();+ }+ return s.done ? "done" : "bridge";+}++/** "auth.json.migrated-20261104T101500Z", or with -2, -3… when that is taken. */+function backupName(at: number): string {+ const stamp = new Date(at).toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");+ for (let i = 1; ; i++) {+ const name = `auth.json.migrated-${stamp}${i > 1 ? `-${i}` : ""}`;+ if (!fs.existsSync(path.join(DATA_DIR, name))) return name;+ }+}++function retire(): void {+ try {+ immediate(() => {+ const m = marker();+ if (m?.state !== "bridge") return;+ // Changed since the last look: read it in, and wait for another quiet spell.+ if (statKey() !== m.json_stat) {+ syncFromFile(m);+ if (marker()?.synced_at !== m.synced_at) return;+ }+ const at = now();+ sql("UPDATE auth_migration SET state = 'done', backup_file = ?, retired_at = ? WHERE id = 1").run(backupName(at), at);+ });+ } catch (e) {+ console.warn(`[fuobe] Couldn't put auth.json aside yet: ${(e as Error).message}`);+ return;+ }+ const m = marker();+ if (m?.state === "done") {+ s.done = true;+ finishDone(m);+ }+}++/**+ * Done: auth.json is put aside under its backup name (after a crash between the database's change and the rename,+ * this finishes it) and the note that isn't JSON is in its place. A JSON auth.json put back later is not read.+ */+function finishDone(m: Marker): void {+ s.finished = true;+ const key = statKey();+ if (key === null) return writeTombstone();+ const file = readFile();+ if ("error" in file) return; // the note, or a broken file: an older build fails closed on either+ const backup = m.backup_file ? path.join(DATA_DIR, m.backup_file) : null;+ if (m.source === "auth.json" && backup && !fs.existsSync(backup)) {+ try {+ fs.renameSync(AUTH_FILE, backup);+ if (process.platform !== "win32") fs.chmodSync(backup, 0o600);+ writeTombstone();+ console.info(`[fuobe] auth.json was kept as ${m.backup_file}: sign-in data is in the database now.`);+ } catch (e) {+ console.warn(`[fuobe] Couldn't put auth.json aside: ${(e as NodeJS.ErrnoException).code ?? (e as Error).message}`);+ }+ return;+ }+ warnOnce("ignored", `${AUTH_FILE} is not read: sign-in data is in the database (fuobe.db). See "Sign-in data" in docs/SELF-HOSTING.md.`);+}++// ---------------------------------------------------------------------------+// The mode++function failClosed(kind: "unreadable" | "failed", message: string): AuthStoreMode {+ warnOnce(kind, `${message} Sign-in stays on and nobody can sign in until it is fixed.`, kind === "failed");+ return kind;+}++/** Where sign-in data stands now. Moves auth.json in when it is waiting, and keeps the bridge going. */+export function authStoreMode(): AuthStoreMode {+ if (globalThis.__fuobeAuthTablesError) return failClosed("failed", `The sign-in tables in the database can't be used (${globalThis.__fuobeAuthTablesError}).`);+ if (s.done) {+ if (!s.finished) {+ try {+ const m = marker();+ if (m) finishDone(m);+ } catch {}+ }+ return "done";+ }+ if (s.dbFailedAt && Date.now() - s.dbFailedAt < 5_000) return "failed";+ try {+ db();+ if (globalThis.__fuobeAuthTablesError) return authStoreMode();+ const m = marker();+ if (m?.state === "done") {+ s.done = true;+ finishDone(m);+ return "done";+ }+ if (m?.state === "bridge") return bridgeTick(m);+ return beforeMove();+ } catch (e) {+ s.dbFailedAt = Date.now();+ return failClosed("failed", `The sign-in data in the database can't be read (${(e as Error).message}).`);+ }+}++/** No marker yet: a new install, or an auth.json to move in. */+function beforeMove(): AuthStoreMode {+ const key = statKey();+ if (key === null) {+ if (hasRows()) return failClosed("failed", "The database holds sign-in rows without a record of where they came from.");+ return "fresh";+ }+ if (s.bad?.key === key && (s.bad.mode === "unreadable" || s.bad.data)) return s.bad.mode;+ if (s.bad?.key === key && Date.now() - s.bad.at < 5_000) return s.bad.mode;+ const file = readFile();+ if ("error" in file) {+ // Another server set the store up a moment ago (and left the note in place of auth.json).+ const set = marker();+ if (set) return set.state === "done" ? ((s.done = true), "done") : bridgeTick(set);+ s.bad = { key, mode: "unreadable", at: Date.now(), data: false };+ return failClosed(+ "unreadable",+ file.error === "tombstone"+ ? `${AUTH_FILE} says sign-in data is in the database, but the database has none: restore fuobe.db, or copy auth.json.migrated-<time> back to auth.json.`+ : `${AUTH_FILE} can't be read (${file.error}).`,+ );+ }+ try {+ importFile(file);+ s.bad = null;+ } catch (e) {+ const data = e instanceof DataError;+ s.bad = { key, mode: "failed", at: Date.now(), data };+ return failClosed("failed", `auth.json couldn't be moved into the database (${(e as Error).message}); nothing was changed.`);+ }+ const m = marker();+ if (m?.state === "done") {+ s.done = true;+ return "done";+ }+ return m ? bridgeTick(m) : "fresh";+}++/** Sign-in can't be used (the database, or auth.json waiting to move in, can't be read): fail closed. */+export const authStoreClosed = (mode = authStoreMode()) => mode === "unreadable" || mode === "failed";++/** The store failed (not just an unreadable auth.json waiting): the proxy answers 503 to everything. */+export const authStoreFailed = () => authStoreMode() === "failed";++const UNREADABLE = "The sign-in file (auth.json) can't be read. Fix or restore it: Fuobe won't write over it.";+const FAILED = "The sign-in data can't be read. Fix or restore it: Fuobe won't write over it.";++/**+ * Change sign-in data: `fn` runs inside a transaction that holds the write lock. A new install is set up first; during+ * the bridge auth.json is caught up with first and written after, in the same transaction.+ */+export function authWrite<T>(fn: () => T): T {+ const mode = authStoreMode();+ if (mode === "unreadable") throw new Error(UNREADABLE);+ if (mode === "failed") throw new Error(FAILED);+ let fresh = false;+ const out = immediate(() => {+ const m = marker();+ const at = now();+ if (!m) {+ if (statKey() !== null || hasRows()) throw new Error("The sign-in data changed while saving: try again.");+ sql("INSERT INTO auth_migration (id, source, state, started_at) VALUES (1, 'new', 'done', ?)").run(at);+ fresh = true;+ } else if (m.state === "bridge") {+ syncFromFile(m);+ }+ sql("INSERT OR IGNORE INTO auth_install (id, secret, updated_at) VALUES (1, '', ?)").run(at);+ const r = fn();+ sql("UPDATE auth_install SET version = version + 1, updated_at = ? WHERE id = 1").run(at);+ if (marker()?.state === "bridge") exportFile();+ return r;+ });+ if (fresh) {+ s.done = true;+ s.finished = true;+ writeTombstone();+ }+ s.writes++;+ return out;+}++/** Changes with every change to sign-in data, by this server or another one on the same database. */+export function authStoreVersion(): number {+ try {+ if (authStoreClosed()) return -1 - s.writes;+ return (sql("SELECT version FROM auth_install WHERE id = 1").get() as { version: number } | undefined)?.version ?? 0;+ } catch {+ return -1 - s.writes;+ }+}++/** On start: move auth.json in now (not on the first request), and keep checking the bridge once a minute. */+export function ensureAuthStore(): AuthStoreMode {+ const mode = authStoreMode();+ if (!globalThis.__fuobeAuthStoreTimer) {+ globalThis.__fuobeAuthStoreTimer = setInterval(() => {+ try {+ authStoreMode();+ } catch {}+ }, 60_000);+ globalThis.__fuobeAuthStoreTimer.unref?.();+ }+ return mode;+}diff --git a/src/server/auth.ts b/src/server/auth.tsindex 9f2d8ae7..d4f805ec 100644--- a/src/server/auth.ts+++ b/src/server/auth.ts@@ -10,19 +10,15 @@* 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- * record pages only, so an unknown id gets a real 404: src/server/records.ts.)+ * Kept in the studio's SQLite database (AUTH_TABLES in src/server/db.ts; an older install's data/auth.json moves in on+ * the first start: src/server/auth-store.ts). Every check is a lookup by primary key or by the unique email, so the+ * proxy's sign-in check stays quick with any number of accounts.*/import crypto from "node:crypto";-import fs from "node:fs";import net from "node:net";import os from "node:os";-import path from "node:path";import { LOCAL_SUFFIXES } from "@/lib/page-place";--const DATA_DIR = path.resolve(/*turbopackIgnore: true*/ process.env.FUOBE_DATA_DIR ?? path.join(process.cwd(), "data"));-const FILE = path.join(DATA_DIR, "auth.json");+import { accountFrom, authStoreClosed, authStoreVersion, authWrite, sql, type AccountRow, type GpuRow, type KeyRow } from "./auth-store";export const SESSION_COOKIE = "fuobe_session";const SESSION_DAYS = 30;@@ -80,7 +76,8 @@ export interface Account {keys?: Partial<Record<CloudProvider, StoredKey>>;}-interface AuthFile {+/** The install's own row: the cookie secret, the Settings password and the public sign-up switch. */+interface Install {/** scrypt hash of the UI-set password ("salt:hash", hex). */password?: string;/**@@ -88,71 +85,54 @@ interface AuthFile {* changes and by Settings → Security → Sign everyone out, which both sign every browser out.*/secret: string;- tokens: ApiToken[];- accounts?: Account[];/** Settings → Security: guests may browse and anyone may sign up (FUOBE_PUBLIC_SIGNUP overrides it). */- publicSignup?: boolean;- /** Session cookies signed out (endSession), by their SHA-256, until they would have expired anyway. */- signedOut?: { hash: string; exp: number }[];- /** In memory only: the file is there but can't be read or parsed. Sign-in stays on, nobody is signed in, nothing is written. */+ publicSignup: boolean;+ /** The sign-in data can't be read (src/server/auth-store.ts). Sign-in stays on, nobody is signed in, nothing is written. */unreadable?: true;}-let cache: { mtime: number; data: AuthFile } | null = null;-let warnedUnreadable = 0;--/**- * The auth file. No file yet: no Settings password, no accounts (a new install). A file that is there but can't be read- * or parsed fails closed: sign-in stays on with nobody signed in, never an open studio, and nothing writes over it.- */-function read(): AuthFile {- try {- const mtime = fs.statSync(FILE).mtimeMs;- if (cache?.mtime === mtime) return cache.data;- const data = JSON.parse(fs.readFileSync(FILE, "utf8")) as AuthFile | null;- if (!data || typeof data !== "object" || Array.isArray(data)) throw new Error("not an object");- data.tokens ??= [];- cache = { mtime, data };- return data;- } catch (e) {- if ((e as NodeJS.ErrnoException).code === "ENOENT") return { secret: "", tokens: [] };- if (Date.now() - warnedUnreadable > 60 * 60_000) {- warnedUnreadable = Date.now();- console.warn(`[fuobe] ${FILE} can't be read (${(e as Error).message}): sign-in stays on and nobody can sign in until it is fixed or restored.`);- }- return { secret: "", tokens: [], unreadable: true };- }-}--declare global {- var __fuobeAuthWrites: number | undefined;+/** The install's row. Sign-in data that can't be read fails closed: sign-in stays on with nobody signed in. */+function install(): Install {+ if (authStoreClosed()) return { secret: "", publicSignup: false, unreadable: true };+ const r = sql("SELECT secret, password_hash, public_signup FROM auth_install WHERE id = 1").get() as+ | { secret: string; password_hash: string | null; public_signup: number }+ | undefined;+ return { secret: r?.secret ?? "", ...(r?.password_hash != null && { password: r.password_hash }), publicSignup: !!r?.public_signup };}-function write(data: AuthFile): void {- if (data.unreadable) throw new Error("The sign-in file (auth.json) can't be read. Fix or restore it: Fuobe won't write over it.");- fs.mkdirSync(DATA_DIR, { recursive: true });- const tmp = `${FILE}.${process.pid}.tmp`;- fs.writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 0o600 });- fs.renameSync(tmp, FILE);- cache = null;- globalThis.__fuobeAuthWrites = (globalThis.__fuobeAuthWrites ?? 0) + 1;+/** Inside authWrite: give the install a cookie secret when it has none yet. */+function ensureSecret(): void {+ sql("UPDATE auth_install SET secret = ? WHERE id = 1 AND secret = ''").run(crypto.randomBytes(32).toString("hex"));}/**- * Changes when this server writes the sign-in file (a sign-out of everyone, a new password, a token revoked…): a request- * that stays open, like the live feed, checks who is asking again when it changes.+ * Changes when sign-in data changes (a sign-out of everyone, a new password, a token revoked…), here or on another+ * server using the same database: a request that stays open, like the live feed, checks who is asking again then.*/-export const authVersion = () => globalThis.__fuobeAuthWrites ?? 0;--function withSecret(data: AuthFile): AuthFile {- return data.secret ? data : { ...data, secret: crypto.randomBytes(32).toString("hex") };-}+export const authVersion = () => authStoreVersion();const envPassword = () => process.env.FUOBE_PASSWORD || "";export function authStatus(): { enabled: boolean; fromEnv: boolean; tokens: Omit<ApiToken, "hash">[] } {- const d = read();- return { enabled: !!(envPassword() || d.password || d.unreadable), fromEnv: !!envPassword(), tokens: d.tokens.map(publicToken) };+ const d = install();+ const tokens = d.unreadable+ ? []+ : (sql("SELECT id, name, prefix, created_at, last_used_at FROM auth_tokens ORDER BY rowid").all() as TokenListRow[]).map((t) => ({+ id: t.id,+ name: t.name,+ prefix: t.prefix,+ createdAt: t.created_at,+ lastUsedAt: t.last_used_at ?? undefined,+ }));+ return { enabled: !!(envPassword() || d.password || d.unreadable), fromEnv: !!envPassword(), tokens };+}++interface TokenListRow {+ id: string;+ name: string;+ prefix: string;+ created_at: number;+ last_used_at: number | null;}const publicToken = (t: ApiToken): Omit<ApiToken, "hash"> => ({ id: t.id, name: t.name, prefix: t.prefix, createdAt: t.createdAt, lastUsedAt: t.lastUsedAt });@@ -160,7 +140,7 @@ const publicToken = (t: ApiToken): Omit<ApiToken, "hash"> => ({ id: t.id, name:/** Sign-in is on: a password is set (FUOBE_PASSWORD or Settings), or the auth file can't be read (fail closed). */export const authEnabled = () => {if (envPassword()) return true;- const d = read();+ const d = install();return !!(d.password || d.unreadable);};@@ -192,7 +172,7 @@ async function verifyHashAsync(pw: string, stored: string): Promise<boolean> {export function checkPassword(pw: string): boolean {const env = envPassword();if (env) return same(crypto.createHash("sha256").update(pw).digest(), crypto.createHash("sha256").update(env).digest());- const stored = read().password;+ const stored = install().password;if (!stored) return false;return verifyHash(pw, stored);}@@ -200,7 +180,7 @@ export function checkPassword(pw: string): boolean {/** {@link checkPassword} for a request: the Settings password's scrypt runs off the main thread. */export async function verifyPassword(pw: string): Promise<boolean> {if (envPassword()) return checkPassword(pw);- const stored = read().password;+ const stored = install().password;return !!stored && (await verifyHashAsync(pw, stored));}@@ -208,8 +188,8 @@ export async function verifyPassword(pw: string): Promise<boolean> {export function setPassword(pw: string | null): void {if (envPassword()) throw new Error("The password is set by FUOBE_PASSWORD on the server");if (pw !== null && pw.length < 8) throw new Error("Use at least 8 characters");- const d = read();- write({ ...d, password: pw === null ? undefined : hashPassword(pw), secret: crypto.randomBytes(32).toString("hex") });+ const hash = pw === null ? null : hashPassword(pw);+ authWrite(() => sql("UPDATE auth_install SET password_hash = ?, secret = ? WHERE id = 1").run(hash, crypto.randomBytes(32).toString("hex")));}// ---------------------------------------------------------------------------@@ -222,10 +202,10 @@ const fingerprint = (s: string) => crypto.createHash("sha256").update(s).digest(/*** The key a session is signed with: the secret and a password's fingerprint. The owner's password (FUOBE_PASSWORD, or* the Settings one): a new one (after a restart, or in Settings) ends every owner sign-in at once, and the secret alone- * (auth.json) can't make an owner cookie. An account's own password hash: its new password ends its other sign-ins.+ * (in the database) can't make an owner cookie. An account's own password hash: its new password ends its other sign-ins.* A new FUOBE_PASSWORD signs no account out; a password set in Settings makes a new secret, which signs out everyone.*/-function keyFor(d: AuthFile, who: "owner" | Pick<Account, "hash">): string {+function keyFor(d: Install, who: "owner" | Pick<Account, "hash">): string {return `${d.secret}.${fingerprint(who === "owner" ? envPassword() || d.password || "" : who.hash)}`;}@@ -234,15 +214,15 @@ function keyFor(d: AuthFile, who: "owner" | Pick<Account, "hash">): string {* The two sign different text with different keys, so neither can be turned into the other.*/export function createSession(accountId?: string): { value: string; maxAge: number } {- let d = read();+ let d = install();if (!d.secret) {- d = withSecret(d);- write(d);+ authWrite(ensureSecret);+ d = install();}const exp = Date.now() + SESSION_MS;const payload = accountId ? `${exp}.${accountId}` : String(exp);// An account that isn't there gets a cookie nothing takes (sessionViewer finds no account for it).- const who = accountId ? { hash: d.accounts?.find((a) => a.id === accountId)?.hash ?? "" } : "owner";+ const who = accountId ? { hash: (sql("SELECT password_hash FROM auth_accounts WHERE id = ?").get(accountId) as { password_hash: string } | undefined)?.password_hash ?? "" } : "owner";return { value: `${payload}.${sign(keyFor(d, who), payload)}`, maxAge: SESSION_DAYS * 86_400 };}@@ -250,7 +230,7 @@ export function createSession(accountId?: string): { value: string; maxAge: numb* An account cookie made before account keys held the password's fingerprint was signed with the secret alone. It is* still taken (it ends with its 30 days, so a deploy signs nobody out) until the account first changes its password.*/-const legacyAccountMac = (d: AuthFile, account: Account, payload: string, mac: string) =>+const legacyAccountMac = (d: Install, account: Account, payload: string, mac: string) =>!account.passwordChangedAt && same(Buffer.from(mac), Buffer.from(sign(d.secret, payload)));/** Who a session cookie belongs to: the owner, an account that still exists, or nobody. */@@ -272,16 +252,16 @@ export function sessionViewer(value: string | undefined): Viewer | null {if (parts.length !== 2 && parts.length !== 3) return null;const exp = parts[0];const mac = parts[parts.length - 1];- const d = read();+ const d = install();if (!d.secret || !mac || !liveExpiry(exp)) return null;const payload = parts.slice(0, -1).join(".");// An account's key holds its password's fingerprint: the account comes first.- const account = parts.length === 3 ? d.accounts?.find((a) => a.id === parts[1]) : undefined;+ const account = parts.length === 3 ? accountById(parts[1]) : undefined;if (parts.length === 3 && !account) return null;const signed = same(Buffer.from(mac), Buffer.from(sign(keyFor(d, account ?? "owner"), payload)));if (!signed && !(account && legacyAccountMac(d, account, payload, mac))) return null;// Signed out with Sign out: a copy of the cookie (another tab's, a stolen one) is refused too.- if (d.signedOut?.length && d.signedOut.some((s) => s.hash === cookieHash(value))) return null;+ if (sql("SELECT 1 FROM auth_signed_out WHERE hash = ?").get(cookieHash(value))) return null;if (!account) return { kind: "owner" };// Signed out everywhere (signOutAccount): a cookie issued at or before then is refused.if (account.sessionsAfter && Number(exp) - SESSION_MS <= account.sessionsAfter) return null;@@ -296,11 +276,10 @@ const cookieHash = (value: string) => crypto.createHash("sha256").update(value).*/export function endSession(value: string | undefined): void {if (!value || !sessionViewer(value)) return;- const d = read();- const now = Date.now();- const signedOut = (d.signedOut ?? []).filter((s) => s.exp > now);- signedOut.push({ hash: cookieHash(value), exp: Number(value.split(".")[0]) });- write({ ...d, signedOut });+ authWrite(() => {+ sql("DELETE FROM auth_signed_out WHERE exp <= ?").run(Date.now());+ sql("INSERT OR REPLACE INTO auth_signed_out (hash, exp) VALUES (?, ?)").run(cookieHash(value), Number(value.split(".")[0]));+ });}/**@@ -309,8 +288,10 @@ export function endSession(value: string | undefined): void {* can't. With `tokens`, every API token is revoked as well. The password stays as it is.*/export function signOutEveryone(opts: { tokens?: boolean } = {}): void {- const d = read();- write({ ...d, secret: crypto.randomBytes(32).toString("hex"), ...(opts.tokens && { tokens: [] }) });+ authWrite(() => {+ sql("UPDATE auth_install SET secret = ? WHERE id = 1").run(crypto.randomBytes(32).toString("hex"));+ if (opts.tokens) sql("DELETE FROM auth_tokens").run();+ });}/** The owner's session (the install password's): what Settings → Security and the tokens need. */@@ -340,19 +321,48 @@ export function createAccount(email: string, password: string): Account {const e = normalizeEmail(email);if (!e) throw new AccountError("Enter a valid email address", 400);if (password.length < 8) throw new AccountError("Use at least 8 characters", 400);- const d = withSecret(read());- if (d.accounts?.some((a) => a.email === e)) throw new AccountError("An account with this email already exists. Log in instead.", 409);+ const taken = () => new AccountError("An account with this email already exists. Log in instead.", 409);+ if (sql("SELECT 1 FROM auth_accounts WHERE email = ?").get(e)) throw taken();const account: Account = { id: crypto.randomBytes(9).toString("hex"), email: e, hash: hashPassword(password), createdAt: Date.now(), lastLoginAt: Date.now() };- write({ ...d, accounts: [...(d.accounts ?? []), account] });+ try {+ authWrite(() => {+ ensureSecret();+ sql("INSERT INTO auth_accounts (id, email, password_hash, created_at, last_login_at) VALUES (?, ?, ?, ?, ?)").run(+ account.id,+ account.email,+ account.hash,+ account.createdAt,+ account.lastLoginAt,+ );+ });+ } catch (err) {+ // Two sign-ups with one email at the same moment: the unique email lets one in.+ if ((err as { code?: string }).code === "SQLITE_CONSTRAINT_UNIQUE" && /auth_accounts\.email/.test((err as Error).message)) throw taken();+ throw err;+ }return account;}+/** The account with this (normalised) email, or undefined: one lookup on the unique email. */+function accountByEmail(e: string): Account | undefined {+ if (authStoreClosed()) return undefined;+ const r = sql("SELECT * FROM auth_accounts WHERE email = ?").get(e) as AccountRow | undefined;+ return r && withRows(r);+}++/** An account's row with its GPU and keys rows. */+function withRows(r: AccountRow): Account {+ const gpu = sql("SELECT * FROM auth_account_gpu WHERE account_id = ?").get(r.id) as GpuRow | undefined;+ const keys = sql("SELECT * FROM auth_account_keys WHERE account_id = ? ORDER BY rowid").all(r.id) as KeyRow[];+ return accountFrom(r, gpu, keys);+}+let dummy: string | undefined;/** The account for this email and password, or null. An unknown email costs the same scrypt as a known one. */export function checkAccount(email: string, password: string): Account | null {const e = normalizeEmail(email);- const account = e ? read().accounts?.find((a) => a.email === e) : undefined;+ const account = e ? accountByEmail(e) : undefined;const ok = verifyHash(password, account?.hash ?? (dummy ??= hashPassword(crypto.randomBytes(12).toString("hex"))));return account && ok ? account : null;}@@ -362,7 +372,7 @@ let dummyAsync: Promise<string> | undefined;/** {@link checkAccount} for a request: scrypt runs off the main thread, and an unknown email costs the same as a known one. */export async function verifyAccount(email: string, password: string): Promise<Account | null> {const e = normalizeEmail(email);- const account = e ? read().accounts?.find((a) => a.email === e) : undefined;+ const account = e ? accountByEmail(e) : undefined;const stored =account?.hash ??(await (dummyAsync ??= (async () => {@@ -384,23 +394,25 @@ export async function setAccountPassword(id: string, current: string, next: striif (!(await verifyAccount(account.email, current))) throw new AccountError("The current password is wrong", 403);const salt = crypto.randomBytes(16);const hash = `${salt.toString("hex")}:${(await scrypt(next, salt)).toString("hex")}`;- // Read again: the file may have changed while the passwords were hashed.- const d = read();- if (!d.accounts?.some((a) => a.id === id)) throw new AccountError("No such account", 404);+ // The account may have gone while the passwords were hashed.const changed = { hash, passwordChangedAt: Date.now() };- write({ ...d, accounts: d.accounts.map((a) => (a.id === id ? { ...a, ...changed } : a)) });+ authWrite(() => {+ const r = sql("UPDATE auth_accounts SET password_hash = ?, password_changed_at = ? WHERE id = ?").run(changed.hash, changed.passwordChangedAt, id);+ if (!r.changes) throw new AccountError("No such account", 404);+ });return { ...account, ...changed };}-/** How often a log-in is written down: each write rewrites the whole accounts file. */+/** How often a log-in is written down. */const LOGIN_RECORD_MS = 60 * 60_000;/** Remember a log-in (Settings → Accounts shows it), at most once an hour per account. */export function recordLogin(id: string): void {- const d = read();- const account = d.accounts?.find((a) => a.id === id);- if (!account || Date.now() - (account.lastLoginAt ?? 0) < LOGIN_RECORD_MS) return;- write({ ...d, accounts: d.accounts?.map((a) => (a.id === id ? { ...a, lastLoginAt: Date.now() } : a)) });+ if (authStoreClosed()) return;+ const r = sql("SELECT last_login_at FROM auth_accounts WHERE id = ?").get(id) as { last_login_at: number | null } | undefined;+ if (!r || Date.now() - (r.last_login_at ?? 0) < LOGIN_RECORD_MS) return;+ const t = Date.now();+ authWrite(() => sql("UPDATE auth_accounts SET last_login_at = ? WHERE id = ? AND COALESCE(last_login_at, 0) < ?").run(t, id, t - LOGIN_RECORD_MS));}/** What the owner sees of an account (Settings → Accounts): never the password hash. */@@ -416,47 +428,81 @@ export interface AccountInfo {keys: CloudProvider[];}-const keysOf = (a: Pick<Account, "keys">): CloudProvider[] => (["fal", "replicate"] as const).filter((p) => !!a.keys?.[p]);+/** The accounts as the owner sees them, newest first: one indexed read, with each account's GPU and key providers. */+const INFO_SQL = `SELECT a.id, a.email, a.created_at, a.last_login_at, a.disabled,+ EXISTS (SELECT 1 FROM auth_account_gpu g WHERE g.account_id = a.id) AS gpu,+ (SELECT group_concat(k.provider) FROM auth_account_keys k WHERE k.account_id = a.id) AS keys+ FROM auth_accounts a`;++interface InfoRow {+ id: string;+ email: string;+ created_at: number;+ last_login_at: number | null;+ disabled: number;+ gpu: number;+ keys: string | null;+}++const infoFrom = (r: InfoRow): AccountInfo => {+ const has = new Set(r.keys?.split(",") ?? []);+ return {+ id: r.id,+ email: r.email,+ createdAt: r.created_at,+ lastLoginAt: r.last_login_at ?? null,+ disabled: !!r.disabled,+ gpu: !!r.gpu,+ keys: (["fal", "replicate"] as const).filter((p) => has.has(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, keys: keysOf(a) }))- .sort((a, b) => b.createdAt - a.createdAt);+ if (authStoreClosed()) return [];+ return (sql(`${INFO_SQL} ORDER BY a.created_at DESC, a.rowid`).all() as InfoRow[]).map(infoFrom);+}++/** One account as the owner sees it (Settings → Accounts, the admin API), or undefined. */+export function accountInfo(id: string): AccountInfo | undefined {+ if (authStoreClosed()) return undefined;+ const r = sql(`${INFO_SQL} WHERE a.id = ?`).get(id) as InfoRow | undefined;+ return r && infoFrom(r);}/**- * The ids of the accounts, read from the auth file itself: throws when it can't be read or parsed, or has no secret- * (every auth file that ever held an account has one). The account sweep removes the files of accounts missing from- * it, so a read that failed for a moment must never look like "no accounts".+ * The ids of the accounts: throws when the sign-in data can't be read, or the install has no secret yet (every install+ * that ever held an account has one). The account sweep removes the files of accounts missing from it, so a read+ * that failed for a moment must never look like "no accounts".*/export function readAccountIds(): Set<string> {- const data = JSON.parse(fs.readFileSync(FILE, "utf8")) as Partial<AuthFile> | null;- if (!data || typeof data !== "object" || typeof data.secret !== "string" || !data.secret || (data.accounts !== undefined && !Array.isArray(data.accounts))) {- throw new Error("The auth file can't be read");- }- return new Set((data.accounts ?? []).map((a) => a?.id).filter((id): id is string => typeof id === "string" && !!id));+ if (authStoreClosed() || !install().secret) throw new Error("The sign-in data can't be read");+ return new Set((sql("SELECT id FROM auth_accounts").all() as { id: string }[]).map((r) => r.id));+}++/** Change one account's row: 404 when there is no such account. */+function updateAccount(id: string, set: string, ...values: unknown[]): void {+ authWrite(() => {+ if (!sql(`UPDATE auth_accounts SET ${set} WHERE id = ?`).run(...values, id).changes) throw new AccountError("No such account", 404);+ });}/** Switch an account off (it is signed out at once) or on again. */export function setAccountDisabled(id: string, disabled: boolean): 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) => (a.id === id ? { ...a, disabled } : a)) });+ updateAccount(id, "disabled = ?", disabled ? 1 : 0);}/** End every sign-in of an account at once, without switching it off: it can log in again. */export function signOutAccount(id: string): void {- const d = read();- if (!d.accounts?.some((a) => a.id === id)) throw new AccountError("No such account", 404);- const now = Date.now();- write({ ...d, accounts: d.accounts.map((a) => (a.id === id ? { ...a, sessionsAfter: now } : a)) });+ updateAccount(id, "sessions_after = ?", Date.now());}-/** Delete an account (its sessions stop working at once). */+/** Delete an account with its GPU link and keys (its sessions stop working at once). */export function deleteAccount(id: string): void {- const d = read();- if (!d.accounts?.some((a) => a.id === id)) throw new AccountError("No such account", 404);- write({ ...d, accounts: d.accounts.filter((a) => a.id !== id) });+ authWrite(() => {+ sql("DELETE FROM auth_account_keys WHERE account_id = ?").run(id);+ sql("DELETE FROM auth_account_gpu WHERE account_id = ?").run(id);+ if (!sql("DELETE FROM auth_accounts WHERE id = ?").run(id).changes) throw new AccountError("No such account", 404);+ });}/** The owner: the install password's session or an API token (everyone while no password is set). */@@ -480,7 +526,11 @@ export function accountsCsv(items = listAccounts()): string {return rows.map((r) => r.map(csvCell).join(",")).join("\r\n") + "\r\n";}-export const accountById = (id: string): Account | undefined => read().accounts?.find((a) => a.id === id);+export const accountById = (id: string): Account | undefined => {+ if (authStoreClosed()) return undefined;+ const r = sql("SELECT * FROM auth_accounts WHERE id = ?").get(id) as AccountRow | undefined;+ return r && withRows(r);+};/** The account's own ComfyUI, or null when it hasn't connected one or the owner switched the account off. */export const accountGpu = (id: string): AccountGpu | null => {@@ -488,18 +538,19 @@ export const accountGpu = (id: string): AccountGpu | null => {return a && !a.disabled ? (a.gpu ?? null) : null;};-function withoutGpu(a: Account): Account {- const copy = { ...a };- delete copy.gpu;- return copy;+/** Inside authWrite: 404 when there is no such account. */+function mustExist(id: string): void {+ if (!sql("SELECT 1 FROM auth_accounts WHERE id = ?").get(id)) throw new AccountError("No such account", 404);}/** Save (or with null, forget) the account's own ComfyUI. The caller checks the address first (src/server/account-gpu.ts). */export function setAccountGpu(id: string, gpu: AccountGpu | null): void {- const d = read();- if (!d.accounts?.some((a) => a.id === id)) throw new AccountError("No such account", 404);- const kept = (g: AccountGpu): AccountGpu => (g.mode === "computer" ? { mode: "computer" } : { url: g.url, ...(g.token && { token: g.token }) });- write({ ...d, accounts: d.accounts.map((a) => (a.id !== id ? a : gpu ? { ...a, gpu: kept(gpu) } : withoutGpu(a))) });+ authWrite(() => {+ mustExist(id);+ if (!gpu) sql("DELETE FROM auth_account_gpu WHERE account_id = ?").run(id);+ else if (gpu.mode === "computer") sql("INSERT OR REPLACE INTO auth_account_gpu (account_id, mode, url, token) VALUES (?, 'computer', NULL, NULL)").run(id);+ else sql("INSERT OR REPLACE INTO auth_account_gpu (account_id, mode, url, token) VALUES (?, NULL, ?, ?)").run(id, gpu.url, gpu.token || null);+ });}/** 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). */@@ -510,19 +561,15 @@ export const accountKeyRecord = (id: string, p: CloudProvider): StoredKey | 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;- }),+ authWrite(() => {+ mustExist(id);+ if (!key) sql("DELETE FROM auth_account_keys WHERE account_id = ? AND provider = ?").run(id, p);+ else {+ sql(+ `INSERT INTO auth_account_keys (account_id, provider, sealed, last4, added_at, rejected_at) VALUES (?, ?, ?, ?, ?, ?)+ ON CONFLICT (account_id, provider) DO UPDATE SET sealed = excluded.sealed, last4 = excluded.last4, added_at = excluded.added_at, rejected_at = excluded.rejected_at`,+ ).run(id, p, key.sealed, key.last4, key.addedAt, key.rejectedAt || null);+ }});}@@ -583,11 +630,14 @@ export function publicSignupFromEnv(): boolean | null {}/** The Settings → Security switch (ignored while FUOBE_PUBLIC_SIGNUP is set). */-export const publicSignupSetting = () => !!read().publicSignup;+export const publicSignupSetting = () => install().publicSignup;export function setPublicSignup(on: boolean): void {if (publicSignupFromEnv() !== null) throw new Error("Public sign-up is set by FUOBE_PUBLIC_SIGNUP on the server");- write({ ...withSecret(read()), publicSignup: on });+ authWrite(() => {+ ensureSecret();+ sql("UPDATE auth_install SET public_signup = ? WHERE id = 1").run(on ? 1 : 0);+ });}/**@@ -786,14 +836,15 @@ export function createToken(name: string): { token: string; info: Omit<ApiToken,do token = `fuobe_${crypto.randomBytes(24).toString("base64url")}`;while (/^fuobe_(wkr|adm)_/i.test(token));const t: ApiToken = { id: crypto.randomBytes(6).toString("hex"), name: name.trim() || "API token", hash: tokenHash(token), prefix: token.slice(0, 12), createdAt: Date.now() };- const d = withSecret(read());- write({ ...d, tokens: [...d.tokens, t] });+ authWrite(() => {+ ensureSecret();+ sql("INSERT INTO auth_tokens (id, name, hash, prefix, created_at) VALUES (?, ?, ?, ?, ?)").run(t.id, t.name, t.hash, t.prefix, t.createdAt);+ });return { token, info: publicToken(t) };}export function revokeToken(id: string): void {- const d = read();- write({ ...d, tokens: d.tokens.filter((t) => t.id !== id) });+ authWrite(() => sql("DELETE FROM auth_tokens WHERE id = ?").run(id));}const touched = new Map<string, number>();@@ -802,14 +853,18 @@ export function validToken(header: string | null): boolean {const m = /^Bearer\s+(fuobe_[\w-]+)$/i.exec(header ?? "");// A worker's token (src/server/computer/workers.ts) or a scoped admin token is never the owner.if (!m || /^fuobe_(wkr|adm)_/i.test(m[1])) return false;- const h = Buffer.from(tokenHash(m[1]));- const d = read();- const hit = d.tokens.find((t) => same(Buffer.from(t.hash), h));+ if (authStoreClosed()) return false;+ // Found by its SHA-256 (unique): what is looked up is a hash, never the token.+ const hit = sql("SELECT id FROM auth_tokens WHERE hash = ?").get(tokenHash(m[1])) as { id: string } | undefined;if (!hit) return false;// Record use at most once an hour per token (avoids a write per request).if (Date.now() - (touched.get(hit.id) ?? 0) > 3_600_000) {touched.set(hit.id, Date.now());- write({ ...d, tokens: d.tokens.map((t) => (t.id === hit.id ? { ...t, lastUsedAt: Date.now() } : t)) });+ try {+ authWrite(() => sql("UPDATE auth_tokens SET last_used_at = ? WHERE id = ?").run(Date.now(), hit.id));+ } catch (e) {+ console.warn(`[fuobe] Couldn't note an API token's use: ${(e as Error).message}`);+ }}return true;}diff --git a/src/server/db.ts b/src/server/db.tsindex bad83975..503e3c4f 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -5,6 +5,83 @@ import path from "node:path";export const DATA_DIR = path.resolve(/*turbopackIgnore: true*/ process.env.FUOBE_DATA_DIR ?? path.join(process.cwd(), "data"));+/**+ * Sign-in data (src/server/auth-store.ts), which data/auth.json held before. Every name starts with "auth_": a data folder+ * may hold tables of the same plain names ("users", "api_tokens"…) from a dropped branch. Secrets stay as auth.json had+ * them: scrypt password hashes ("salt:hash"), account keys sealed by secret-box.ts, API tokens by their SHA-256 only.+ * - auth_install: one row: the cookie secret, the Settings password's hash, the public sign-up switch, auth.json's+ * top-level fields this build doesn't know, and a number that grows with every change (authVersion).+ * - auth_migration: one row once the store is set up: where it came from (an imported auth.json, or new) and whether+ * the imported file is still kept in step for a build that may still read it ("bridge") or was put aside ("done").+ * - auth_tokens, auth_accounts (one per email, lower-cased), auth_account_gpu and auth_account_keys (rows of an+ * account, removed with it), auth_signed_out (signed-out cookies by their SHA-256, until they would have expired).+ * Safe to run on every start.+ */+export const AUTH_TABLES = `CREATE TABLE IF NOT EXISTS auth_install (+ id INTEGER PRIMARY KEY CHECK (id = 1),+ secret TEXT NOT NULL DEFAULT '',+ password_hash TEXT,+ public_signup INTEGER NOT NULL DEFAULT 0,+ extra_json TEXT,+ version INTEGER NOT NULL DEFAULT 0,+ updated_at INTEGER NOT NULL+ );+ CREATE TABLE IF NOT EXISTS auth_migration (+ id INTEGER PRIMARY KEY CHECK (id = 1),+ source TEXT NOT NULL,+ state TEXT NOT NULL,+ started_at INTEGER NOT NULL,+ synced_at INTEGER,+ json_stat TEXT,+ json_sha256 TEXT,+ counts_json TEXT,+ backup_file TEXT,+ retired_at INTEGER+ );+ CREATE TABLE IF NOT EXISTS auth_tokens (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ hash TEXT NOT NULL UNIQUE,+ prefix TEXT NOT NULL,+ created_at INTEGER NOT NULL,+ last_used_at INTEGER,+ extra_json TEXT+ );+ CREATE TABLE IF NOT EXISTS auth_accounts (+ id TEXT PRIMARY KEY,+ email TEXT NOT NULL CHECK (email = lower(email)),+ password_hash TEXT NOT NULL,+ created_at INTEGER NOT NULL,+ password_changed_at INTEGER,+ last_login_at INTEGER,+ disabled INTEGER NOT NULL DEFAULT 0,+ sessions_after INTEGER,+ extra_json TEXT+ );+ CREATE UNIQUE INDEX IF NOT EXISTS auth_accounts_email ON auth_accounts(email);+ CREATE INDEX IF NOT EXISTS auth_accounts_created ON auth_accounts(created_at DESC);+ CREATE TABLE IF NOT EXISTS auth_account_gpu (+ account_id TEXT PRIMARY KEY REFERENCES auth_accounts(id) ON DELETE CASCADE,+ mode TEXT CHECK (mode IS NULL OR mode IN ('link', 'computer')),+ url TEXT,+ token TEXT,+ CHECK (mode = 'computer' OR url IS NOT NULL)+ );+ CREATE TABLE IF NOT EXISTS auth_account_keys (+ account_id TEXT NOT NULL REFERENCES auth_accounts(id) ON DELETE CASCADE,+ provider TEXT NOT NULL,+ sealed TEXT NOT NULL,+ last4 TEXT NOT NULL,+ added_at INTEGER NOT NULL,+ rejected_at INTEGER,+ PRIMARY KEY (account_id, provider)+ );+ CREATE TABLE IF NOT EXISTS auth_signed_out (+ hash TEXT PRIMARY KEY,+ exp INTEGER NOT NULL+ );+ CREATE INDEX IF NOT EXISTS auth_signed_out_exp ON auth_signed_out(exp);`;+/** Run in order, once each: a migration is known by its place in this list (append only, never reorder). */export const MIGRATIONS: string[] = [`CREATE TABLE IF NOT EXISTS generations (@@ -612,8 +689,14 @@ export const MIGRATIONS: string[] = [// skill's name, one set of its inputs as text (a file is its /api/files/… URL) and the file inputs that take the// newest upload of their kind when the run starts. NULL: a request, as before.`ALTER TABLE assist_schedules ADD COLUMN skill_json TEXT;`,+ // Sign-in data (AUTH_TABLES, src/server/auth-store.ts), which data/auth.json held before. Also made on every open+ // (ensureAuthTables), since other branches append migrations at the same place.+ AUTH_TABLES,];+/** The place of the sign-in tables' migration in MIGRATIONS. */+const AUTH_MIGRATION = 27;+/*** "Use the ComfyUI on this computer" (src/server/computer/tasks.ts). relay_runners: each principal's computer (the one* that runs its waiting jobs, until its lease lapses) and what its tab said about its ComfyUI. relay_tasks: one per@@ -815,6 +898,44 @@ export const SKILL_TABLES = `CREATE TABLE IF NOT EXISTS skill_runs (CREATE INDEX IF NOT EXISTS skill_runs_skill ON skill_runs(skill, created_at DESC);CREATE INDEX IF NOT EXISTS skill_runs_status ON skill_runs(status);`;+/** The columns each sign-in table must have: a table of the same name made by something else is never used. */+const AUTH_COLUMNS: Record<string, string[]> = {+ auth_install: ["id", "secret", "password_hash", "public_signup", "extra_json", "version", "updated_at"],+ auth_migration: ["id", "source", "state", "started_at", "synced_at", "json_stat", "json_sha256", "counts_json", "backup_file", "retired_at"],+ auth_tokens: ["id", "name", "hash", "prefix", "created_at", "last_used_at", "extra_json"],+ auth_accounts: ["id", "email", "password_hash", "created_at", "password_changed_at", "last_login_at", "disabled", "sessions_after", "extra_json"],+ auth_account_gpu: ["account_id", "mode", "url", "token"],+ auth_account_keys: ["account_id", "provider", "sealed", "last4", "added_at", "rejected_at"],+ auth_signed_out: ["hash", "exp"],+};++/** Make the sign-in tables and check they are ours. Never throws: a problem is kept for auth-store.ts, which fails closed. */+function ensureAuthTables(db: Database.Database): string | null {+ try {+ for (const [table, columns] of Object.entries(AUTH_COLUMNS)) {+ const have = (db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[]).map((c) => c.name);+ if (have.length && columns.some((c) => !have.includes(c))) return `a table named ${table} with other columns is already in the database`;+ }+ db.exec(AUTH_TABLES);+ return null;+ } catch (e) {+ return (e as Error).message;+ }+}++/**+ * The database holds the cookie secret, password hashes and sealed keys: only the server's own user may read it (and+ * its -wal and -shm files, which SQLite makes with the database file's mode). Not on Windows, which has no such modes.+ */+function keepPrivate(file: string): void {+ if (process.platform === "win32") return;+ for (const f of [file, `${file}-wal`, `${file}-shm`]) {+ try {+ if ((fs.statSync(f).mode & 0o077) !== 0) fs.chmodSync(f, 0o600);+ } catch {}+ }+}+/** Columns the optional services added to existing tables: [table, column, type]. */const HOOK_COLUMNS: [string, string, string][] = [// 1: never served to the account (its output check hasn't said "show").@@ -843,6 +964,8 @@ const RELAY_COLUMNS: [string, string, string][] = [declare global {var __fuobeDb: Database.Database | undefined;+ /** Why the sign-in tables couldn't be made or used (null: they are fine). auth-store.ts then fails closed. */+ var __fuobeAuthTablesError: string | null | undefined;}/**@@ -863,22 +986,45 @@ function forgetDroppedBranchMigrations(db: Database.Database): void {if (done(24) && !hasColumn("assets", "account_id") && has("trigger", "audit_log_no_delete")) forget(24);}+/** Add a column found missing: another server starting at the same moment may have just added it. */+function addColumn(db: Database.Database, alter: string): void {+ try {+ db.exec(alter);+ } catch (e) {+ if (!/duplicate column name/i.test((e as Error).message)) throw e;+ }+}+function open(): Database.Database {fs.mkdirSync(DATA_DIR, { recursive: true });- const db = new Database(path.join(DATA_DIR, "fuobe.db"));- db.pragma("journal_mode = WAL");+ const file = path.join(DATA_DIR, "fuobe.db");+ const db = new Database(file);+ keepPrivate(file);+ // Before anything else: another server opening the same file at the same moment is waited for, not an error.db.pragma("busy_timeout = 5000");+ db.pragma("journal_mode = WAL");+ db.pragma("foreign_keys = ON");+ // A deleted row's bytes are overwritten where that costs no extra writes: a deleted account's email and password hash+ // don't stay behind in the file.+ db.pragma("secure_delete = FAST");db.exec(`CREATE TABLE IF NOT EXISTS _migrations (id INTEGER PRIMARY KEY)`);forgetDroppedBranchMigrations(db);const done = new Set((db.prepare("SELECT id FROM _migrations").all() as { id: number }[]).map((r) => r.id),);+ // The sign-in tables first: a folder whose place 27 went to another branch's migration still gets them. When they+ // can't be made (a table of the same name with other columns), their migration waits and sign-in fails closed.+ globalThis.__fuobeAuthTablesError = ensureAuthTables(db);+ if (globalThis.__fuobeAuthTablesError) console.error(`[fuobe] The sign-in tables can't be used: ${globalThis.__fuobeAuthTablesError}`);MIGRATIONS.forEach((sql, i) => {if (done.has(i)) return;+ if (i === AUTH_MIGRATION && globalThis.__fuobeAuthTablesError) return;+ // The write lock first, then a second look: another server starting at the same moment may have run it.db.transaction(() => {+ if (db.prepare("SELECT 1 FROM _migrations WHERE id = ?").get(i)) return;db.exec(sql);db.prepare("INSERT INTO _migrations (id) VALUES (?)").run(i);- })();+ }).immediate();});// Placeholder results are opt-in (settings.ts, demoMode): a saved "auto", which made a placeholder whenever the model// wasn't connected, is cleared, so the install runs with the default "off". A saved "on" stays. Safe on every start.@@ -887,7 +1033,7 @@ function open(): Database.Database {// "openrouter"…); chats from before read agent "claude" as Anthropic. Added when it's missing rather than as a// numbered migration, so branches that add migrations never clash over its place in the list.if (!(db.prepare("PRAGMA table_info(assist_thread_state)").all() as { name: string }[]).some((c) => c.name === "provider")) {- db.exec("ALTER TABLE assist_thread_state ADD COLUMN provider TEXT");+ addColumn(db, "ALTER TABLE assist_thread_state ADD COLUMN provider TEXT");}// "Use the ComfyUI on this computer" (src/server/computer): its tables, made here rather than as a numbered migration,// since other branches add migrations at the same time and a migration is known by its place in the list.@@ -895,13 +1041,13 @@ function open(): Database.Database {// Columns added after the tables were first made (a data folder that ran an earlier build of this feature).for (const [table, column, type] of RELAY_COLUMNS) {const has = (db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[]).some((c) => c.name === column);- if (!has) db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);+ if (!has) addColumn(db, `ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);}// The optional billing and moderation services (billing.ts, moderation.ts): their tables and columns.db.exec(HOOK_TABLES);for (const [table, column, type] of HOOK_COLUMNS) {const has = (db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[]).some((c) => c.name === column);- if (!has) db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);+ if (!has) addColumn(db, `ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);}// Admin tokens and the admin API's log.db.exec(ADMIN_TABLES);@@ -920,6 +1066,7 @@ function open(): Database.Database {} catch (e) {console.warn(`[fuobe] Couldn't index runs by account: ${(e as Error).message}`);}+ keepPrivate(file);return db;}diff --git a/src/server/generations.ts b/src/server/generations.tsindex ab990050..5b0345b9 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -443,6 +443,12 @@ export const ASSET_FREE: Record<string, string> = {"reports_inbox.target_json": "what a report is about: a run, asset or share id, never a file","admin_tokens.scopes_json": "an admin token's scope names","admin_audit.detail_json": "small facts about an admin action: counts, ids and names, never a file's URL",+ "auth_install.extra_json": "sign-in settings an older auth.json held that this build doesn't know",+ "auth_migration.counts_json": "how many accounts, tokens and keys moved in from auth.json",+ "auth_migration.backup_file": "the name auth.json was kept under in the data folder, never a served file",+ "auth_tokens.extra_json": "an API token's fields this build doesn't know",+ "auth_accounts.extra_json": "an account's fields this build doesn't know",+ "auth_account_gpu.url": "the address of an account's own ComfyUI, never a Fuobe file","shorts_sessions.range_json": "start and end times","shorts_sessions.settings_json": "ratio, language, model and resolution","shorts_sessions.segments_json": "generation ids of each take",diff --git a/src/server/secret-box.ts b/src/server/secret-box.tsindex 4d10864d..7d0d4376 100644--- a/src/server/secret-box.ts+++ b/src/server/secret-box.ts@@ -11,7 +11,7 @@ import { DATA_DIR } from "./db";* 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.+ * over. Back it up with the database (fuobe.db): without it, the saved keys must be added again.*/const VERSION = "v1";diff --git a/tests/account-gpu.test.ts b/tests/account-gpu.test.tsindex b79ac993..0652d633 100644--- a/tests/account-gpu.test.ts+++ b/tests/account-gpu.test.ts@@ -1,7 +1,6 @@-import fs from "node:fs";-import path from "node:path";import { afterAll, beforeAll, describe, expect, it } from "vitest";import { tempDir } from "./helpers/temp-dir";+import { accountRows } from "./helpers/auth-db";const dir = tempDir("fuobe-account-gpu-");process.env.FUOBE_DATA_DIR = dir;@@ -99,7 +98,8 @@ describe("Your GPU: where an account's runs go", () => {it("forgets the GPU on disconnect", () => {auth.setAccountGpu(id, null);expect(auth.accountGpu(id)).toBeNull();- expect(JSON.parse(fs.readFileSync(path.join(dir, "auth.json"), "utf8")).accounts[0]).not.toHaveProperty("gpu");+ expect(auth.accountById(id)).not.toHaveProperty("gpu");+ expect(accountRows("auth_account_gpu", id)).toEqual([]);});});diff --git a/tests/account-keys-isolation.test.ts b/tests/account-keys-isolation.test.tsindex e0474150..dc677204 100644--- a/tests/account-keys-isolation.test.ts+++ b/tests/account-keys-isolation.test.ts@@ -5,6 +5,7 @@ import { NextRequest } from "next/server";import { keysSeen, startFakeFal, startFakeReplicate, type FakeCloud } from "./helpers/fake-cloud";import { TINY_PNG } from "./helpers/fake-comfy-runner";import { tempDir } from "./helpers/temp-dir";+import { dbBytes } from "./helpers/auth-db";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 }) }));@@ -361,7 +362,7 @@ describe("deleting an account stops its paid runs with its key, then forgets theconst cancel = fal.log.find((r) => r.path.endsWith("/cancel"));expect(cancel?.authorization, how).toBe("Key acct-fal-E");expect(auth.accountById(id), how).toBeUndefined();- expect(fs.readFileSync(path.join(dir, "auth.json"), "utf8")).not.toContain(`gone-${how}@example.com`);+ expect(dbBytes(dir)).not.toContain(`gone-${how}@example.com`);expect(keysSeen(fal.log)).toEqual(["Key acct-fal-E"]);}});diff --git a/tests/account-keys.test.ts b/tests/account-keys.test.tsindex d039e78f..d0dd3a55 100644--- a/tests/account-keys.test.ts+++ b/tests/account-keys.test.ts@@ -2,9 +2,10 @@ import fs from "node:fs";import path from "node:path";import { beforeAll, describe, expect, it } from "vitest";import { tempDir } from "./helpers/temp-dir";+import { accountRows, authDb, dbBytes } from "./helpers/auth-db";/**- * Your keys: where an account's own fal.ai key or Replicate token is kept. Sealed on its record in auth.json, never in+ * Your keys: where an account's own fal.ai key or Replicate token is kept. Sealed on its account's row in the database, never in* plain text in any file of the data folder, shown only by its last 4 characters, gone with the account.*/const dir = tempDir("fuobe-account-keys-");@@ -42,13 +43,15 @@ beforeAll(() => {});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", () => {+ it("are sealed on its record: the database 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");+ authDb().pragma("wal_checkpoint(TRUNCATE)");+ const record = auth.accountById(a)!;+ expect(accountRows("auth_account_keys", a).map((r) => r.provider).sort()).toEqual(["fal", "replicate"]);+ 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()) {@@ -117,7 +120,8 @@ describe("an account's own keys, at rest", () => {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]");+ expect(dbBytes(dir)).not.toContain("[email protected]");+ expect(accountRows("auth_account_keys", c)).toEqual([]);// 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();diff --git a/tests/account-review-fixes.test.ts b/tests/account-review-fixes.test.tsindex 1c2e4ab9..3aa56887 100644--- a/tests/account-review-fixes.test.ts+++ b/tests/account-review-fixes.test.ts@@ -4,6 +4,7 @@ import path from "node:path";import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";import { tempDir } from "./helpers/temp-dir";+import { authDb, authSecret, setAccountCreatedAt, withoutAccounts } from "./helpers/auth-db";/*** The review of "Your GPU" tools (public sign-up): each test here shows one problem the review found, and stays as the@@ -53,12 +54,7 @@ beforeAll(async () => {auth.setAccountGpu(a, { url: fake.url });cookie = `${auth.SESSION_COOKIE}=${auth.createSession(a).value}`;// Accounts past their first week, so their files may reach 3 GB (a new account keeps 1 GB).- const authFile = path.join(dir, "auth.json");- const data = JSON.parse(fs.readFileSync(authFile, "utf8")) as { accounts: { createdAt: number }[] };- for (const x of data.accounts) x.createdAt -= 8 * 24 * 60 * 60_000;- fs.writeFileSync(authFile, JSON.stringify(data));- // A new modified time, so the auth module reads the file again (it caches by that time).- fs.utimesSync(authFile, new Date(), new Date(Date.now() + 5000));+ for (const id of [a, b]) setAccountCreatedAt(id, auth.accountById(id)!.createdAt - 8 * 24 * 60 * 60_000);});afterAll(async () => {globalThis.fetch = realFetch;@@ -276,25 +272,31 @@ describe("an answer that won't be read lets its connection go", () => {});});-describe("the account sweep never wipes accounts on a bad read of the auth file", () => {- it("keeps every account's files when the auth file can't be read, or lists no accounts", async () => {+describe("the account sweep never wipes accounts on a bad read of the sign-in data", () => {+ it("keeps every account's files when the sign-in data can't be read, has no secret, or lists no accounts", async () => {const own = mine(b);- const file = path.join(dir, "auth.json");- const good = fs.readFileSync(file);+ // The sign-in tables can't be used.+ globalThis.__fuobeAuthTablesError = "a test";try {- fs.writeFileSync(file, "{ not json");expect((await sweepAccountFiles()).accounts).toBe(0);expect(fs.existsSync(absolutePath(own.relPath))).toBe(true);- fs.rmSync(file);- expect((await sweepAccountFiles()).accounts).toBe(0);- expect(fs.existsSync(absolutePath(own.relPath))).toBe(true);- // A file put back from before the sign-ups (no accounts in it) while accounts own files here.- fs.writeFileSync(file, JSON.stringify({ secret: "s", tokens: [] }));+ } finally {+ globalThis.__fuobeAuthTablesError = null;+ }+ // No secret: never an install that held an account.+ const secret = authSecret();+ authDb().prepare("UPDATE auth_install SET secret = ''").run();+ try {expect((await sweepAccountFiles()).accounts).toBe(0);expect(fs.existsSync(absolutePath(own.relPath))).toBe(true);} finally {- fs.writeFileSync(file, good);+ authDb().prepare("UPDATE auth_install SET secret = ?").run(secret);}+ // Data put back from before the sign-ups (no accounts in it) while accounts own files here.+ await withoutAccounts(async () => {+ expect((await sweepAccountFiles()).accounts).toBe(0);+ expect(fs.existsSync(absolutePath(own.relPath))).toBe(true);+ });// Read whole, a deleted account's files still go.const gone = auth.createAccount("[email protected]", "long enough").id;const theirs = mine(gone);diff --git a/tests/account-runs-admin.test.ts b/tests/account-runs-admin.test.tsindex b6fb7cd2..c823fe8f 100644--- a/tests/account-runs-admin.test.ts+++ b/tests/account-runs-admin.test.ts@@ -7,6 +7,7 @@ import type { AccountListing, AccountRun, AccountTotals } from "@/server/accountimport type { ListOptions } from "@/server/generations";import { TINY_PNG } from "./helpers/fake-comfy-runner";import { tempDir } from "./helpers/temp-dir";+import { authSecret } from "./helpers/auth-db";// Route handlers are called directly, outside a Next request: connection() has nothing to wait for.vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));@@ -73,13 +74,13 @@ function output(id: string, bytes = 0) {return asset;}-/** Session cookies: the owner's, account A's and C's, an owner-shaped one signed with auth.json's secret alone, and two at once. */+/** Session cookies: the owner's, account A's and C's, an owner-shaped one signed with the stored secret alone, and two at once. */const cookies = {} as Record<"owner" | "a" | "c" | "forged" | "doubled", string>;beforeAll(() => {auth.setPassword("install password");const owner = auth.createSession().value;const a = auth.createSession(A).value;- const secret = (JSON.parse(fs.readFileSync(path.join(dir, "auth.json"), "utf8")) as { secret: string }).secret;+ const secret = authSecret();const exp = Date.now() + 60_000;cookies.owner = `${auth.SESSION_COOKIE}=${owner}`;cookies.a = `${auth.SESSION_COOKIE}=${a}`;diff --git a/tests/account-space-limits.test.ts b/tests/account-space-limits.test.tsindex a70189fe..a608facc 100644--- a/tests/account-space-limits.test.ts+++ b/tests/account-space-limits.test.ts@@ -1,7 +1,6 @@-import fs from "node:fs";-import path from "node:path";import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";import { tempDir } from "./helpers/temp-dir";+import { setAccountCreatedAt } from "./helpers/auth-db";const jar = { set: vi.fn(), delete: vi.fn(), get: vi.fn() };vi.mock("next/headers", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/headers")>()), cookies: async () => jar }));vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));@@ -33,13 +32,8 @@ beforeAll(() => {fresh = auth.createAccount("[email protected]", "long enough").id;old = auth.createAccount("[email protected]", "long enough").id;for (const id of [fresh, old]) auth.setAccountGpu(id, { url: "https://gpu.example.com" });- // An account made 8 days ago (auth.json is the accounts' store).- const file = path.join(dir, "auth.json");- const data = JSON.parse(fs.readFileSync(file, "utf8")) as { accounts: { id: string; createdAt: number }[] };- for (const a of data.accounts) if (a.id === old) a.createdAt = Date.now() - 8 * DAY;- fs.writeFileSync(file, JSON.stringify(data));- // A new modified time, so the auth module reads the file again (it caches by that time).- fs.utimesSync(file, new Date(), new Date(Date.now() + 5000));+ // An account made 8 days ago.+ setAccountCreatedAt(old, Date.now() - 8 * DAY);});afterEach(() => {delete process.env.FUOBE_ACCOUNTS_DISK_GB;diff --git a/tests/auth-migration.test.ts b/tests/auth-migration.test.tsnew file mode 100644index 00000000..a7c5cc8e--- /dev/null+++ b/tests/auth-migration.test.ts@@ -0,0 +1,619 @@+/**+ * Sign-in data in SQLite (src/server/auth-store.ts): a new install, an older install's auth.json moving in (once, in one+ * transaction), the bridge that keeps auth.json in step for a server of an older build, putting it aside, crashes, a+ * second server starting at the same moment, a file that can't be read or can't go in, and 100,000 accounts.+ * Synthetic data only. Each "server" is the auth modules loaded afresh on a data folder (a restart).+ */+import { spawn } from "node:child_process";+import crypto from "node:crypto";+import fs from "node:fs";+import path from "node:path";+import { pathToFileURL } from "node:url";+import { afterAll, afterEach, describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";++delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_PUBLIC_SIGNUP;+delete process.env.FUOBE_AUTH_BRIDGE_MS;++const DAY = 86_400_000;+const MIN = 60_000;+const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");+const mac = (key: string, payload: string) => crypto.createHmac("sha256", key).update(payload).digest("base64url");+const hashPw = (pw: string) => {+ const salt = crypto.randomBytes(16);+ return `${salt.toString("hex")}:${crypto.scryptSync(pw, salt, 32).toString("hex")}`;+};++/** The auth modules loaded afresh on a data folder: a server (re)starting there. */+async function server(dir: string) {+ globalThis.__fuobeDb?.close();+ globalThis.__fuobeDb = undefined;+ globalThis.__fuobeAuthTablesError = undefined;+ globalThis.__fuobeSecretKey = undefined;+ process.env.FUOBE_DATA_DIR = dir;+ vi.resetModules();+ const auth = await import("@/server/auth");+ const store = await import("@/server/auth-store");+ const box = await import("@/server/secret-box");+ const keys = await import("@/server/account-keys");+ const db = () => globalThis.__fuobeDb!;+ const marker = () => db().prepare("SELECT * FROM auth_migration WHERE id = 1").get() as Record<string, unknown> | undefined;+ const count = (t: string) => (db().prepare(`SELECT COUNT(*) AS n FROM ${t}`).get() as { n: number }).n;+ return { auth, store, box, keys, db, marker, count };+}++afterEach(() => {+ globalThis.__fuobeAuthClock = undefined;+ globalThis.__fuobeAuthImportFault = undefined;+ delete process.env.FUOBE_AUTH_BRIDGE_MS;+});+afterAll(() => {+ globalThis.__fuobeDb?.close();+ globalThis.__fuobeDb = undefined;+});++const authFile = (dir: string) => path.join(dir, "auth.json");++/** What a server of an older build reads: the file, or "no file" (an open studio), or a file it can't read (fails closed). */+function legacyRead(dir: string): Record<string, unknown> & { unreadable?: true } {+ try {+ const d = JSON.parse(fs.readFileSync(authFile(dir), "utf8"));+ if (!d || typeof d !== "object" || Array.isArray(d)) throw new Error("not an object");+ return d;+ } catch (e) {+ if ((e as NodeJS.ErrnoException).code === "ENOENT") return { secret: "", tokens: [] };+ return { unreadable: true };+ }+}++/** A server of an older build writing auth.json (a temporary file, then a rename). */+function legacyWrite(dir: string, data: unknown): void {+ const tmp = `${authFile(dir)}.old.tmp`;+ fs.writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 0o600 });+ fs.renameSync(tmp, authFile(dir));+}++/** An auth.json as an older install has it, every optional field used, and cookies and tokens made before the move. */+function fixture(seal: (plain: string, context: string) => string) {+ const now = Date.now();+ const secret = crypto.randomBytes(32).toString("hex");+ const owner = hashPw("owner password");+ const ctx = (id: string, p: string) => `fuobe:account-key:v1:${id}:${p}`;+ const accounts = [+ {+ id: "acct00000000000001",+ email: "[email protected]",+ hash: hashPw("first password"),+ createdAt: now - 9 * DAY,+ lastLoginAt: now - DAY,+ gpu: { mode: "link", url: "https://gpu-a.example.com", token: "gpu-link-token-a" },+ keys: {+ fal: { sealed: seal("fal-key-first:ab12", ctx("acct00000000000001", "fal")), last4: "ab12", addedAt: now - DAY },+ replicate: { sealed: seal("r8_replicate_first_cd34", ctx("acct00000000000001", "replicate")), last4: "cd34", addedAt: now - DAY, rejectedAt: now - 1000 },+ },+ futureField: { kept: true },+ },+ {+ id: "acct00000000000002",+ email: "[email protected]",+ hash: hashPw("second password"),+ createdAt: now - 5 * DAY,+ passwordChangedAt: now - 2 * DAY,+ disabled: false,+ sessionsAfter: now - 3 * DAY,+ gpu: { url: "https://gpu-b.example.com" },+ },+ { id: "acct00000000000003", email: "[email protected]", hash: hashPw("third password"), createdAt: now - DAY, disabled: true, gpu: { mode: "computer" } },+ { id: "acct00000000000004", email: "[email protected]", hash: hashPw("fourth password"), createdAt: now - 1000, keys: {} },+ ];+ const tokenValue = () => `fuobe_${crypto.randomBytes(24).toString("base64url")}`;+ const tokens = [tokenValue(), tokenValue(), tokenValue()];+ const exp = now + 29 * DAY;+ const ownerCookie = `${exp}.${mac(`${secret}.${sha(owner)}`, String(exp))}`;+ const signedOutCookie = `${exp - 1}.${mac(`${secret}.${sha(owner)}`, String(exp - 1))}`;+ const accountCookie = (a: (typeof accounts)[number]) => `${exp}.${a.id}.${mac(`${secret}.${sha(a.hash)}`, `${exp}.${a.id}`)}`;+ const legacyCookie = (a: (typeof accounts)[number]) => `${exp}.${a.id}.${mac(secret, `${exp}.${a.id}`)}`;+ const data = {+ password: owner,+ secret,+ tokens: [+ { id: "tok1", name: "CI", hash: sha(tokens[0]), prefix: tokens[0].slice(0, 12), createdAt: now - DAY, lastUsedAt: now - 2 * 3_600_000 },+ { id: "tok2", name: "Laptop", hash: sha(tokens[1]), prefix: tokens[1].slice(0, 12), createdAt: now - DAY },+ { id: "tok3", name: "MCP", hash: sha(tokens[2]), prefix: tokens[2].slice(0, 12), createdAt: now - 1000 },+ ],+ accounts,+ publicSignup: true,+ signedOut: [+ { hash: sha(signedOutCookie), exp: exp - 1 },+ { hash: sha("an expired cookie"), exp: now - 1000 },+ ],+ laterSetting: { kept: "as it was" },+ };+ return {+ data,+ tokens,+ cookies: {+ owner: ownerCookie,+ signedOut: signedOutCookie,+ first: accountCookie(accounts[0]),+ second: accountCookie(accounts[1]),+ third: accountCookie(accounts[2]),+ firstLegacy: legacyCookie(accounts[0]),+ secondLegacy: legacyCookie(accounts[1]),+ },+ };+}++/** A data folder with an older install's auth.json (and the server key its account keys were sealed with). */+async function olderInstall(prefix: string) {+ const dir = tempDir(prefix);+ const srv = await server(dir);+ const fx = fixture(srv.box.seal);+ fs.writeFileSync(authFile(dir), JSON.stringify(fx.data, null, 2), { mode: 0o600 });+ return { dir, srv, fx, original: fs.readFileSync(authFile(dir), "utf8") };+}++describe("a new install", () => {+ it("starts open with nothing stored; the first change sets the store up and leaves a note no older build can read", async () => {+ const dir = tempDir("fuobe-auth-new-");+ let srv = await server(dir);+ expect(srv.auth.authEnabled()).toBe(false);+ expect(srv.store.authStoreMode()).toBe("fresh");+ expect(srv.auth.listAccounts()).toEqual([]);+ expect(srv.marker()).toBeUndefined();+ expect(fs.existsSync(authFile(dir))).toBe(false);+ srv.auth.setPassword("owner password");+ expect(srv.marker()).toMatchObject({ source: "new", state: "done" });+ expect(() => JSON.parse(fs.readFileSync(authFile(dir), "utf8"))).toThrow();+ expect(fs.readFileSync(authFile(dir), "utf8")).toContain("fuobe.db");+ // An older build pointed at this folder fails closed instead of opening the studio.+ expect(legacyRead(dir).unreadable).toBe(true);+ srv = await server(dir);+ expect(srv.auth.authEnabled()).toBe(true);+ expect(srv.auth.checkPassword("owner password")).toBe(true);+ expect(srv.store.authStoreMode()).toBe("done");+ });++ it("moves in an auth.json put there before the first change, and ignores one put back after", async () => {+ const dir = tempDir("fuobe-auth-drop-");+ let srv = await server(dir);+ expect(srv.auth.authEnabled()).toBe(false);+ legacyWrite(dir, { password: hashPw("dropped password"), secret: "a".repeat(64), tokens: [] });+ expect(srv.auth.authEnabled()).toBe(true);+ expect(srv.auth.checkPassword("dropped password")).toBe(true);+ expect(srv.marker()).toMatchObject({ source: "auth.json", state: "bridge" });+ // Put aside, then an auth.json without a password put back: not read.+ globalThis.__fuobeAuthClock = () => Date.now() + 11 * MIN;+ expect(srv.store.authStoreMode()).toBe("done");+ legacyWrite(dir, { secret: "", tokens: [] });+ srv = await server(dir);+ expect(srv.auth.authEnabled()).toBe(true);+ expect(srv.auth.checkPassword("dropped password")).toBe(true);+ });+});++describe("an older install's auth.json moves in", () => {+ it("whole: every account, token and setting reads back the same; cookies, tokens, passwords and sealed keys made before still work", async () => {+ const { dir, srv, fx, original } = await olderInstall("fuobe-auth-import-");+ const { auth, store, keys } = srv;+ expect(store.authStoreMode()).toBe("bridge");+ expect(srv.marker()).toMatchObject({ source: "auth.json", state: "bridge" });+ expect(JSON.parse(srv.marker()!.counts_json as string)).toEqual({ accounts: 4, tokens: 3, keys: 2, gpus: 3, signedOut: 1 });+ expect([srv.count("auth_accounts"), srv.count("auth_tokens"), srv.count("auth_account_keys"), srv.count("auth_account_gpu"), srv.count("auth_signed_out")]).toEqual([4, 3, 2, 3, 1]);+ // Moving in doesn't touch the file.+ expect(fs.readFileSync(authFile(dir), "utf8")).toBe(original);++ // Every account as it was (the "disabled: false" and empty keys of the file mean the same as leaving them out).+ const [first, second, third, fourth] = fx.data.accounts;+ expect(auth.accountById(first.id)).toEqual(first);+ const without = (o: object, key: string) => Object.fromEntries(Object.entries(o).filter(([k]) => k !== key));+ expect(auth.accountById(second.id)).toEqual(without(second, "disabled"));+ expect(auth.accountById(third.id)).toEqual(third);+ expect(auth.accountById(fourth.id)).toEqual(without(fourth, "keys"));+ const out = store.exportJson();+ expect(out.laterSetting).toEqual({ kept: "as it was" });+ expect(out.tokens).toEqual(fx.data.tokens);+ expect(out.signedOut).toEqual([fx.data.signedOut[0]]);+ expect(out.publicSignup).toBe(true);+ expect(auth.listAccounts().map((a) => a.email)).toEqual(["[email protected]", "[email protected]", "[email protected]", "[email protected]"]);+ expect(auth.listAccounts()[3]).toMatchObject({ gpu: true, keys: ["fal", "replicate"], disabled: false });++ // Sign-in made before the move.+ expect(auth.authEnabled()).toBe(true);+ expect(auth.publicSignupSetting()).toBe(true);+ expect(auth.checkPassword("owner password")).toBe(true);+ expect(auth.validSession(fx.cookies.owner)).toBe(true);+ expect(auth.sessionViewer(fx.cookies.signedOut)).toBeNull();+ expect(auth.sessionViewer(fx.cookies.first)).toMatchObject({ kind: "account", account: { email: "[email protected]" } });+ expect(auth.sessionViewer(fx.cookies.second)).toMatchObject({ kind: "account", account: { email: "[email protected]" } });+ expect(auth.sessionViewer(fx.cookies.third)).toBeNull(); // switched off+ expect(auth.sessionViewer(fx.cookies.firstLegacy)).toMatchObject({ kind: "account" });+ expect(auth.sessionViewer(fx.cookies.secondLegacy)).toBeNull(); // changed its password since+ for (const t of fx.tokens) expect(auth.validToken(`Bearer ${t}`)).toBe(true);+ expect(auth.checkAccount("[email protected]", "first password")?.id).toBe(first.id);+ await expect(auth.verifyAccount("[email protected]", "second password")).resolves.toMatchObject({ id: second.id });+ expect(auth.checkAccount("[email protected]", "second password")).toBeNull();+ // Sealed keys open with the same server key: nothing was sealed again.+ expect(keys.accountKey(first.id, "fal")).toBe("fal-key-first:ab12");+ expect(keys.accountKey(first.id, "replicate")).toBe("r8_replicate_first_cd34");+ expect(auth.accountKeyRecord(first.id, "fal")?.sealed).toBe(first.keys!.fal!.sealed);+ expect(auth.accountGpu(first.id)).toEqual(first.gpu);+ expect(auth.accountGpu(second.id)).toEqual({ url: "https://gpu-b.example.com" });+ expect(auth.accountGpu(third.id)).toBeNull(); // switched off++ // A restart moves nothing in again.+ const startedAt = srv.marker()!.started_at;+ const again = await server(dir);+ expect(again.auth.listAccounts()).toHaveLength(4);+ expect(again.marker()!.started_at).toBe(startedAt);+ expect(again.count("auth_accounts")).toBe(4);+ expect(again.auth.validSession(fx.cookies.owner)).toBe(true);+ });++ it("every sign-in path works on the moved data", async () => {+ const { srv, fx } = await olderInstall("fuobe-auth-paths-");+ const { auth } = srv;+ const [first, second] = fx.data.accounts;+ // A new password for an account ends its other sign-ins.+ const changed = await auth.setAccountPassword(first.id, "first password", "first new password");+ expect(auth.sessionViewer(fx.cookies.first)).toBeNull();+ expect(auth.sessionViewer(fx.cookies.firstLegacy)).toBeNull();+ expect(auth.sessionViewer(auth.createSession(first.id).value)).toMatchObject({ kind: "account" });+ expect(changed.passwordChangedAt).toBeGreaterThan(0);+ await expect(auth.setAccountPassword(first.id, "wrong", "whatever long")).rejects.toMatchObject({ status: 403 });+ await expect(auth.setAccountPassword("nobody", "x", "whatever long")).rejects.toMatchObject({ status: 404 });+ // Owner: switch off, sign out everywhere, delete.+ auth.setAccountDisabled(second.id, true);+ expect(auth.sessionViewer(fx.cookies.second)).toBeNull();+ auth.setAccountDisabled(second.id, false);+ expect(auth.sessionViewer(fx.cookies.second)).toMatchObject({ kind: "account" });+ auth.signOutAccount(second.id);+ expect(auth.sessionViewer(fx.cookies.second)).toBeNull();+ expect(() => auth.setAccountDisabled("nobody", true)).toThrow(/No such account/);+ expect(() => auth.signOutAccount("nobody")).toThrow(/No such account/);+ expect(() => auth.setAccountGpu("nobody", null)).toThrow(/No such account/);+ expect(() => auth.setAccountKey("nobody", "fal", null)).toThrow(/No such account/);+ auth.deleteAccount(first.id);+ expect(auth.accountById(first.id)).toBeUndefined();+ expect(auth.accountKeyRecord(first.id, "fal")).toBeNull();+ expect(srv.db().prepare("SELECT COUNT(*) AS n FROM auth_account_keys WHERE account_id = ?").get(first.id)).toEqual({ n: 0 });+ expect(srv.db().prepare("SELECT COUNT(*) AS n FROM auth_account_gpu WHERE account_id = ?").get(first.id)).toEqual({ n: 0 });+ expect(() => auth.deleteAccount(first.id)).toThrow(/No such account/);+ // Sign-up: one account per email, whatever its case.+ const made = auth.createAccount("[email protected]", "long enough");+ expect(() => auth.createAccount("[email protected]", "long enough")).toThrow(expect.objectContaining({ status: 409 }));+ expect(auth.checkAccount("[email protected]", "long enough")?.id).toBe(made.id);+ // Sign out (this cookie only), then everyone (with tokens).+ const owner = auth.createSession().value;+ await new Promise((r) => setTimeout(r, 5)); // another expiry: another cookie+ const other = auth.createSession().value;+ auth.endSession(owner);+ expect(auth.validSession(owner)).toBe(false);+ expect(auth.validSession(other)).toBe(true);+ const v = auth.authVersion();+ auth.signOutEveryone({ tokens: true });+ expect(auth.authVersion()).not.toBe(v);+ expect(auth.validSession(other)).toBe(false);+ expect(auth.validSession(fx.cookies.owner)).toBe(false);+ for (const t of fx.tokens) expect(auth.validToken(`Bearer ${t}`)).toBe(false);+ expect(auth.authStatus().tokens).toEqual([]);+ // Tokens: made, used, revoked.+ const { token, info } = auth.createToken("Script");+ expect(auth.validToken(`Bearer ${token}`)).toBe(true);+ expect(auth.authStatus().tokens).toEqual([expect.objectContaining({ id: info.id, name: "Script", lastUsedAt: expect.any(Number) })]);+ auth.revokeToken(info.id);+ expect(auth.validToken(`Bearer ${token}`)).toBe(false);+ // The public sign-up switch, and the Settings password.+ auth.setPublicSignup(false);+ expect(auth.publicSignupSetting()).toBe(false);+ auth.setPassword(null);+ expect(auth.authEnabled()).toBe(false);+ auth.setPassword("owner password two");+ expect(auth.checkPassword("owner password two")).toBe(true);+ // The sweep's account list.+ expect(auth.readAccountIds()).toEqual(new Set(auth.listAccounts().map((a) => a.id)));+ expect(auth.accountsCsv().split("\r\n")[0]).toBe("email,created,last_login,gpu_connected,fal_key,replicate_key,disabled");+ });+});++describe("the bridge: auth.json kept in step for a server of an older build", () => {+ it("writes each change to auth.json in its usual format, and reads back what an older server writes there", async () => {+ const { dir, srv, fx } = await olderInstall("fuobe-auth-bridge-");+ const { auth } = srv;+ expect(srv.store.authStoreMode()).toBe("bridge");+ // A change here: the older server sees it.+ const made = auth.createAccount("[email protected]", "long enough");+ const text = fs.readFileSync(authFile(dir), "utf8");+ expect(text).toBe(JSON.stringify(srv.store.exportJson(), null, 2));+ const seen = legacyRead(dir) as { accounts: { id: string; email: string }[]; password: string; secret: string };+ expect(seen.accounts.map((a) => a.email)).toContain("[email protected]");+ expect(seen.password).toBe(fx.data.password);+ expect(seen.secret).toBe(fx.data.secret);+ if (process.platform !== "win32") expect(fs.statSync(authFile(dir)).mode & 0o777).toBe(0o600);++ // The older server signs someone up, revokes a token and signs a cookie out: seen here on the next call.+ const older = legacyRead(dir) as typeof fx.data & { accounts: Record<string, unknown>[] };+ older.accounts.push({ id: "acctolder000000001", email: "[email protected]", hash: hashPw("older password"), createdAt: Date.now(), lastLoginAt: Date.now() });+ older.tokens = older.tokens.filter((t) => t.id !== "tok2");+ older.signedOut = [...(older.signedOut ?? []), { hash: sha(fx.cookies.first), exp: Date.now() + DAY }];+ legacyWrite(dir, older);+ expect(auth.checkAccount("[email protected]", "older password")?.id).toBe("acctolder000000001");+ expect(auth.validToken(`Bearer ${fx.tokens[1]}`)).toBe(false);+ expect(auth.validToken(`Bearer ${fx.tokens[0]}`)).toBe(true);+ expect(auth.sessionViewer(fx.cookies.first)).toBeNull();+ expect(auth.accountById(made.id)?.email).toBe("[email protected]");+ // Then a change here keeps both.+ auth.setAccountDisabled(made.id, true);+ const after = legacyRead(dir) as { accounts: { id: string; disabled?: boolean }[] };+ expect(after.accounts.find((a) => a.id === made.id)?.disabled).toBe(true);+ expect(after.accounts.some((a) => a.id === "acctolder000000001")).toBe(true);++ // auth.json removed: written again (an older server would otherwise see no password).+ fs.rmSync(authFile(dir));+ expect(auth.authEnabled()).toBe(true);+ expect((legacyRead(dir) as { password?: string }).password).toBe(fx.data.password);++ // An older server's file that can't be read back in (a broken write) leaves the database as it was.+ fs.writeFileSync(authFile(dir), "{ broken");+ expect(auth.checkAccount("[email protected]", "older password")?.id).toBe("acctolder000000001");+ auth.setPublicSignup(false);+ expect((legacyRead(dir) as { publicSignup?: boolean }).publicSignup).toBeUndefined();+ expect(legacyRead(dir).unreadable).toBeUndefined();+ });++ it("is put aside after 10 minutes once quiet for 3: kept as auth.json.migrated-<time>, with a note no older build can read", async () => {+ const { dir, srv, fx } = await olderInstall("fuobe-auth-retire-");+ const t0 = Date.now();+ expect(srv.store.authStoreMode()).toBe("bridge");+ // An older server still writing at minute 9: not put aside at minute 11, but at minute 12.5.+ globalThis.__fuobeAuthClock = () => t0 + 9 * MIN;+ legacyWrite(dir, { ...legacyRead(dir), publicSignup: false });+ expect(srv.store.authStoreMode()).toBe("bridge");+ globalThis.__fuobeAuthClock = () => t0 + 11 * MIN;+ expect(srv.store.authStoreMode()).toBe("bridge");+ expect(srv.auth.publicSignupSetting()).toBe(false);+ const last = fs.readFileSync(authFile(dir), "utf8");+ globalThis.__fuobeAuthClock = () => t0 + 12.5 * MIN;+ expect(srv.store.authStoreMode()).toBe("done");+ const m = srv.marker()!;+ expect(m).toMatchObject({ state: "done", backup_file: expect.stringMatching(/^auth\.json\.migrated-\d{8}T\d{6}Z$/) });+ const backup = path.join(dir, m.backup_file as string);+ expect(fs.readFileSync(backup, "utf8")).toBe(last);+ if (process.platform !== "win32") {+ expect(fs.statSync(backup).mode & 0o777).toBe(0o600);+ expect(fs.statSync(authFile(dir)).mode & 0o777).toBe(0o600);+ }+ expect(() => JSON.parse(fs.readFileSync(authFile(dir), "utf8"))).toThrow();+ expect(legacyRead(dir).unreadable).toBe(true);+ // Changes no longer touch auth.json; a restart moves nothing in.+ srv.auth.createAccount("[email protected]", "long enough");+ expect(legacyRead(dir).unreadable).toBe(true);+ const again = await server(dir);+ expect(again.store.authStoreMode()).toBe("done");+ expect(again.auth.validSession(fx.cookies.owner)).toBe(true);+ expect(again.auth.listAccounts()).toHaveLength(5);+ expect(fs.readdirSync(dir).filter((f) => f.startsWith("auth.json.migrated-"))).toHaveLength(1);+ });++ it("finishes putting auth.json aside after a crash between the database's change and the rename", async () => {+ const { dir, srv, original } = await olderInstall("fuobe-auth-retire-crash-");+ expect(srv.store.authStoreMode()).toBe("bridge");+ srv.db().prepare("UPDATE auth_migration SET state = 'done', backup_file = 'auth.json.migrated-20261104T000000Z', retired_at = ? WHERE id = 1").run(Date.now());+ const again = await server(dir);+ expect(again.store.authStoreMode()).toBe("done");+ expect(fs.readFileSync(path.join(dir, "auth.json.migrated-20261104T000000Z"), "utf8")).toBe(original);+ expect(legacyRead(dir).unreadable).toBe(true);+ // The note gone too: written again.+ fs.rmSync(authFile(dir));+ const third = await server(dir);+ expect(third.store.authStoreMode()).toBe("done");+ expect(legacyRead(dir).unreadable).toBe(true);+ });+});++describe("a crash, or another server, while moving in", () => {+ it("a crash in the middle leaves no rows and no marker, and the next start moves it all in", async () => {+ const { dir, srv, original, fx } = await olderInstall("fuobe-auth-crash-");+ globalThis.__fuobeAuthImportFault = () => {+ throw new Error("the power went out");+ };+ expect(srv.store.authStoreMode()).toBe("failed");+ expect(srv.auth.authEnabled()).toBe(true);+ expect(srv.auth.validSession(fx.cookies.owner)).toBe(false);+ expect(srv.marker()).toBeUndefined();+ expect(srv.count("auth_accounts") + srv.count("auth_tokens") + srv.count("auth_install")).toBe(0);+ expect(fs.readFileSync(authFile(dir), "utf8")).toBe(original);+ globalThis.__fuobeAuthImportFault = undefined;+ const again = await server(dir);+ expect(again.store.authStoreMode()).toBe("bridge");+ expect(again.count("auth_accounts")).toBe(4);+ expect(again.auth.validSession(fx.cookies.owner)).toBe(true);+ });++ const child = (dir: string, go: string, ...args: string[]) =>+ new Promise<{ code: number | null; out: string }>((resolve) => {+ const root = path.join(import.meta.dirname, "..");+ const p = spawn(process.execPath, ["--no-warnings", "--import", pathToFileURL(path.join(root, "tests/helpers/ts-register.mjs")).href, path.join(root, "tests/helpers/auth-child.ts"), ...args, go], {+ cwd: root,+ env: { ...process.env, FUOBE_DATA_DIR: dir },+ });+ let out = "";+ p.stdout.on("data", (d) => (out += d));+ p.stderr.on("data", (d) => (out += d));+ p.on("close", (code) => resolve({ code, out }));+ });+ const result = (out: string) => JSON.parse(/RESULT (.*)/.exec(out)?.[1] ?? "null") as Record<string, unknown> | null;++ it("servers starting at the same moment move it in once", async () => {+ const { dir } = await olderInstall("fuobe-auth-race-");+ // The older install's database is there already (its own tables made); its auth.json waits to move in.+ (await import("@/server/db")).db();+ globalThis.__fuobeDb?.close();+ globalThis.__fuobeDb = undefined;+ const go = path.join(dir, "go");+ const runs = [1, 2, 3, 4].map(() => child(dir, go, "start", "-"));+ await new Promise((r) => setTimeout(r, 2500));+ fs.writeFileSync(go, "");+ const done = await Promise.all(runs);+ for (const d of done) expect(d.code, d.out).toBe(0);+ expect(done.map((d) => result(d.out))).toEqual(Array(4).fill({ mode: "bridge", accounts: 4 }));+ expect(done.filter((d) => d.out.includes("Sign-in data moved")).length).toBe(1);+ const after = await server(dir);+ expect(after.auth.listAccounts()).toHaveLength(4);+ expect(after.count("auth_accounts")).toBe(4);+ expect(JSON.parse(after.marker()!.counts_json as string)).toMatchObject({ accounts: 4 });+ }, 60_000);++ it("sign-ups with one email at the same moment on several servers: one account", async () => {+ const dir = tempDir("fuobe-auth-signup-race-");+ // A new install that has started once (its database made), with nothing stored yet.+ await server(dir);+ (await import("@/server/db")).db();+ globalThis.__fuobeDb?.close();+ globalThis.__fuobeDb = undefined;+ const go = path.join(dir, "go");+ const runs = [1, 2, 3, 4].map(() => child(dir, go, "signup", "[email protected]"));+ await new Promise((r) => setTimeout(r, 2500));+ fs.writeFileSync(go, "");+ const done = await Promise.all(runs);+ for (const d of done) expect(d.code, d.out).toBe(0);+ const results = done.map((d) => result(d.out)?.result);+ expect(results.filter((r) => r === "ok")).toHaveLength(1);+ expect(results.filter((r) => r === "409")).toHaveLength(3);+ const srv = await server(dir);+ expect(srv.auth.listAccounts().map((a) => a.email)).toEqual(["[email protected]"]);+ }, 60_000);+});++describe("an auth.json that can't be read, or can't go in", () => {+ it("can't be read: sign-in stays on, nobody is signed in, nothing is written; fixed, it moves in", async () => {+ const { dir, srv, fx, original } = await olderInstall("fuobe-auth-unreadable-");+ fs.writeFileSync(authFile(dir), "{ not json");+ expect(srv.store.authStoreMode()).toBe("unreadable");+ expect(srv.auth.authEnabled()).toBe(true);+ expect(srv.auth.authStatus().enabled).toBe(true);+ expect(srv.auth.validSession(fx.cookies.owner)).toBe(false);+ expect(srv.auth.validToken(`Bearer ${fx.tokens[0]}`)).toBe(false);+ expect(srv.auth.checkPassword("owner password")).toBe(false);+ expect(() => srv.auth.createAccount("[email protected]", "long enough")).toThrow(/can't be read/);+ expect(() => srv.auth.createSession()).toThrow(/can't be read/);+ expect(() => srv.auth.readAccountIds()).toThrow();+ expect(srv.auth.listAccounts()).toEqual([]);+ expect(fs.readFileSync(authFile(dir), "utf8")).toBe("{ not json");+ expect(srv.marker()).toBeUndefined();+ // Not a request-blocking failure: /login still answers (and asks for a password nobody can use).+ expect(srv.store.authStoreFailed()).toBe(false);+ fs.writeFileSync(authFile(dir), original);+ fs.utimesSync(authFile(dir), new Date(), new Date(Date.now() + 10_000));+ expect(srv.auth.validSession(fx.cookies.owner)).toBe(true);+ expect(srv.store.authStoreMode()).toBe("bridge");+ });++ it("the note an older build can't read, with no sign-in data in the database (fuobe.db lost): fails closed", async () => {+ const dir = tempDir("fuobe-auth-note-");+ let srv = await server(dir);+ srv.auth.setPassword("owner password");+ globalThis.__fuobeDb?.close();+ globalThis.__fuobeDb = undefined;+ for (const f of ["fuobe.db", "fuobe.db-wal", "fuobe.db-shm"]) fs.rmSync(path.join(dir, f), { force: true });+ srv = await server(dir);+ expect(srv.store.authStoreMode()).toBe("unreadable");+ expect(srv.auth.authEnabled()).toBe(true);+ });++ for (const [what, edit] of [+ ["two accounts with one email", (d: { accounts: { email: string; id: string }[] }) => (d.accounts[1].email = d.accounts[0].email)],+ ["an email that isn't lower-case", (d: { accounts: { email: string; id: string }[] }) => (d.accounts[1].email = "[email protected]")],+ ["two accounts with one id", (d: { accounts: { email: string; id: string }[] }) => (d.accounts[1].id = d.accounts[0].id)],+ ] as const) {+ it(`can't go in (${what}): nothing changes, sign-in fails closed and every request gets 503, /login too`, async () => {+ const { dir, srv, fx } = await olderInstall("fuobe-auth-bad-");+ const bad = structuredClone(fx.data);+ edit(bad);+ fs.writeFileSync(authFile(dir), JSON.stringify(bad, null, 2));+ const before = fs.readFileSync(authFile(dir), "utf8");+ const errors = vi.spyOn(console, "error").mockImplementation(() => {});+ expect(srv.store.authStoreMode()).toBe("failed");+ expect(srv.store.authStoreFailed()).toBe(true);+ expect(srv.auth.authEnabled()).toBe(true);+ expect(srv.auth.validSession(fx.cookies.owner)).toBe(false);+ expect(() => srv.auth.setPassword("another password")).toThrow(/can't be read/);+ expect(srv.marker()).toBeUndefined();+ expect(srv.count("auth_accounts") + srv.count("auth_install")).toBe(0);+ expect(fs.readFileSync(authFile(dir), "utf8")).toBe(before);+ // The log says what kind of problem, never an email, a hash or the secret.+ const logged = errors.mock.calls.flat().join("\n");+ expect(logged).toMatch(/couldn't be moved into the database/);+ for (const a of fx.data.accounts) {+ expect(logged).not.toContain(a.email);+ expect(logged).not.toContain(a.hash);+ }+ expect(logged).not.toContain(fx.data.secret);+ errors.mockRestore();+ const { proxy } = await import("@/proxy");+ const { NextRequest } = await import("next/server");+ for (const p of ["/login", "/", "/api/auth/public"]) expect(proxy(new NextRequest(`http://localhost:3000${p}`)).status, p).toBe(503);+ });+ }+});++describe("100,000 accounts", () => {+ it("move in once, and every lookup stays quick", async () => {+ const dir = tempDir("fuobe-auth-100k-");+ const now = Date.now();+ const secret = crypto.randomBytes(32).toString("hex");+ const N = 100_000;+ const fakeHash = (i: number) => `${i.toString(16).padStart(32, "0")}:${sha(String(i))}`;+ const accounts = Array.from({ length: N }, (_, i) => ({+ id: `acct${i.toString(16).padStart(14, "0")}`,+ email: `member-${i}@example.com`,+ hash: fakeHash(i),+ createdAt: now - (N - i) * 1000,+ lastLoginAt: now - i,+ ...(i % 10 === 0 && { gpu: { url: `https://gpu-${i}.example.com` } }),+ }));+ let srv = await server(dir);+ fs.writeFileSync(authFile(dir), JSON.stringify({ password: hashPw("owner password"), secret, tokens: [], accounts }, null, 2));+ let t = performance.now();+ expect(srv.store.authStoreMode()).toBe("bridge");+ const importMs = performance.now() - t;+ expect(srv.count("auth_accounts")).toBe(N);+ expect(importMs).toBeLessThan(30_000);+ // Put aside (the bridge rewrites the whole file on each change, for 10 minutes only).+ globalThis.__fuobeAuthClock = () => now + 11 * MIN;+ expect(srv.store.authStoreMode()).toBe("done");+ globalThis.__fuobeAuthClock = undefined;+ srv = await server(dir);+ const pick = () => accounts[Math.floor(Math.random() * N)];+ const exp = Date.now() + DAY;+ const cookieOf = (a: (typeof accounts)[number]) => `${exp}.${a.id}.${mac(`${secret}.${sha(a.hash)}`, `${exp}.${a.id}`)}`;+ const avg = (n: number, fn: () => void) => {+ const start = performance.now();+ for (let i = 0; i < n; i++) fn();+ return (performance.now() - start) / n;+ };+ expect(avg(2000, () => expect(srv.auth.accountById(pick().id)).toBeDefined())).toBeLessThan(1);+ expect(avg(2000, () => expect(srv.auth.sessionViewer(cookieOf(pick()))?.kind).toBe("account"))).toBeLessThan(1);+ expect(avg(200, () => srv.auth.signOutAccount(pick().id))).toBeLessThan(5);+ t = performance.now();+ expect(srv.auth.listAccounts()).toHaveLength(N);+ expect(performance.now() - t).toBeLessThan(3000);+ t = performance.now();+ srv.auth.createAccount("[email protected]", "long enough");+ expect(performance.now() - t).toBeLessThan(500); // the scrypt hash, then one insert+ expect(() => srv.auth.createAccount(`member-${N - 1}@example.com`, "long enough")).toThrow(expect.objectContaining({ status: 409 }));+ }, 180_000);+});++describe("files", () => {+ it.skipIf(process.platform === "win32")("the database and its -wal and -shm files are readable by the server's user only", async () => {+ const dir = tempDir("fuobe-auth-modes-");+ const srv = await server(dir);+ srv.auth.setPassword("owner password");+ for (const f of ["fuobe.db", "fuobe.db-wal", "fuobe.db-shm"]) {+ const file = path.join(dir, f);+ if (fs.existsSync(file)) expect(fs.statSync(file).mode & 0o077, f).toBe(0);+ }+ });+});diff --git a/tests/auth.test.ts b/tests/auth.test.tsindex 5fb9a64c..1c6fbba1 100644--- a/tests/auth.test.ts+++ b/tests/auth.test.ts@@ -1,7 +1,6 @@-import fs from "node:fs";-import path from "node:path";import { describe, expect, it } from "vitest";import { tempDir } from "./helpers/temp-dir";+import { dbBytes } from "./helpers/auth-db";const dir = tempDir("fuobe-auth-");process.env.FUOBE_DATA_DIR = dir;@@ -20,7 +19,7 @@ describe("auth", () => {expect(auth.authEnabled()).toBe(true);expect(auth.checkPassword("correct horse")).toBe(true);expect(auth.checkPassword("wrong horse")).toBe(false);- expect(fs.readFileSync(path.join(dir, "auth.json"), "utf8")).not.toContain("correct horse");+ expect(dbBytes(dir)).not.toContain("correct horse");});it("signs sessions and signs everyone out when the password changes", () => {@@ -39,7 +38,7 @@ describe("auth", () => {expect(auth.validToken(`Bearer ${token}`)).toBe(true);expect(auth.validToken(`Bearer ${token}x`)).toBe(false);expect(auth.validToken(token)).toBe(false);- expect(fs.readFileSync(path.join(dir, "auth.json"), "utf8")).not.toContain(token);+ expect(dbBytes(dir)).not.toContain(token);expect(auth.authStatus().tokens[0]).toMatchObject({ name: "CI", prefix: token.slice(0, 12) });expect(auth.authStatus().tokens[0]).not.toHaveProperty("hash");auth.revokeToken(info.id);diff --git a/tests/helpers/auth-child.ts b/tests/helpers/auth-child.tsnew file mode 100644index 00000000..aceb9cc0--- /dev/null+++ b/tests/helpers/auth-child.ts@@ -0,0 +1,26 @@+/**+ * A second (third…) server on the same data folder, as its own process: tests/auth-migration.test.ts starts several at+ * once. Loads the sign-in modules, waits for the "go" file so they all act at the same moment, then:+ * - start: sets the store up (moves auth.json in when it is waiting) and prints the mode and the number of accounts;+ * - signup <email>: signs up with that email and prints "ok" or the refusal's status.+ * Run with: node --import tests/helpers/ts-register.mjs tests/helpers/auth-child.ts <action> <arg> <go file>+ */+import fs from "node:fs";++const [action, arg, go] = process.argv.slice(2);+const auth = await import("@/server/auth");+const store = await import("@/server/auth-store");+while (go && !fs.existsSync(go)) await new Promise((r) => setTimeout(r, 2));+let out: Record<string, unknown>;+if (action === "start") {+ const mode = store.authStoreMode();+ out = { mode, accounts: auth.listAccounts().length };+} else {+ try {+ auth.createAccount(arg, "long enough");+ out = { result: "ok" };+ } catch (e) {+ out = { result: String((e as { status?: number }).status ?? (e as Error).message) };+ }+}+console.log(`RESULT ${JSON.stringify(out)}`);diff --git a/tests/helpers/auth-db.ts b/tests/helpers/auth-db.tsnew file mode 100644index 00000000..22b8675f--- /dev/null+++ b/tests/helpers/auth-db.ts@@ -0,0 +1,48 @@+/**+ * Sign-in data in the test's database (src/server/auth-store.ts), for tests that look at what is stored or change it+ * behind the auth module's back. The database is the one the auth module opened: call an auth function first.+ */+import type Database from "better-sqlite3";+import fs from "node:fs";+import path from "node:path";++/** The database the server opened. */+export function authDb(): Database.Database {+ const d = globalThis.__fuobeDb;+ if (!d) throw new Error("Open the database first (call an auth function)");+ return d;+}++/** The install's cookie secret. */+export const authSecret = () => (authDb().prepare("SELECT secret FROM auth_install WHERE id = 1").get() as { secret: string } | undefined)?.secret ?? "";++/** Make an account older (or newer) than it is. */+export function setAccountCreatedAt(id: string, at: number): void {+ if (!authDb().prepare("UPDATE auth_accounts SET created_at = ? WHERE id = ?").run(at, id).changes) throw new Error(`No account ${id}`);+}++/** Rows of a sign-in table for one account. */+export const accountRows = (table: "auth_account_gpu" | "auth_account_keys", id: string) => authDb().prepare(`SELECT * FROM ${table} WHERE account_id = ?`).all(id) as Record<string, unknown>[];++/** Every byte of the database file, with the write-ahead log folded in: for "never stored as it is" checks. */+export function dbBytes(dir: string): string {+ authDb().pragma("wal_checkpoint(TRUNCATE)");+ return ["fuobe.db", "fuobe.db-wal"].map((f) => (fs.existsSync(path.join(dir, f)) ? fs.readFileSync(path.join(dir, f)).toString("latin1") : "")).join("\n");+}++/** Run `fn` while the accounts table is empty (their GPU and key rows stay), then put every account back. */+export async function withoutAccounts<T>(fn: () => T | Promise<T>): Promise<T> {+ const d = authDb();+ const rows = d.prepare("SELECT * FROM auth_accounts ORDER BY rowid").all() as Record<string, unknown>[];+ d.pragma("foreign_keys = OFF");+ d.prepare("DELETE FROM auth_accounts").run();+ try {+ return await fn();+ } finally {+ for (const r of rows) {+ const cols = Object.keys(r);+ d.prepare(`INSERT INTO auth_accounts (${cols.join(", ")}) VALUES (${cols.map(() => "?").join(", ")})`).run(...cols.map((c) => r[c]));+ }+ d.pragma("foreign_keys = ON");+ }+}diff --git a/tests/helpers/ts-hooks.mjs b/tests/helpers/ts-hooks.mjsnew file mode 100644index 00000000..dd26e00d--- /dev/null+++ b/tests/helpers/ts-hooks.mjs@@ -0,0 +1,36 @@+/**+ * Lets a child `node` process load the server's TypeScript the way the tests do: "@/…" from src, the "server-only"+ * stub, and imports written without an extension. Used with --import tests/helpers/ts-register.mjs.+ */+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";++const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");+const tryFile = (p) => [p, `${p}.ts`, `${p}.tsx`, path.join(p, "index.ts")].find((f) => fs.existsSync(f) && fs.statSync(f).isFile());++export async function resolve(specifier, context, next) {+ if (specifier === "server-only") return { url: pathToFileURL(path.join(root, "tests/stubs/server-only.ts")).href, shortCircuit: true };+ let base = null;+ if (specifier.startsWith("@/")) base = path.join(root, "src", specifier.slice(2));+ else if ((specifier.startsWith("./") || specifier.startsWith("../")) && context.parentURL?.startsWith("file:")) {+ const parent = fileURLToPath(context.parentURL);+ if (parent.endsWith(".ts") || parent.endsWith(".tsx")) base = path.resolve(path.dirname(parent), specifier);+ }+ const file = base && tryFile(base);+ if (file) return { url: pathToFileURL(file).href, shortCircuit: true };+ return next(specifier, context);+}++/** TypeScript to JavaScript (the typescript package, as the editor sees it), as ES modules. */+let ts;+export async function load(url, context, next) {+ if (!url.startsWith("file:") || !/\.tsx?$/.test(url)) return next(url, context);+ ts ??= (await import("typescript")).default;+ const source = fs.readFileSync(fileURLToPath(url), "utf8");+ const out = ts.transpileModule(source, {+ fileName: fileURLToPath(url),+ compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.ReactJSX, verbatimModuleSyntax: false, isolatedModules: true },+ });+ return { format: "module", source: out.outputText, shortCircuit: true };+}diff --git a/tests/helpers/ts-register.mjs b/tests/helpers/ts-register.mjsnew file mode 100644index 00000000..ef595e2c--- /dev/null+++ b/tests/helpers/ts-register.mjs@@ -0,0 +1,2 @@+import { register } from "node:module";+register("./ts-hooks.mjs", import.meta.url);diff --git a/tests/public-signup.test.ts b/tests/public-signup.test.tsindex 8e744fb9..0a9e8f4b 100644--- a/tests/public-signup.test.ts+++ b/tests/public-signup.test.ts@@ -1,9 +1,8 @@import crypto from "node:crypto";-import fs from "node:fs";-import path from "node:path";import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";import { NextRequest } from "next/server";import { tempDir } from "./helpers/temp-dir";+import { authDb, authSecret, dbBytes } from "./helpers/auth-db";// Route handlers call connection(); outside a request scope it would throw.vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));// Route handlers set the session cookie through cookies() (no request scope in a test): a jar that only records.@@ -41,9 +40,8 @@ describe("accounts", () => {expect(a.email).toBe("[email protected]");expect(a.hash).toMatch(/^[0-9a-f]{32}:[0-9a-f]{64}$/);expect(a.createdAt).toBeGreaterThan(0);- const file = fs.readFileSync(path.join(dir, "auth.json"), "utf8");- expect(file).not.toContain("long enough");- expect(JSON.parse(file).accounts[0].email).toBe("[email protected]");+ expect(dbBytes(dir)).not.toContain("long enough");+ expect(authDb().prepare("SELECT email FROM auth_accounts WHERE id = ?").get(a.id)).toEqual({ email: "[email protected]" });});it("logs in with the right password only", () => {@@ -433,7 +431,7 @@ describe("an account changes its password (Settings → Account)", () => {headers: { "content-type": "application/json", cookie: `${auth.SESSION_COOKIE}=${cookie}` },body: JSON.stringify(body),});- const secret = () => (JSON.parse(fs.readFileSync(path.join(dir, "auth.json"), "utf8")) as { secret: string }).secret;+ const secret = authSecret;/** An account cookie signed with the secret alone, as before account keys held the password's fingerprint. */const legacy = (id: string) => {const payload = `${Date.now() + 86_400_000}.${id}`;diff --git a/tests/security-lows.test.ts b/tests/security-lows.test.tsindex ddc2bdd8..c193ea7f 100644--- a/tests/security-lows.test.ts+++ b/tests/security-lows.test.ts@@ -153,23 +153,21 @@ describe("L-16: pages carry a Content-Security-Policy, and no X-Powered-By", ()});});-describe("L-17: sign-in fails closed when the accounts file can't be read", () => {- it("keeps sign-in on and never overwrites a file it couldn't read", () => {- const file = path.join(dir, "auth.json");- const good = fs.readFileSync(file, "utf8");+describe("L-17: sign-in fails closed when the sign-in data can't be read", () => {+ it("keeps sign-in on, signs nobody in and writes nothing while the sign-in tables can't be used", () => {const owner = auth.createSession().value;+ const before = auth.listAccounts().length;+ globalThis.__fuobeAuthTablesError = "a test";try {- fs.writeFileSync(file, "{ not json");- fs.utimesSync(file, new Date(), new Date(Date.now() + 10_000));expect(auth.authEnabled()).toBe(true);expect(auth.validSession(owner)).toBe(false);- expect(() => auth.createAccount("[email protected]", "long enough")).toThrow();- expect(fs.readFileSync(file, "utf8")).toBe("{ not json");+ expect(() => auth.createAccount("[email protected]", "long enough")).toThrow(/can't be read/);} finally {- fs.writeFileSync(file, good);- fs.utimesSync(file, new Date(), new Date(Date.now() + 20_000));+ globalThis.__fuobeAuthTablesError = null;}expect(auth.validSession(owner)).toBe(true);+ expect(auth.listAccounts()).toHaveLength(before);+ // An auth.json that can't be read, waiting to move into the database: tests/auth-migration.test.ts.});});diff --git a/tests/sign-in-hardening.test.ts b/tests/sign-in-hardening.test.tsindex 0d87c35e..fb6ce4ec 100644--- a/tests/sign-in-hardening.test.ts+++ b/tests/sign-in-hardening.test.ts@@ -1,6 +1,4 @@import crypto from "node:crypto";-import fs from "node:fs";-import path from "node:path";import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";import { tempDir } from "./helpers/temp-dir";@@ -99,12 +97,11 @@ describe("M-2: password checks are counted and never hold up the server", () =>await expect(auth.verifyPassword("nope nope")).resolves.toBe(false);});- it("records a log-in at most once an hour, so log-ins don't rewrite the accounts file", async () => {- const file = path.join(dir, "auth.json");+ it("records a log-in at most once an hour, so log-ins don't write the sign-in data each time", async () => {expect((await login.POST(post("/api/auth/login", { email: "[email protected]", password: "member password" }))).status).toBe(200);- const before = fs.readFileSync(file, "utf8");+ const before = auth.authVersion();for (let i = 0; i < 3; i++) expect((await login.POST(post("/api/auth/login", { email: "[email protected]", password: "member password" }))).status).toBe(200);- expect(fs.readFileSync(file, "utf8")).toBe(before);+ expect(auth.authVersion()).toBe(before);});it("an account deleting itself gets 5 password checks a minute", async () => {diff --git a/tests/sign-out-everyone.test.ts b/tests/sign-out-everyone.test.tsindex 79d325b6..c821ad36 100644--- a/tests/sign-out-everyone.test.ts+++ b/tests/sign-out-everyone.test.ts@@ -1,9 +1,8 @@import crypto from "node:crypto";-import fs from "node:fs";-import path from "node:path";import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";import { NextRequest } from "next/server";import { tempDir } from "./helpers/temp-dir";+import { authSecret } from "./helpers/auth-db";vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));const dir = tempDir("fuobe-signout-");@@ -18,11 +17,11 @@ afterAll(() => {});const DAY = 86_400_000;-const secret = () => (JSON.parse(fs.readFileSync(path.join(dir, "auth.json"), "utf8")) as { secret: string }).secret;+const secret = authSecret;const hmac = (key: string, payload: string) => crypto.createHmac("sha256", key).update(payload).digest("base64url");const passwordTag = () => crypto.createHash("sha256").update(process.env.FUOBE_PASSWORD ?? "").digest("hex");/**- * A cookie signed as the server signs it, as someone who read auth.json and also knew the password could make one: an+ * A cookie signed as the server signs it, as someone who read the database and also knew the password could make one: an* owner's ("<expiry>") with the secret and the password, an account's ("<expiry>.<id>") with the secret alone.*/const forge = (payload: string) => `${payload}.${hmac(payload.includes(".") ? secret() : `${secret()}.${passwordTag()}`, payload)}`;@@ -77,7 +76,7 @@ describe("H-1: owner sign-ins are tied to the password", () => {}});- it("the secret alone (someone who read auth.json, not the password) can't make an owner cookie", () => {+ it("the secret alone (someone who read the database, not the password) can't make an owner cookie", () => {const exp = String(Date.now() + DAY);expect(auth.validSession(`${exp}.${hmac(secret(), exp)}`)).toBe(false);expect(auth.validSession(forge(exp))).toBe(true);