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: a safe way back to an older version, and a note every older build keeps locked
Adarsh8aca2b6fab7f
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 53eb2b63..5176e837 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 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`).+- **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 note in its place that every older build reads as "sign-in on, nobody can sign in" (JSON with `unreadable: true` and a password hash no scrypt result matches). Going back to an older build goes through `scripts/auth-export.mjs`, which writes `auth.json` from the tables and marks the store `exported`; the next start moves that file back in, with the older build's changes, and bridges again. Any other `auth.json` found after the move (a backup copied back) is never read on its own: the proxy answers 503 until it is removed, or until a start with `FUOBE_AUTH_REIMPORT=1` moves it in. 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/SELF-HOSTING.md b/docs/SELF-HOSTING.mdindex a68cf55b..42284eae 100644--- a/docs/SELF-HOSTING.md+++ b/docs/SELF-HOSTING.md@@ -82,10 +82,22 @@ The password, the sign-in secret, API tokens and accounts are kept in the databa- 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.+- Then it is renamed to `auth.json.migrated-<date and time>`, which is kept as a backup, and a note takes its place. Every older version reads the note as "sign-in is on and nobody can sign in", so it never opens 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. Its log says why and which entry, by its place in the list (for example "account 7"), never by email.-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.+The backup `auth.json.migrated-<…>` holds the password hash, the sign-in secret, API tokens and every account (with its email, password hash, GPU link and sealed keys) as they were at the upgrade, including accounts deleted since. Keep it as private as `fuobe.db`, and delete it once you won't go back to an older version.++**Backups.** `fuobe.db` (with its `-wal` and `-shm` files) can be read only by the server's own user, so a backup job must run as that user. Copy `fuobe.db` together with `secrets.key`: stop the server first, or make a consistent copy while it runs with `(umask 077; sqlite3 data/fuobe.db ".backup backup.db")`, which also takes the `-wal` file's changes. Keep the copy and `secrets.key` as private as the originals: they hold the sign-in secret, password hashes and GPU links, and `secrets.key` opens the saved keys.++**Going back to an older version.**++1. Stop the server.+2. Run `node scripts/auth-export.mjs` from this version's folder (with `FUOBE_DATA_DIR` set if your data folder isn't `./data`). It writes `auth.json` from the database, with everything made since the upgrade, readable by the server's user only. It never writes over an `auth.json` that isn't the note.+3. Start the older version.++When you start this version again, it moves that `auth.json` back in, with what the older version changed (new accounts, a new password), and keeps it in step for 10 minutes again. This needs no step either.++Don't copy `auth.json.migrated-<…>` back instead. It lacks the accounts made since the upgrade, and the older version removes the files of accounts it doesn't know. If an `auth.json` that the export didn't write is found after the move, this version doesn't read it on its own: it answers every request with 503 and says so in its log. Remove the file to keep the database's sign-in data, or start once with `FUOBE_AUTH_REIMPORT=1` to replace the database's sign-in data with what the file holds.## Environment variables@@ -96,6 +108,7 @@ To back up, copy `fuobe.db` (stop the server first, or use `sqlite3 data/fuobe.d| `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 (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_AUTH_REIMPORT=1` | For one start only: an `auth.json` found after sign-in data moved into the database replaces the database's sign-in data ([Sign-in data](#sign-in-data)). Remove it after that start || `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 be02806d..086788dc 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -322,7 +322,9 @@ account with that provider. The studio's own keys are never used for an account'keys included. Removing or replacing a key that runs are going on answers 409 `runs-going` first;with `{ stopRuns: true }` those runs are stopped with the old key before it changes. A run stillbeing handed to the provider is stopped there when its submit lands: the key (or the deleted- account's record) waits for that, up to a minute.+ account's record) waits for that, up to a minute. On an install upgraded from `auth.json`, the+ backup `auth.json.migrated-<time>` still holds the accounts as they were at the upgrade, sealed+ keys included: delete it once the upgrade is confirmed ([Sign-in data](SELF-HOSTING.md#sign-in-data)).- **What it changes in the studios.** `GET /api/status` lists the account's keys(`viewer.keys`) and its engine mode: `both` while it has a key and the studio isn't open-sourceonly, else `open`. The model pickers dim the paid models it has no key for ("Add your Replicatediff --git a/scripts/auth-export.mjs b/scripts/auth-export.mjsnew file mode 100644index 00000000..5138878c--- /dev/null+++ b/scripts/auth-export.mjs@@ -0,0 +1,119 @@+#!/usr/bin/env node+// Writes data/auth.json again from the sign-in data in the database, for going back to a Fuobe version from before+// sign-in data moved into fuobe.db (docs/SELF-HOSTING.md, "Sign-in data").+//+// node scripts/auth-export.mjs # the data folder is FUOBE_DATA_DIR, or ./data+//+// Stop the server first. The file is written in the format the older version reads (the same as src/server/auth-store.ts+// exportJson), readable by this user only, and only when there is no auth.json or only the note left in its place.+// The store is marked "exported": the next start of this version moves the file back in, with what the older version+// changed in it, as long as nothing changed in the database since. Prints counts only, never an email or a secret.+import crypto from "node:crypto";+import fs from "node:fs";+import path from "node:path";+import Database from "better-sqlite3";++const dir = path.resolve(process.env.FUOBE_DATA_DIR ?? path.join(process.cwd(), "data"));+const dbFile = path.join(dir, "fuobe.db");+const authFile = path.join(dir, "auth.json");++function fail(message) {+ console.error(`auth-export: ${message}`);+ process.exit(1);+}++if (!fs.existsSync(dbFile)) fail(`no database at ${dbFile}: set FUOBE_DATA_DIR to the data folder`);++/** What is in auth.json now: nothing, the note this version leaves there, or something else (never written over). */+function current() {+ let raw;+ try {+ raw = fs.readFileSync(authFile, "utf8");+ } catch (e) {+ if (e.code === "ENOENT") return "none";+ fail(`${authFile} can't be read (${e.code ?? "error"}): move it away first`);+ }+ if (raw.startsWith("This is not Fuobe's sign-in file any more.")) return "note";+ try {+ const d = JSON.parse(raw);+ const some = (v) => Array.isArray(v) && v.length > 0;+ if (d && typeof d === "object" && d.fuobeSignInMovedTo !== undefined && !some(d.accounts) && !some(d.tokens) && !d.publicSignup) return "note";+ } catch {}+ return "other";+}++const db = new Database(dbFile);+db.pragma("busy_timeout = 5000");+const has = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'auth_migration'").get();+const marker = has ? db.prepare("SELECT * FROM auth_migration WHERE id = 1").get() : undefined;+if (!marker) fail("this data folder has no sign-in data in the database: nothing to export");+if (marker.state === "bridge") fail("auth.json is still kept up to date by the server (the first minutes after the upgrade): use it as it is");+const state = current();+if (state === "other") fail(`${authFile} is already there and is not the note: move it away first (it is never written over)`);++const extra = (json) => (json ? JSON.parse(json) : {});++const out = db+ .transaction(() => {+ const inst = db.prepare("SELECT secret, password_hash, public_signup, extra_json, version FROM auth_install WHERE id = 1").get();+ const gpus = new Map(db.prepare("SELECT * FROM auth_account_gpu").all().map((g) => [g.account_id, g]));+ const keys = new Map();+ for (const k of db.prepare("SELECT * FROM auth_account_keys ORDER BY rowid").all()) keys.set(k.account_id, [...(keys.get(k.account_id) ?? []), k]);+ const gpuFrom = (g) =>+ g.mode === "computer" ? { mode: "computer" } : { ...(g.mode === "link" && { mode: "link" }), url: g.url ?? "", ...(g.token !== null && { token: g.token }) };+ const keyFrom = (k) => ({ sealed: k.sealed, last4: k.last4, addedAt: k.added_at, ...(k.rejected_at !== null && { rejectedAt: k.rejected_at }) });+ const accounts = db+ .prepare("SELECT * FROM auth_accounts ORDER BY rowid")+ .all()+ .map((r) => {+ const a = { ...extra(r.extra_json), id: r.id, email: r.email, hash: r.password_hash, createdAt: r.created_at };+ 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;+ const g = gpus.get(r.id);+ if (g) a.gpu = gpuFrom(g);+ const ks = keys.get(r.id);+ if (ks?.length) a.keys = Object.fromEntries(ks.map((k) => [k.provider, keyFrom(k)]));+ return a;+ });+ const tokens = db+ .prepare("SELECT * FROM auth_tokens ORDER BY rowid")+ .all()+ .map((t) => ({+ ...extra(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 signedOut = db.prepare("SELECT hash, exp FROM auth_signed_out ORDER BY rowid").all();+ const data = {+ ...extra(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 }),+ };+ const text = JSON.stringify(data, null, 2);+ const tmp = `${authFile}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;+ fs.writeFileSync(tmp, text, { mode: 0o600 });+ // The file goes in place only if the database's change below commits.+ db.prepare("UPDATE auth_migration SET state = 'exported', exported_version = ? WHERE id = 1").run(inst?.version ?? 0);+ return { tmp, accounts: accounts.length, tokens: tokens.length };+ })+ .immediate();+if (current() === "other") {+ fs.rmSync(out.tmp, { force: true });+ db.prepare("UPDATE auth_migration SET state = 'done', exported_version = NULL WHERE id = 1 AND state = 'exported'").run();+ fail(`${authFile} appeared while exporting: nothing written. Is the server still running?`);+}+fs.renameSync(out.tmp, authFile);+db.close();+console.log(+ `auth-export: wrote ${authFile} with ${out.accounts} accounts and ${out.tokens} API tokens. Start the older version now. When this version starts again, it moves the file back in.`,+);diff --git a/src/server/auth-store.ts b/src/server/auth-store.tsindex af7525ee..a4756766 100644--- a/src/server/auth-store.ts+++ b/src/server/auth-store.ts@@ -17,9 +17,14 @@* 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.+ * quiet for 3 minutes after that, it is put aside as auth.json.migrated-<UTC time> (kept, never deleted) and a note+ * takes its place (TOMBSTONE): JSON that every older build reads as "sign-in on, nobody can sign in", so an older build+ * pointed at this folder later never opens the studio. A new install gets the note with its first sign-in change.+ *+ * Going back to an older build: scripts/auth-export.mjs writes auth.json from the database again and marks the store+ * "exported". The next start of this build moves that file back in (with what the older build changed in it) and+ * bridges again. Any other auth.json found beside a store that was already moved (a backup copied back) is never read+ * on its own: sign-in fails closed (503) until it is removed, or FUOBE_AUTH_REIMPORT=1 says to move it in.*/import "server-only";import type Database from "better-sqlite3";@@ -52,7 +57,7 @@ export type AuthStoreMode = "fresh" | "bridge" | "done" | "unreadable" | "failedinterface Marker {source: "auth.json" | "new";- state: "bridge" | "done";+ state: "bridge" | "done" | "exported";started_at: number;synced_at: number | null;json_stat: string | null;@@ -60,6 +65,8 @@ interface Marker {counts_json: string | null;backup_file: string | null;retired_at: number | null;+ /** exported: auth_install.version when scripts/auth-export.mjs wrote auth.json. */+ exported_version: number | null;}interface Counts {@@ -92,9 +99,15 @@ declare global {const now = () => globalThis.__fuobeAuthClock?.() ?? Date.now();+/** How often a server whose store was moved looks at auth.json again (for a file put back, or an unfinished rename). */+const FILE_CHECK_MS = 60_000;+const s = {+ /** The store was moved (done or exported) and auth.json was looked at, at fileCheckedAt. */done: false,- finished: false,+ fileCheckedAt: 0,+ /** What that look found that keeps sign-in closed (an auth.json put back, or one that can't go in). */+ held: null as { mode: "unreadable" | "failed"; message: string } | null,/** 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. */@@ -102,7 +115,7 @@ const s = {/** 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 },+ warned: { unreadable: 0, failed: 0 },writes: 0,};@@ -173,28 +186,60 @@ function readFile(): FileRead {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" };+ return { error: raw.toString("utf8").startsWith(TEXT_TOMBSTONE_HEAD) ? "tombstone" : "not valid JSON" };}if (!data || typeof data !== "object" || Array.isArray(data)) return { error: "not an object" };+ if (isTombstone(data)) return { error: "tombstone" };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.-`;+/**+ * The note left in place of auth.json once it was moved: JSON that every older build reads as "sign-in on, nobody can+ * sign in". Builds from 2026-10-31 on read `unreadable: true` as a file they can't read: they fail closed and never+ * write over it. Older ones see a password whose hash (1 byte) no scrypt result (32 bytes) can match, no secret (no+ * cookie is valid) and no tokens. Each of them, and the account sweep, finds no accounts, and a missing secret makes+ * the sweep stop instead of removing anyone's files.+ */+const TOMBSTONE_KEY = "fuobeSignInMovedTo";+const TOMBSTONE = `${JSON.stringify(+ {+ [TOMBSTONE_KEY]: "fuobe.db",+ note: 'Sign-in data (the password, accounts and API tokens) is in the database, fuobe.db, in this folder. This file signs nobody in. To go back to an older Fuobe build, see "Sign-in data" in docs/SELF-HOSTING.md.',+ password: "00:00",+ secret: "",+ tokens: [],+ unreadable: true,+ },+ null,+ 2,+)}\n`;+/** The first form of the note (plain text), from test builds of this change. */+const TEXT_TOMBSTONE_HEAD = "This is not Fuobe's sign-in file any more.";++/**+ * The note, also after an older build that let its owner in (FUOBE_PASSWORD) wrote it again: it holds no accounts, no+ * tokens and no public sign-up. One that does is sign-in data an older build added, which is never ignored.+ */+function isTombstone(data: AuthJson): boolean {+ const some = (v: unknown) => Array.isArray(v) && v.length > 0;+ return data[TOMBSTONE_KEY] !== undefined && !some(data.accounts) && !some(data.tokens) && !data.publicSignup;+}-/** 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 {+/**+ * Write a file the way auth.json was always written: a temporary file (a name no other server or container uses),+ * then a rename, readable by this user only. Gives the file's stat key as written: the rename keeps it, and a stat+ * after the rename could already see another server's file.+ */+function writeAtomic(file: string, text: string): string {fs.mkdirSync(path.dirname(file), { recursive: true });- const tmp = `${file}.${process.pid}.tmp`;+ const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;fs.writeFileSync(tmp, text, { mode: 0o600 });+ const st = fs.statSync(tmp);fs.renameSync(tmp, file);+ return `${st.mtimeMs}:${st.size}:${st.ino}`;}function writeTombstone(): void {@@ -492,8 +537,8 @@ function importFile(file: { data: AuthJson; key: string | null; sha: string }):/** 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"));+ const key = writeAtomic(AUTH_FILE, text);+ sql("UPDATE auth_migration SET json_stat = ?, json_sha256 = ? WHERE id = 1").run(key, crypto.createHash("sha256").update(text).digest("hex"));}/**@@ -554,7 +599,7 @@ function bridgeTick(m: Marker): AuthStoreMode {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";+ return s.done ? (s.held?.mode ?? "done") : "bridge";}/** "auth.json.migrated-20261104T101500Z", or with -2, -3… when that is taken. */@@ -584,35 +629,128 @@ function retire(): void {return;}const m = marker();- if (m?.state === "done") {- s.done = true;- finishDone(m);- }+ if (m?.state === "done") afterMove(m);+}++const reimportAsked = () => process.env.FUOBE_AUTH_REIMPORT?.trim() === "1";++const PUT_BACK =+ "auth.json is back in the data folder, but sign-in data was already moved into the database (fuobe.db), so it is not read. Remove it to keep the database's sign-in data, or start once with FUOBE_AUTH_REIMPORT=1 to replace the database's sign-in data with it. See \"Sign-in data\" in docs/SELF-HOSTING.md.";++/** Keep sign-in closed for what afterMove found, until the next look. */+function hold(mode: "unreadable" | "failed", message: string): AuthStoreMode {+ s.held = { mode, message };+ return failClosed(mode, message);}/**- * 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.+ * The store was moved (done), or written out for an older build (exported): look at auth.json, at most once a minute.+ * - The note, or no file: as it should be (the note is written again when it is missing).+ * - The file as the bridge last left it: put aside under its backup name (a crash between the database's change and+ * that, or a copy put back that holds nothing new), and the note put in its place.+ * - exported: the file scripts/auth-export.mjs wrote, maybe changed by the older build since: moved back in.+ * - Any other JSON auth.json (a backup copied back, a file from elsewhere) is never read on its own: an older build may+ * have run on it, and ignoring it would lose its accounts (and the sweep would remove their files), while reading it+ * could bring back a revoked token or an old password. Sign-in fails closed until it is removed, or until a start+ * with FUOBE_AUTH_REIMPORT=1 moves it in.*/-function finishDone(m: Marker): void {- s.finished = true;+function afterMove(m: Marker): AuthStoreMode {+ s.done = true;+ s.fileCheckedAt = now();+ s.held = null;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);+ const file = key === null ? null : readFile();+ const note = file === null || ("error" in file && file.error === "tombstone");+ if (m.state === "exported") {+ if (note) {+ immediate(() => {+ if (marker()?.state === "exported") sql("UPDATE auth_migration SET state = 'done', exported_version = NULL WHERE id = 1").run();+ });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 "done";}- return;+ if ("error" in file!) return hold("unreadable", `${AUTH_FILE} can't be read (${file.error}).`);+ return reimport(file!, "exported");+ }+ if (note) {+ if (file === null) writeTombstone();+ return "done";+ }+ // A broken file (an older build fails closed on it too): not read, and not written over.+ if ("error" in file!) return "done";+ if (m.source === "auth.json" && file.sha === m.json_sha256) {+ putAside(m);+ return "done";+ }+ if (reimportAsked()) return reimport(file, "asked");+ return hold("failed", PUT_BACK);+}++/** auth.json as the bridge last left it: kept under the backup name (never written over), and the note in its place. */+function putAside(m: Marker): void {+ try {+ if (m.backup_file) {+ const backup = path.join(DATA_DIR, m.backup_file);+ let made = true;+ try {+ // A link can't replace a file already there, so a second server finishing at the same moment can't put the+ // note over the backup.+ fs.linkSync(AUTH_FILE, backup);+ } catch (e) {+ const code = (e as NodeJS.ErrnoException).code;+ if (code === "EEXIST") made = false;+ else fs.copyFileSync(AUTH_FILE, backup, fs.constants.COPYFILE_EXCL); // a file system without links+ }+ if (made) {+ if (process.platform !== "win32") fs.chmodSync(backup, 0o600);+ console.info(+ `[fuobe] auth.json was kept as ${m.backup_file}: sign-in data is in the database now. That file still holds the accounts, password hashes and sealed keys as they were at the move, including accounts deleted since: delete it once you won't go back to an older version.`,+ );+ }+ }+ writeTombstone();+ } catch (e) {+ console.warn(`[fuobe] Couldn't put auth.json aside: ${(e as NodeJS.ErrnoException).code ?? (e as Error).message}`);}- 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.`);+}++/**+ * Move auth.json in again over the store's rows, in one transaction, checked as the first move is. From an export, only+ * when nothing changed in the database since (else the database's changes would be lost): sign-in fails closed instead.+ * Then the bridge starts again (an older build may still run on the file), and puts the file aside under a new name.+ */+function reimport(file: { data: AuthJson; key: string | null; sha: string }, why: "exported" | "asked"): AuthStoreMode {+ let counts: Counts | null = null;+ try {+ immediate(() => {+ const m = marker();+ if (m?.state !== "done" && m?.state !== "exported") return; // another server did it+ const version = (sql("SELECT version FROM auth_install WHERE id = 1").get() as { version: number } | undefined)?.version ?? 0;+ if (why === "exported" && m.exported_version !== version && !reimportAsked()) {+ throw new DataError("sign-in data changed in the database after auth.json was exported");+ }+ const at = now();+ clearAll();+ counts = insertAll(file.data, at, version + 1);+ verify(file.data, counts, at);+ sql(+ "UPDATE auth_migration SET source = 'auth.json', state = 'bridge', started_at = ?, synced_at = ?, json_stat = ?, json_sha256 = ?, counts_json = ?, backup_file = NULL, retired_at = NULL, exported_version = NULL WHERE id = 1",+ ).run(at, at, file.key, file.sha, JSON.stringify(counts));+ });+ } catch (e) {+ const how = e instanceof DataError ? e.message : `the database said: ${(e as Error).message}`;+ return hold("failed", `auth.json couldn't be moved back into the database (${how}); nothing was changed. ${PUT_BACK}`);+ }+ if (counts) {+ const c = counts as Counts;+ console.info(+ `[fuobe] Sign-in data moved back in from auth.json (${why === "exported" ? "written for an older version" : "FUOBE_AUTH_REIMPORT=1"}): ${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>.`,+ );+ }+ s.done = false;+ s.retireCheckedAt = 0;+ const m = marker();+ return m?.state === "bridge" ? bridgeTick(m) : m ? afterMove(m) : "fresh";}// ---------------------------------------------------------------------------@@ -626,28 +764,19 @@ function failClosed(kind: "unreadable" | "failed", message: string): AuthStoreMo/** 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.done && now() - s.fileCheckedAt < FILE_CHECK_MS) return s.held ? failClosed(s.held.mode, s.held.message) : "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 === "done" || m?.state === "exported") return afterMove(m);+ s.done = false;+ s.held = null;if (m?.state === "bridge") return bridgeTick(m);return beforeMove();} catch (e) {+ s.done = false;s.dbFailedAt = Date.now();return failClosed("failed", `The sign-in data in the database can't be read (${(e as Error).message}).`);}@@ -666,7 +795,7 @@ function beforeMove(): AuthStoreMode {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);+ if (set) return set.state === "bridge" ? bridgeTick(set) : afterMove(set);s.bad = { key, mode: "unreadable", at: Date.now(), data: false };return failClosed("unreadable",@@ -684,11 +813,8 @@ function beforeMove(): AuthStoreMode {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";+ if (!m) return "fresh";+ return m.state === "bridge" ? bridgeTick(m) : afterMove(m);}/** Sign-in can't be used (the database, or auth.json waiting to move in, can't be read): fail closed. */@@ -700,34 +826,54 @@ 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.";+/** An older server changed auth.json while a change here was being made: the change is made again on top of it. */+class FileMoved extends Error {}+/*** 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.+ * the bridge auth.json is caught up with first and written after, in the same transaction. When an older server+ * changes the file in between, the transaction is undone and run again on top of that change (up to 3 times).*/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);+ let out!: T;+ for (let attempt = 1; ; attempt++) {+ try {+ 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);+ } else if (m.state === "exported") {+ throw new Error("The sign-in data changed while saving: try again.");+ }+ 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);+ const after = marker();+ if (after?.state === "bridge") {+ if (attempt < 3 && statKey() !== after.json_stat) throw new FileMoved();+ exportFile();+ }+ return r;+ });+ break;+ } catch (e) {+ if (e instanceof FileMoved) continue;+ throw e;}- 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;+ s.fileCheckedAt = now();+ s.held = null;writeTombstone();}s.writes++;diff --git a/src/server/db.ts b/src/server/db.tsindex 503e3c4f..26a7c25b 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -12,7 +12,8 @@ export const DATA_DIR = path.resolve(/*turbopackIgnore: true*/ process.env.FUOBE* - 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").+ * the imported file is still kept in step for a build that may still read it ("bridge"), was put aside ("done"), or+ * was written out again for an older build by scripts/auth-export.mjs ("exported", with the version it wrote).* - 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.@@ -36,7 +37,8 @@ export const AUTH_TABLES = `CREATE TABLE IF NOT EXISTS auth_install (json_sha256 TEXT,counts_json TEXT,backup_file TEXT,- retired_at INTEGER+ retired_at INTEGER,+ exported_version INTEGER);CREATE TABLE IF NOT EXISTS auth_tokens (id TEXT PRIMARY KEY,@@ -694,8 +696,8 @@ export const MIGRATIONS: string[] = [AUTH_TABLES,];-/** The place of the sign-in tables' migration in MIGRATIONS. */-const AUTH_MIGRATION = 27;+/** The place of the sign-in tables' migration in MIGRATIONS (27). */+const AUTH_MIGRATION = MIGRATIONS.indexOf(AUTH_TABLES);/*** "Use the ComfyUI on this computer" (src/server/computer/tasks.ts). relay_runners: each principal's computer (the one@@ -901,7 +903,7 @@ export const SKILL_TABLES = `CREATE TABLE IF NOT EXISTS skill_runs (/** 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_migration: ["id", "source", "state", "started_at", "synced_at", "json_stat", "json_sha256", "counts_json", "backup_file", "retired_at", "exported_version"],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"],@@ -1004,8 +1006,8 @@ function open(): Database.Database {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.+ // Most of a deleted row's bytes (a deleted account's email and password hash) are overwritten where that costs no+ // extra writes. Traces can stay on free pages, and in the -wal file until its next checkpoint.db.pragma("secure_delete = FAST");db.exec(`CREATE TABLE IF NOT EXISTS _migrations (id INTEGER PRIMARY KEY)`);forgetDroppedBranchMigrations(db);diff --git a/tests/auth-migration.test.ts b/tests/auth-migration.test.tsindex a7c5cc8e..78bf8312 100644--- a/tests/auth-migration.test.ts+++ b/tests/auth-migration.test.ts@@ -4,7 +4,7 @@* 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 { spawn, spawnSync } from "node:child_process";import crypto from "node:crypto";import fs from "node:fs";import path from "node:path";@@ -67,6 +67,45 @@ function legacyRead(dir: string): Record<string, unknown> & { unreadable?: true}}+/**+ * What a build from before 2026-10-31 (no fail-closed read yet) makes of auth.json: a file it can't parse means no+ * password (an open studio). The note must keep it locked: a password nobody can match, no secret, no tokens, no accounts.+ */+function veryOldLocked(dir: string): boolean {+ let d: { password?: string; secret?: string; tokens?: unknown[]; accounts?: unknown[] };+ try {+ d = JSON.parse(fs.readFileSync(authFile(dir), "utf8"));+ } catch {+ d = { secret: "", tokens: [] };+ }+ const verify = (pw: string) => {+ if (!d.password) return false;+ const [salt, hash] = d.password.split(":");+ if (!salt || !hash) return false;+ const a = crypto.scryptSync(pw, Buffer.from(salt, "hex"), 32);+ const b = Buffer.from(hash, "hex");+ return a.length === b.length && crypto.timingSafeEqual(a, b);+ };+ return !!d.password && !verify("") && !verify("owner password") && !d.secret && !d.tokens?.length && !d.accounts?.length;+}++/** The note in place of auth.json: JSON, so every older build reads it, and locked for each of them. */+function isNote(dir: string): boolean {+ const d = JSON.parse(fs.readFileSync(authFile(dir), "utf8"));+ return d.fuobeSignInMovedTo === "fuobe.db" && legacyRead(dir).unreadable === true && veryOldLocked(dir);+}++/** scripts/auth-export.mjs on a data folder (the server stopped first). */+function exportScript(dir: string, env: Record<string, string> = {}) {+ globalThis.__fuobeDb?.close();+ globalThis.__fuobeDb = undefined;+ const r = spawnSync(process.execPath, [path.join(process.cwd(), "scripts", "auth-export.mjs")], {+ env: { ...process.env, FUOBE_DATA_DIR: dir, ...env },+ encoding: "utf8",+ });+ return { code: r.status, out: `${r.stdout}${r.stderr}` };+}+/** 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`;@@ -165,8 +204,7 @@ describe("a new install", () => {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");+ expect(isNote(dir)).toBe(true);// An older build pointed at this folder fails closed instead of opening the studio.expect(legacyRead(dir).unreadable).toBe(true);srv = await server(dir);@@ -175,7 +213,7 @@ describe("a new install", () => {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 () => {+ it("moves in an auth.json put there before the first change; one put back after is never read on its own", async () => {const dir = tempDir("fuobe-auth-drop-");let srv = await server(dir);expect(srv.auth.authEnabled()).toBe(false);@@ -183,13 +221,25 @@ describe("a new install", () => {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.+ // Put aside, then an auth.json without a password put back: not read, and nobody gets in (503) until it goes.globalThis.__fuobeAuthClock = () => Date.now() + 11 * MIN;expect(srv.store.authStoreMode()).toBe("done");legacyWrite(dir, { secret: "", tokens: [] });+ const errors = vi.spyOn(console, "error").mockImplementation(() => {});srv = await server(dir);+ expect(srv.store.authStoreMode()).toBe("failed");+ expect(srv.store.authStoreFailed()).toBe(true);expect(srv.auth.authEnabled()).toBe(true);+ expect(srv.auth.checkPassword("dropped password")).toBe(false);+ expect(() => srv.auth.readAccountIds()).toThrow();+ expect(errors.mock.calls.flat().join("\n")).toMatch(/FUOBE_AUTH_REIMPORT=1/);+ errors.mockRestore();+ // Removed: the database's sign-in data again, and the note in its place.+ fs.rmSync(authFile(dir));+ srv = await server(dir);+ expect(srv.store.authStoreMode()).toBe("done");expect(srv.auth.checkPassword("dropped password")).toBe(true);+ expect(isNote(dir)).toBe(true);});});@@ -384,8 +434,7 @@ describe("the bridge: auth.json kept in step for a server of an older build", ()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);+ expect(isNote(dir)).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);@@ -403,7 +452,7 @@ describe("the bridge: auth.json kept in step for a server of an older build", ()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);+ expect(isNote(dir)).toBe(true);// The note gone too: written again.fs.rmSync(authFile(dir));const third = await server(dir);@@ -412,6 +461,141 @@ describe("the bridge: auth.json kept in step for a server of an older build", ()});});+describe("going back to an older build, and forward again", () => {+ /** An older install moved in and put aside, then an account made on this build. */+ async function moved(prefix: string) {+ const o = await olderInstall(prefix);+ expect(o.srv.store.authStoreMode()).toBe("bridge");+ globalThis.__fuobeAuthClock = () => Date.now() + 11 * MIN;+ expect(o.srv.store.authStoreMode()).toBe("done");+ globalThis.__fuobeAuthClock = undefined;+ const after = o.srv.auth.createAccount("[email protected]", "long enough");+ return { ...o, after };+ }++ it("scripts/auth-export.mjs writes auth.json for the older build; this build moves its changes back in", async () => {+ const { dir, fx, after } = await moved("fuobe-auth-export-");+ const backups = () => fs.readdirSync(dir).filter((f) => f.startsWith("auth.json.migrated-"));+ expect(backups()).toHaveLength(1);+ const r = exportScript(dir);+ expect(r.code, r.out).toBe(0);+ expect(r.out).not.toContain("@example.com");+ if (process.platform !== "win32") expect(fs.statSync(authFile(dir)).mode & 0o777).toBe(0o600);+ // The older build reads every account, the one made after the move too, and the password.+ const older = legacyRead(dir) as typeof fx.data & { accounts: Record<string, unknown>[] };+ expect(legacyRead(dir).unreadable).toBeUndefined();+ expect(older.accounts.map((a) => a.email)).toContain("[email protected]");+ expect(older.password).toBe(fx.data.password);+ // A second export would write over what the older build changed: refused.+ expect(exportScript(dir).code).not.toBe(0);+ // The older build signs someone up and changes the owner's password.+ older.accounts.push({ id: "acctrollback00001", email: "[email protected]", hash: hashPw("rollback password"), createdAt: Date.now() });+ older.password = hashPw("owner password two");+ legacyWrite(dir, older);+ // Forward again: moved back in, with the older build's changes, and bridged again.+ const srv = await server(dir);+ expect(srv.store.authStoreMode()).toBe("bridge");+ expect(srv.auth.checkAccount("[email protected]", "rollback password")?.id).toBe("acctrollback00001");+ expect(srv.auth.checkAccount("[email protected]", "long enough")?.id).toBe(after.id);+ expect(srv.auth.checkPassword("owner password two")).toBe(true);+ expect(srv.auth.checkPassword("owner password")).toBe(false);+ expect(srv.auth.readAccountIds().has("acctrollback00001")).toBe(true);+ expect(srv.marker()).toMatchObject({ state: "bridge", exported_version: null });+ globalThis.__fuobeAuthClock = () => Date.now() + 11 * MIN;+ expect(srv.store.authStoreMode()).toBe("done");+ expect(backups()).toHaveLength(2);+ expect(isNote(dir)).toBe(true);+ });++ it("an export the older build never used: back to the database as it was", async () => {+ const { dir } = await moved("fuobe-auth-export-unused-");+ expect(exportScript(dir).code).toBe(0);+ fs.rmSync(authFile(dir));+ const srv = await server(dir);+ expect(srv.store.authStoreMode()).toBe("done");+ expect(srv.marker()).toMatchObject({ state: "done" });+ expect(srv.auth.listAccounts()).toHaveLength(5);+ expect(isNote(dir)).toBe(true);+ });++ it("an export after which the database changed: fails closed until FUOBE_AUTH_REIMPORT=1", async () => {+ const { dir } = await moved("fuobe-auth-export-stale-");+ expect(exportScript(dir).code).toBe(0);+ let srv = await server(dir);+ // A change in the database after the export (the auth store not started: it would move the file in first).+ (await import("@/server/db")).db().prepare("UPDATE auth_install SET version = version + 1").run();+ srv = await server(dir);+ const errors = vi.spyOn(console, "error").mockImplementation(() => {});+ expect(srv.store.authStoreMode()).toBe("failed");+ errors.mockRestore();+ process.env.FUOBE_AUTH_REIMPORT = "1";+ try {+ srv = await server(dir);+ expect(srv.store.authStoreMode()).toBe("bridge");+ expect(srv.auth.listAccounts()).toHaveLength(5);+ } finally {+ delete process.env.FUOBE_AUTH_REIMPORT;+ }+ });++ it("the export script refuses an auth.json that isn't the note, and a store still in its bridge", async () => {+ const { dir, srv } = await olderInstall("fuobe-auth-export-refuse-");+ expect(srv.store.authStoreMode()).toBe("bridge");+ expect(exportScript(dir).out).toMatch(/kept up to date/);+ const { dir: dir2 } = await moved("fuobe-auth-export-refuse2-");+ legacyWrite(dir2, { secret: "", tokens: [] });+ const r = exportScript(dir2);+ expect(r.code).not.toBe(0);+ expect(r.out).toMatch(/move it away first/);+ expect(legacyRead(dir2)).toEqual({ secret: "", tokens: [] });+ });++ it("a backup copied back over auth.json: unchanged it is put aside again; changed by an older build it fails closed, and nothing is swept", async () => {+ const { dir, after } = await moved("fuobe-auth-putback-");+ let srv = await server(dir);+ expect(srv.store.authStoreMode()).toBe("done");+ const backup = path.join(dir, srv.marker()!.backup_file as string);+ // Copied back and not changed: holds nothing new, so the note goes back in its place.+ fs.copyFileSync(backup, authFile(dir));+ srv = await server(dir);+ expect(srv.store.authStoreMode()).toBe("done");+ expect(isNote(dir)).toBe(true);+ expect(srv.auth.accountById(after.id)).toBeDefined();+ // Copied back, and an older build signed someone up there.+ const old = JSON.parse(fs.readFileSync(backup, "utf8"));+ old.accounts.push({ id: "acctputback000001", email: "[email protected]", hash: hashPw("putback password"), createdAt: Date.now() });+ legacyWrite(dir, old);+ const errors = vi.spyOn(console, "error").mockImplementation(() => {});+ srv = await server(dir);+ expect(srv.store.authStoreMode()).toBe("failed");+ expect(() => srv.auth.readAccountIds()).toThrow(); // the account sweep stops: nobody's files are removed+ expect(srv.auth.accountById(after.id)).toBeUndefined(); // closed, not gone+ errors.mockRestore();+ // A running server notices a file put back within a minute.+ fs.rmSync(authFile(dir));+ srv = await server(dir);+ expect(srv.store.authStoreMode()).toBe("done");+ legacyWrite(dir, old);+ expect(srv.store.authStoreMode()).toBe("done");+ globalThis.__fuobeAuthClock = () => Date.now() + 61_000;+ vi.spyOn(console, "error").mockImplementation(() => {});+ expect(srv.store.authStoreMode()).toBe("failed");+ vi.restoreAllMocks();+ globalThis.__fuobeAuthClock = undefined;+ // Moved in when asked: the file as it is.+ process.env.FUOBE_AUTH_REIMPORT = "1";+ try {+ srv = await server(dir);+ expect(srv.store.authStoreMode()).toBe("bridge");+ expect(srv.auth.checkAccount("[email protected]", "putback password")?.id).toBe("acctputback000001");+ // The backup was taken before that account existed: only what the file holds comes back.+ expect(srv.auth.accountById(after.id)).toBeUndefined();+ } finally {+ delete process.env.FUOBE_AUTH_REIMPORT;+ }+ });+});+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-");