Skip to content

armgit / fuobe

Public Imported from GitHub
0

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

Sign-in data: an auth.json found after the move is set aside, and the site keeps serving

Adarsha866fb84a1b2
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 5176e837..4e952bef 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 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`).
+- **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, a file from elsewhere) is never read as sign-in data and the site keeps serving from the tables: under the database's write lock it is linked to `auth.json.stray-<time>` (0600, through the file itself, never a symlink's target; a symlink is kept as a symlink), the note replaces `auth.json` by a rename only while `auth.json` is still that file (so it is never missing for an older build), and a row in `auth_stray_files` holds its counts and the ids of accounts only it lists. The owner sees the name and counts in Settings → Accounts and `signInNotices` of `GET /api/admin/accounts` while the file is there; the account sweep keeps the files of those accounts meanwhile. `FUOBE_AUTH_REIMPORT=1` moves such a file in instead (one whose data can't go in is set aside too). An `auth.json` that can't be read before the move keeps sign-in on with nobody signed in; one whose data can't go in, a database whose sign-in tables can't be used, or an export that comes back after the database changed make the proxy answer every request, `/login` too, with a calm "Back in a moment" page (503 with Retry-After, JSON for `/api/`), never the reason: the log has it. 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.md
index 42284eae..3cb00cba 100644
--- a/docs/SELF-HOSTING.md
+++ b/docs/SELF-HOSTING.md
@@ -83,7 +83,7 @@ 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 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.
+- 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 visitors get a short "Back in a moment" page (status 503) on every request, so a deploy never switches to that server. The server log says why and which entry, by its place in the list (for example "account 7"), never by email. The same page shows when the database's sign-in tables can't be read.
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.
@@ -97,7 +97,21 @@ The backup `auth.json.migrated-<…>` holds the password hash, the sign-in secre
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.
+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.
+
+**An `auth.json` found after the move.** The database stays the only source of sign-in data, and the site keeps working for everyone. When this version finds an `auth.json` that is not the note and not a file the export wrote (for example a backup copied back), it does not read it as sign-in data. Within a minute, it does these steps:
+
+- It renames the file to `auth.json.stray-<date and time>`, readable by the server's user only. Fuobe never deletes it.
+- It puts the note back in place of `auth.json`.
+- It writes a line to the server log.
+- It shows a notice to the owner in Settings → Accounts, and in `signInNotices` of `GET /api/admin/accounts`. The notice gives only the file's name and its counts: accounts, API tokens, and accounts that are not in the database.
+
+Nothing in that file signs anyone in or opens the studio. It does not change the password or the sign-in secret either. The accounts that only that file lists keep their files while the file stays in the data folder. When you don't need the file, delete it, and the notice goes away. To use the file instead of the database's sign-in data, do these steps:
+
+1. Copy it back to `auth.json`.
+2. Start the server once with `FUOBE_AUTH_REIMPORT=1`. The file then replaces the database's sign-in data, and it is moved in exactly like the first upgrade.
+
+If its data can't be moved in, nothing changes, and the file is set aside again.
## Environment variables
@@ -108,7 +122,7 @@ Don't copy `auth.json.migrated-<…>` back instead. It lacks the accounts made s
| `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_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, instead of being set aside unread ([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/admin-api.md b/docs/admin-api.md
index 29aa2dd3..6f074624 100644
--- a/docs/admin-api.md
+++ b/docs/admin-api.md
@@ -94,7 +94,7 @@ Times are epoch milliseconds and sizes are bytes. Every answer is `Cache-Control
| Call | Request | Answer |
|---|---|---|
-| `GET /api/admin/accounts` | `q` (the email contains it, up to 100 characters), `email` (exactly that address), `format=csv` | `{ total, items, totals }`; with `q` or `email`, also `matched`. `total` and `totals` always cover every account. CSV: a `text/csv` download |
+| `GET /api/admin/accounts` | `q` (the email contains it, up to 100 characters), `email` (exactly that address), `format=csv` | `{ total, items, totals, signInNotices }`; with `q` or `email`, also `matched`. `total` and `totals` always cover every account. `signInNotices` lists each `auth.json` that was found in the data folder after the sign-in data moved into the database. Each one was set aside without being read ([Sign-in data](SELF-HOSTING.md#sign-in-data)). An entry gives `{ file, foundAt, reason, counts }`. `reason` is `stray`, `unreadable` or `import-failed`. `counts` is `{ accounts, tokens, accountsNotInDatabase }`, or `null` when the file isn't sign-in data. An entry stays in the list until you delete its file. CSV: a `text/csv` download |
| `GET /api/admin/accounts/{id}` | | one account with its numbers; 404 `No such account` |
| `PATCH /api/admin/accounts/{id}` | exactly one of `{ disabled: boolean }` or `{ signOut: true }` | the account (no numbers) |
| `DELETE /api/admin/accounts/{id}` | | 204 |
diff --git a/docs/public-signup.md b/docs/public-signup.md
index 086788dc..1beecc0e 100644
--- a/docs/public-signup.md
+++ b/docs/public-signup.md
@@ -137,7 +137,11 @@ log-in (the CSV always has them). Running now counts as the run limit does: a ba
going is one run. A line above the list gives the runs of every account in the last 24 hours and 7
days, the runs going now, and the space all accounts' files take against their share of the disk.
The owner can switch an account off (it is signed out at once and can't log in) or delete it, and
-export the list as CSV.
+export the list as CSV. If an `auth.json` turns up in the data folder after the sign-in data moved
+into the database, the section also shows a notice. Visitors never see it. The file is not used: it
+is set aside under a new name, and sign-in goes on from the database. The notice gives the file's
+name and how many accounts and API tokens it lists
+([Sign-in data](SELF-HOSTING.md#sign-in-data)).
**Accounts' runs** (`/settings/runs`, from the list) shows what accounts made, newest first: one
account's or every account's, each labelled with its email, filtered by account, status (finished,
diff --git a/src/app/api/admin/accounts/route.ts b/src/app/api/admin/accounts/route.ts
index 065104e6..a3a6f20e 100644
--- a/src/app/api/admin/accounts/route.ts
+++ b/src/app/api/admin/accounts/route.ts
@@ -2,13 +2,15 @@ import { connection } from "next/server";
import { accountsWithStats } from "@/server/account-admin";
import { adminAccess, auditRead } from "@/server/admin-tokens";
import { accountsCsv, listAccounts, normalizeEmail } from "@/server/auth";
+import { signInNotices } from "@/server/auth-store";
const NO_STORE = { "Cache-Control": "no-store" };
/**
* Settings → Accounts (owner only, or an admin token with accounts:read): everyone who signed up, newest first, with
* their runs and space and the totals. `?q=` keeps the emails that contain it, `?email=` the one with that address;
- * `total` and `totals` still count every account. `?format=csv` downloads the list.
+ * `total` and `totals` still count every account. `?format=csv` downloads the list. `signInNotices`: each auth.json
+ * found in the data folder after sign-in data moved into the database and set aside unread (its name and counts only).
*/
export async function GET(request: Request) {
await connection();
@@ -33,8 +35,9 @@ export async function GET(request: Request) {
}
auditRead(access.actor, "accounts.list", filters);
const { items: listed, totals } = accountsWithStats(all);
- if (!filtered) return Response.json({ total: all.length, items: listed, totals }, { headers: NO_STORE });
+ const notices = signInNotices();
+ if (!filtered) return Response.json({ total: all.length, items: listed, totals, signInNotices: notices }, { headers: NO_STORE });
const keep = new Set(items.map((a) => a.id));
const matches = listed.filter((a) => keep.has(a.id));
- return Response.json({ total: all.length, matched: matches.length, items: matches, totals }, { headers: NO_STORE });
+ return Response.json({ total: all.length, matched: matches.length, items: matches, totals, signInNotices: notices }, { headers: NO_STORE });
}
diff --git a/src/components/accounts-admin.tsx b/src/components/accounts-admin.tsx
index d8fbadfa..76bf14eb 100644
--- a/src/components/accounts-admin.tsx
+++ b/src/components/accounts-admin.tsx
@@ -1,7 +1,7 @@
"use client";
import { useQuery, useQueryClient } from "@tanstack/react-query";
-import { Download, Images, Loader2, Trash2, UserX, UserCheck } from "lucide-react";
+import { Download, Images, Info, Loader2, Trash2, UserX, UserCheck } from "lucide-react";
import Link from "next/link";
import { useEffect } from "react";
import { toast } from "sonner";
@@ -51,11 +51,42 @@ export async function adminCall<T>(url: string, method = "GET", body?: unknown):
return j;
}
+/**
+ * An auth.json found in the data folder after sign-in data moved into the database, set aside unread (src/server/auth-store.ts):
+ * its name and counts only. `counts` is null when the file isn't sign-in data.
+ */
+export interface SignInNoticeRow {
+ file: string;
+ foundAt: number;
+ reason: "stray" | "unreadable" | "import-failed";
+ counts: { accounts: number; tokens: number; accountsNotInDatabase: number } | null;
+}
+
+/** The owner's note about one set-aside auth.json: what it is, that nothing in it is used, and what to do about it. */
+function SignInNotice({ notice: n }: { notice: SignInNoticeRow }) {
+ const c = n.counts;
+ const plural = (k: number, one: string, many: string) => `${k} ${k === 1 ? one : many}`;
+ return (
+ <p role="status" className="flex items-start gap-1.5 rounded-lg bg-warning/10 px-2.5 py-2 text-[12px] text-foreground">
+ <Info className="mt-0.5 size-3.5 shrink-0 text-warning" />
+ <span className="min-w-0">
+ {n.reason === "import-failed" ? "An auth.json that FUOBE_AUTH_REIMPORT=1 couldn't move in" : "An auth.json"} was found in the data folder ({timeAgo(n.foundAt)}) and
+ set aside as <code className="break-all">{n.file}</code>. Sign-in goes on from the database: nothing in that file is used.{" "}
+ {c
+ ? `It lists ${plural(c.accounts, "account", "accounts")} (${c.accountsNotInDatabase} not in the database) and ${plural(c.tokens, "API token", "API tokens")}. `
+ : "It isn't sign-in data Fuobe can read. "}
+ {c && c.accountsNotInDatabase > 0 ? "Their files are kept while the file is there. " : ""}
+ Delete the file to clear this note, or see “Sign-in data” in the self-hosting guide to use it instead.
+ </span>
+ </p>
+ );
+}
+
/** Everyone who signed up, with their numbers (the owner only). Settings and the runs page share it; it refreshes while runs are going. */
export function useAdminAccounts(enabled: boolean) {
return useQuery({
queryKey: ["admin-accounts"],
- queryFn: () => adminCall<{ total: number; items: AccountRow[]; totals: AccountTotals }>("/api/admin/accounts"),
+ queryFn: () => adminCall<{ total: number; items: AccountRow[]; totals: AccountTotals; signInNotices?: SignInNoticeRow[] }>("/api/admin/accounts"),
enabled,
refetchInterval: (q) => (q.state.data?.totals.running ? 15_000 : false),
});
@@ -177,6 +208,7 @@ export function AccountsAdmin() {
</div>
) : (
<div className="min-w-0 space-y-3">
+ {q.data.signInNotices?.map((n) => <SignInNotice key={n.file} notice={n} />)}
{total > 0 && (
<dl className="flex flex-wrap gap-x-4 gap-y-1 text-[12px]">
<Stat label="Runs in 24 hours">{q.data.totals.runsDay}</Stat>
diff --git a/src/proxy.ts b/src/proxy.ts
index 898196a8..d7793d41 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -86,7 +86,27 @@ function pass(request: NextRequest): NextResponse {
* chose (next-themes' "theme" key, read before the first paint).
*/
function plain404(title: string, text: string, back?: { href: string; label: string }, home = back ? "Home" : "Back to Home"): NextResponse {
- const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>${title} · Fuobe</title><link rel="icon" href="/icon.svg" type="image/svg+xml"><script>try{var t=localStorage.getItem("theme");if(t==="dark"||(t!=="light"&&matchMedia("(prefers-color-scheme: dark)").matches))document.documentElement.className="dark"}catch(e){}</script><style>
+ return new NextResponse(plainPage(title, text, `${back ? `<a class="back" href="${back.href}">${back.label}</a>` : ""}<a class="go" href="/">${home}</a>`, COMPASS), {
+ status: 404,
+ headers: { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" },
+ });
+}
+
+/**
+ * What every visitor gets while the server can't use its sign-in data (src/server/auth-store.ts authStoreFailed): a calm
+ * "back in a moment" in the same look, that tries again by itself; an API call gets the same in a sentence. Never why:
+ * the server log tells the owner. Still a 503 (with Retry-After), so a new release in this state is never switched to.
+ */
+function backSoon(request: NextRequest): NextResponse {
+ const headers = { "Cache-Control": "no-store", "Retry-After": "30" };
+ if (request.nextUrl.pathname.startsWith("/api/")) return NextResponse.json({ error: "Fuobe will be back in a moment. Please try again shortly." }, { status: 503, headers });
+ const html = plainPage("Back in a moment", "Fuobe is getting ready. This page tries again by itself.", '<a class="go" href="">Try again</a>', CLOCK, 30);
+ return new NextResponse(html, { status: 503, headers: { ...headers, "Content-Type": "text/html; charset=utf-8" } });
+}
+
+/** The page plain404 and backSoon show: the heading, a line, the buttons, and an icon; `refresh` reloads it after that many seconds. */
+function plainPage(title: string, text: string, nav: string, icon: string, refresh?: number): string {
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex">${refresh ? `<meta http-equiv="refresh" content="${refresh}">` : ""}<title>${title} · Fuobe</title><link rel="icon" href="/icon.svg" type="image/svg+xml"><script>try{var t=localStorage.getItem("theme");if(t==="dark"||(t!=="light"&&matchMedia("(prefers-color-scheme: dark)").matches))document.documentElement.className="dark"}catch(e){}</script><style>
:root{color-scheme:light;--bg:#fff;--fg:#1e1e1f;--muted:#6e6e71;--line:#e8e8e9;--brand:#5d4bdb;--faint:#efedfc}
.dark{color-scheme:dark;--bg:#121213;--fg:#fafafb;--muted:#a9a9ab;--line:rgba(255,255,255,.14);--brand:#6a5ee7;--faint:#25223d}
body{margin:0;min-height:100svh;display:flex;flex-direction:column;background:var(--bg);color:var(--fg);font:15px/1.5 Inter,ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif}
@@ -97,15 +117,16 @@ p{margin:8px 0 0;color:var(--muted);text-wrap:pretty}nav{margin-top:28px;display
nav a{display:inline-flex;align-items:center;height:36px;padding:0 16px;border-radius:999px;text-decoration:none;font-weight:500;font-size:14px}
.go{background:var(--brand);color:#fff}.back{border:1px solid var(--line);color:var(--fg)}a:focus-visible{outline:2px solid var(--brand);outline-offset:2px}
.mark{display:grid;place-items:center;width:48px;height:48px;border-radius:16px;background:var(--faint);color:var(--brand)}
-</style></head><body><header><a href="/">${LOGO}<span>Fuobe</span></a></header><main><span class="mark" aria-hidden="true">${COMPASS}</span><h1>${title}</h1><p>${text}</p><nav>${back ? `<a class="back" href="${back.href}">${back.label}</a>` : ""}<a class="go" href="/">${home}</a></nav></main></body></html>`;
- return new NextResponse(html, { status: 404, headers: { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" } });
+</style></head><body><header><a href="/">${LOGO}<span>Fuobe</span></a></header><main><span class="mark" aria-hidden="true">${icon}</span><h1>${title}</h1><p>${text}</p><nav>${nav}</nav></main></body></html>`;
}
-/** The Fuobe mark (src/app/icon.svg) and the 404's compass (lucide's Compass, as NotFoundState shows). */
+/** The Fuobe mark (src/app/icon.svg), the 404's compass (lucide's Compass, as NotFoundState shows) and backSoon's clock (lucide's Clock). */
const LOGO =
'<svg width="24" height="24" viewBox="0 0 32 32" aria-hidden="true"><rect width="32" height="32" rx="8" fill="#5d4bdb"/><g transform="translate(5.5 5.5) scale(0.875)" fill="none" stroke="#fff" stroke-width="2.3" stroke-linecap="round" stroke-linejoin="round"><path d="m12.296 3.464 3.02 3.956"/><path d="M20.2 6 3 11l-.9-2.4c-.3-1.1.3-2.2 1.3-2.5l13.5-4c1.1-.3 2.2.3 2.5 1.3z"/><path d="M3 11h18v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><path d="m6.18 5.276 3.1 3.899"/></g></svg>';
const COMPASS =
'<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z"/></svg>';
+const CLOCK =
+ '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>';
const behindHttps = (request: NextRequest) => request.nextUrl.protocol === "https:";
@@ -329,9 +350,9 @@ 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" } });
- }
+ // Visitors get a calm "back in a moment" (503); the server log says why. An auth.json that turns up after the move is
+ // not this: it is set aside and the site keeps serving.
+ if (authStoreFailed()) return backSoon(request);
// 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-sweep.ts b/src/server/account-sweep.ts
index 9e01d9d9..fdb8f381 100644
--- a/src/server/account-sweep.ts
+++ b/src/server/account-sweep.ts
@@ -4,6 +4,7 @@ import path from "node:path";
import { RETENTION_MS, runAccountDeletedHooks } from "./account-files";
import { clearAccountLoras } from "./account-loras";
import { accountById, deleteAccount, readAccountIds, setAccountDisabled } from "./auth";
+import { strayAccountIds } from "./auth-store";
import { accountEvent, accountFacts } from "./billing";
import { db } from "./db";
import { handOversDone } from "./generations";
@@ -98,7 +99,9 @@ export async function sweepAccountFiles(now = Date.now()): Promise<{ uploads: nu
if (owning.length) {
try {
const live = readAccountIds();
- if (live.size) gone = owning.filter((id) => !live.has(id));
+ // Accounts only an auth.json set aside unread lists (an older build may have signed them up): kept while it is there.
+ const waiting = strayAccountIds();
+ if (live.size) gone = owning.filter((id) => !live.has(id) && !waiting.has(id));
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.ts
index a4756766..3569a903 100644
--- a/src/server/auth-store.ts
+++ b/src/server/auth-store.ts
@@ -11,7 +11,7 @@
* 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.
+ * proxy answers 503 (a calm "back in a moment" page), 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.
@@ -23,8 +23,15 @@
*
* 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.
+ * bridges again.
+ *
+ * Any other auth.json found once the store was moved (a backup copied back, a file from elsewhere) is never read as
+ * sign-in data: the database stays the store and the site keeps serving. The file is set aside unread as
+ * auth.json.stray-<UTC time> (readable by this user only, never deleted here), the note goes back in its place, the log
+ * says so, and the owner sees a notice in Settings → Accounts and the admin API (its counts and its name only). Nothing in
+ * it signs anyone in, opens the studio, changes the password or the cookie secret. The accounts it lists that the
+ * database doesn't have keep their files while it is there (the account sweep skips them), so the owner can still choose
+ * it: a start with FUOBE_AUTH_REIMPORT=1 moves an auth.json in, as it is, over the database's sign-in data.
*/
import "server-only";
import type Database from "better-sqlite3";
@@ -106,7 +113,7 @@ const s = {
/** The store was moved (done or exported) and auth.json was looked at, at fileCheckedAt. */
done: false,
fileCheckedAt: 0,
- /** What that look found that keeps sign-in closed (an auth.json put back, or one that can't go in). */
+ /** What that look found that keeps sign-in closed (an export that can't be read, or can't go back 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,
@@ -115,7 +122,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 },
+ warned: { unreadable: 0, failed: 0, stray: 0 },
writes: 0,
};
@@ -181,21 +188,28 @@ 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(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") };
+ const parsed = parse(raw);
+ if ("error" in parsed) return parsed;
+ return { data: parsed.data, key, sha: crypto.createHash("sha256").update(raw).digest("hex") };
} catch (e) {
return { error: (e as NodeJS.ErrnoException).code ?? "can't be read" };
}
}
+/** A file's text as sign-in data, or why it isn't: "tombstone" for the note. */
+function parse(raw: Buffer): { data: AuthJson } | { error: string } {
+ 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(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 };
+}
+
/**
* 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
@@ -602,12 +616,24 @@ function bridgeTick(m: Marker): AuthStoreMode {
return s.done ? (s.held?.mode ?? "done") : "bridge";
}
-/** "auth.json.migrated-20261104T101500Z", or with -2, -3… when that is taken. */
-function backupName(at: number): string {
+/** "auth.json.<kind>-20261104T101500Z", or with -2, -3… when that is taken. */
+function freeName(kind: "migrated" | "stray", 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;
+ const name = `auth.json.${kind}-${stamp}${i > 1 ? `-${i}` : ""}`;
+ if (!lexists(path.join(DATA_DIR, name))) return name;
+ }
+}
+
+const backupName = (at: number) => freeName("migrated", at);
+
+/** There is something under that name (a link counts, wherever it points). */
+function lexists(file: string): boolean {
+ try {
+ fs.lstatSync(file);
+ return true;
+ } catch {
+ return false;
}
}
@@ -634,8 +660,8 @@ function retire(): void {
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.";
+const EXPORTED_BACK =
+ "Remove auth.json 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 {
@@ -649,10 +675,9 @@ function hold(mode: "unreadable" | "failed", message: string): AuthStoreMode {
* - 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.
+ * - Any other auth.json (a backup copied back, a file from elsewhere, one that can't be read): never read as sign-in
+ * data, which could bring back a revoked token or an old password. It is set aside unread (setAside) and the site
+ * keeps serving from the database. With FUOBE_AUTH_REIMPORT=1 it is moved in instead.
*/
function afterMove(m: Marker): AuthStoreMode {
s.done = true;
@@ -676,14 +701,207 @@ function afterMove(m: Marker): AuthStoreMode {
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 (!("error" in file!)) {
+ if (m.source === "auth.json" && file.sha === m.json_sha256) {
+ putAside(m);
+ return "done";
+ }
+ if (reimportAsked()) return reimport(file, "asked");
}
- if (reimportAsked()) return reimport(file, "asked");
- return hold("failed", PUT_BACK);
+ setAside("error" in file! ? "unreadable" : "stray");
+ return "done";
+}
+
+/** Why an auth.json was set aside: sign-in data, a file that isn't sign-in data, or one FUOBE_AUTH_REIMPORT=1 couldn't move in. */
+export type StrayReason = "stray" | "unreadable" | "import-failed";
+
+/** What a set-aside file lists, for the owner's notice: counts only (null when it isn't sign-in data). */
+export interface StrayCounts {
+ accounts: number;
+ tokens: number;
+ /** Accounts it lists whose id the database doesn't have. */
+ accountsNotInDatabase: number;
+}
+
+/** The names setAside gives (and the only ones the notice and the account sweep read back). */
+const STRAY_NAME = /^auth\.json\.stray-\d{8}T\d{6}Z(?:-\d+)?$/;
+/** A set-aside file bigger than this isn't read for its counts. */
+const STRAY_READ_MAX = 128 * 1024 * 1024;
+/** Notices kept (the newest). */
+const STRAY_ROWS_MAX = 100;
+/** Account ids kept per file for the sweep. */
+const STRAY_IDS_MAX = 100_000;
+const NOFOLLOW = fs.constants.O_NOFOLLOW ?? 0;
+
+/** A plain file's bytes, never through a link (null: not a plain file, too big, or it can't be read). */
+function readPlain(file: string): Buffer | null {
+ let fd: number | undefined;
+ try {
+ fd = fs.openSync(file, fs.constants.O_RDONLY | NOFOLLOW);
+ const st = fs.fstatSync(fd);
+ if (!st.isFile() || st.size > STRAY_READ_MAX) return null;
+ return fs.readFileSync(fd);
+ } catch {
+ return null;
+ } finally {
+ if (fd !== undefined) fs.closeSync(fd);
+ }
+}
+
+/** Readable by this user only, through the file itself (never a link put in its place). Not on Windows. */
+function keepPrivate(file: string): void {
+ if (process.platform === "win32") return;
+ let fd: number | undefined;
+ try {
+ fd = fs.openSync(file, fs.constants.O_RDONLY | NOFOLLOW);
+ if (fs.fstatSync(fd).isFile()) fs.fchmodSync(fd, 0o600);
+ } catch {
+ } finally {
+ if (fd !== undefined) fs.closeSync(fd);
+ }
+}
+
+const sameFile = (a: fs.Stats, b: fs.Stats) => a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs;
+
+/** How many accounts and tokens a set-aside file lists, and the ids of its accounts the database doesn't have. */
+function strayFacts(raw: Buffer | null): { counts: StrayCounts | null; ids: string[] } {
+ const parsed = raw ? parse(raw) : null;
+ if (!parsed || "error" in parsed) return { counts: null, ids: [] };
+ const list = (v: unknown): unknown[] => (Array.isArray(v) ? v : []);
+ const accounts = list(parsed.data.accounts);
+ const known = new Set((sql("SELECT id FROM auth_accounts").all() as { id: string }[]).map((r) => r.id));
+ const ids = new Set<string>();
+ for (const a of accounts) {
+ const id = a && typeof a === "object" ? (a as { id?: unknown }).id : undefined;
+ if (typeof id === "string" && id && id.length <= 64 && !known.has(id)) ids.add(id);
+ }
+ return { counts: { accounts: accounts.length, tokens: list(parsed.data.tokens).length, accountsNotInDatabase: ids.size }, ids: [...ids].slice(0, STRAY_IDS_MAX) };
+}
+
+/**
+ * An auth.json found once the store was moved, that isn't the note, the bridge's last copy or an export: kept as
+ * auth.json.stray-<UTC time>, unread as sign-in data, and the note put back. Under the database's write lock, so two
+ * servers never both act on one file. auth.json is never missing on the way (an older build would read "no file" as
+ * "no password"): the file gets its second name by a link first, and the note then replaces auth.json by a rename, only
+ * when auth.json is still the file that was kept (otherwise what is there now is looked at again next time).
+ */
+function setAside(reason: StrayReason): void {
+ let made: { name: string; counts: StrayCounts | null } | null = null;
+ try {
+ immediate(() => {
+ // Another server moved it in (FUOBE_AUTH_REIMPORT=1) or an export happened a moment ago: not this one's to do.
+ if (marker()?.state !== "done") return;
+ let before: fs.Stats;
+ try {
+ before = fs.lstatSync(AUTH_FILE);
+ } catch {
+ return;
+ }
+ // A folder (or a device…) named auth.json: nothing reads it, and nothing can be renamed over it.
+ if (!before.isFile() && !before.isSymbolicLink()) throw Object.assign(new Error("it is not a file"), { code: "not a file" });
+ const name = freeName("stray", now());
+ const target = path.join(DATA_DIR, name);
+ let linked = false;
+ if (before.isSymbolicLink()) {
+ // A link to a file elsewhere: the same link under the new name (what it points to is never touched or read).
+ fs.symlinkSync(fs.readlinkSync(AUTH_FILE), target);
+ } else {
+ try {
+ fs.linkSync(AUTH_FILE, target);
+ linked = true;
+ } catch (e) {
+ const code = (e as NodeJS.ErrnoException).code;
+ if (code === "EEXIST" || code === "ENOENT") throw e;
+ // A file system without links.
+ fs.copyFileSync(AUTH_FILE, target, fs.constants.COPYFILE_EXCL);
+ }
+ }
+ const raw = before.isSymbolicLink() ? null : readPlain(target);
+ const parsed = raw ? parse(raw) : null;
+ if (parsed && "error" in parsed && parsed.error === "tombstone") {
+ // The note itself, put there a moment ago: nothing to keep.
+ fs.rmSync(target, { force: true });
+ return;
+ }
+ keepPrivate(target);
+ const kept = linked ? fs.lstatSync(target) : before;
+ let current: fs.Stats | null = null;
+ try {
+ current = fs.lstatSync(AUTH_FILE);
+ } catch {}
+ if (!current) writeTombstone();
+ else if (sameFile(current, kept)) writeAtomic(AUTH_FILE, TOMBSTONE);
+ const facts = strayFacts(raw);
+ const why: StrayReason = reason === "import-failed" ? reason : facts.counts ? "stray" : "unreadable";
+ sql("INSERT OR REPLACE INTO auth_stray_files (name, found_at, reason, counts_json, account_ids_json) VALUES (?, ?, ?, ?, ?)").run(
+ name,
+ now(),
+ why,
+ facts.counts && JSON.stringify(facts.counts),
+ facts.ids.length ? JSON.stringify(facts.ids) : null,
+ );
+ // Notices for files that are gone, and past the newest STRAY_ROWS_MAX.
+ for (const r of sql("SELECT name FROM auth_stray_files").all() as { name: string }[]) {
+ if (!STRAY_NAME.test(r.name) || !lexists(path.join(DATA_DIR, r.name))) sql("DELETE FROM auth_stray_files WHERE name = ?").run(r.name);
+ }
+ sql("DELETE FROM auth_stray_files WHERE name NOT IN (SELECT name FROM auth_stray_files ORDER BY found_at DESC, name DESC LIMIT ?)").run(STRAY_ROWS_MAX);
+ made = { name, counts: facts.counts };
+ });
+ } catch (e) {
+ warnOnce("stray", `An auth.json is in the data folder but couldn't be set aside (${(e as NodeJS.ErrnoException).code ?? (e as Error).message}). It is not read: sign-in goes on from the database.`);
+ return;
+ }
+ if (made) {
+ const { name, counts } = made as { name: string; counts: StrayCounts | null };
+ const what = counts ? `it lists ${counts.accounts} accounts (${counts.accountsNotInDatabase} not in the database) and ${counts.tokens} API tokens` : "it isn't sign-in data Fuobe can read";
+ console.warn(
+ `[fuobe] An auth.json was found in the data folder after sign-in data moved into the database. It was not used: it is kept as ${name} (${what}), and sign-in goes on from the database. Delete that file when you don't need it, or see "Sign-in data" in docs/SELF-HOSTING.md to use it instead.`,
+ );
+ }
+}
+
+interface StrayRow {
+ name: string;
+ found_at: number;
+ reason: StrayReason;
+ counts_json: string | null;
+ account_ids_json: string | null;
+}
+
+/** The set-aside files still in the data folder, newest first. */
+function strayRows(): StrayRow[] {
+ return (sql("SELECT * FROM auth_stray_files ORDER BY found_at DESC, name DESC").all() as StrayRow[]).filter(
+ (r) => STRAY_NAME.test(r.name) && lexists(path.join(DATA_DIR, r.name)),
+ );
+}
+
+/** For the owner (GET /api/admin/accounts): each auth.json set aside unread that is still in the data folder. */
+export interface SignInNotice {
+ file: string;
+ foundAt: number;
+ reason: StrayReason;
+ /** null: the file isn't sign-in data Fuobe can read. */
+ counts: StrayCounts | null;
+}
+
+export function signInNotices(): SignInNotice[] {
+ try {
+ if (authStoreClosed()) return [];
+ return strayRows().map((r) => ({ file: r.name, foundAt: r.found_at, reason: r.reason, counts: r.counts_json ? (JSON.parse(r.counts_json) as StrayCounts) : null }));
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * Accounts a set-aside auth.json lists that the database doesn't have, while that file is still there: the account
+ * sweep keeps their files (an older build may have signed them up), until the owner deletes the file or moves it in.
+ * Throws when it can't tell (the sweep then removes nothing).
+ */
+export function strayAccountIds(): Set<string> {
+ const ids = new Set<string>();
+ for (const r of strayRows()) for (const id of r.account_ids_json ? (JSON.parse(r.account_ids_json) as string[]) : []) ids.add(id);
+ return ids;
}
/** auth.json as the bridge last left it: kept under the backup name (never written over), and the note in its place. */
@@ -738,8 +956,14 @@ function reimport(file: { data: AuthJson; key: string | null; sha: string }, why
).run(at, at, file.key, file.sha, JSON.stringify(counts));
});
} catch (e) {
+ if (why === "asked" && e instanceof DataError) {
+ // Asked for, and its data can't go in: the database keeps its sign-in data, and the file is set aside.
+ console.error(`[fuobe] FUOBE_AUTH_REIMPORT=1: auth.json couldn't be moved into the database (${e.message}); nothing was changed.`);
+ setAside("import-failed");
+ return "done";
+ }
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}`);
+ return hold("failed", `auth.json couldn't be moved back into the database (${how}); nothing was changed. ${EXPORTED_BACK}`);
}
if (counts) {
const c = counts as Counts;
@@ -820,7 +1044,11 @@ function beforeMove(): AuthStoreMode {
/** 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. */
+/**
+ * The store failed (not just an unreadable auth.json waiting): the database can't be used, an older install's auth.json
+ * couldn't move in, or an export came back after the database changed. The proxy answers every request with a calm
+ * "back in a moment" page (503, so a new release in this state is never switched to); the log says why.
+ */
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.";
diff --git a/src/server/db.ts b/src/server/db.ts
index 26a7c25b..13475144 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -16,6 +16,9 @@ export const DATA_DIR = path.resolve(/*turbopackIgnore: true*/ process.env.FUOBE
* 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).
+ * - auth_stray_files: each auth.json found after the move and set aside unread (auth.json.stray-<UTC time>): when, why,
+ * its counts (for the owner's notice) and the ids of the accounts it lists that the database doesn't have (the account
+ * sweep keeps their files while that file is there). Never an email, a hash or a secret.
* Safe to run on every start.
*/
export const AUTH_TABLES = `CREATE TABLE IF NOT EXISTS auth_install (
@@ -82,7 +85,14 @@ export const AUTH_TABLES = `CREATE TABLE IF NOT EXISTS auth_install (
hash TEXT PRIMARY KEY,
exp INTEGER NOT NULL
);
- CREATE INDEX IF NOT EXISTS auth_signed_out_exp ON auth_signed_out(exp);`;
+ CREATE INDEX IF NOT EXISTS auth_signed_out_exp ON auth_signed_out(exp);
+ CREATE TABLE IF NOT EXISTS auth_stray_files (
+ name TEXT PRIMARY KEY,
+ found_at INTEGER NOT NULL,
+ reason TEXT NOT NULL,
+ counts_json TEXT,
+ account_ids_json TEXT
+ );`;
/** Run in order, once each: a migration is known by its place in this list (append only, never reorder). */
export const MIGRATIONS: string[] = [
@@ -909,6 +919,7 @@ const AUTH_COLUMNS: Record<string, string[]> = {
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"],
+ auth_stray_files: ["name", "found_at", "reason", "counts_json", "account_ids_json"],
};
/** Make the sign-in tables and check they are ours. Never throws: a problem is kept for auth-store.ts, which fails closed. */
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 5b0345b9..3b07924f 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -449,6 +449,8 @@ export const ASSET_FREE: Record<string, string> = {
"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",
+ "auth_stray_files.counts_json": "how many accounts and tokens a set-aside auth.json lists",
+ "auth_stray_files.account_ids_json": "ids of the accounts a set-aside auth.json lists that the database doesn't have",
"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/tests/admin-tokens.test.ts b/tests/admin-tokens.test.ts
index a491a57e..2b6933b4 100644
--- a/tests/admin-tokens.test.ts
+++ b/tests/admin-tokens.test.ts
@@ -307,7 +307,7 @@ describe("admin tokens: every admin route asks for its scope", () => {
const a = auth.createAccount(`owner-view-${++n}@example.com`, "long enough");
const res = await routes.accounts.GET(req("/api/admin/accounts", { cookie: ownerCookie }));
expect(res.status).toBe(200);
- expect(Object.keys((await res.json()) as object).sort()).toEqual(["items", "total", "totals"]);
+ expect(Object.keys((await res.json()) as object).sort()).toEqual(["items", "signInNotices", "total", "totals"]);
const off = await routes.account.PATCH(req(`/api/admin/accounts/${a.id}`, { cookie: ownerCookie, method: "PATCH", body: { disabled: true } }), ctx({ id: a.id }));
expect(await off.json()).toMatchObject({ id: a.id, disabled: true });
const denied = await routes.accounts.GET(req("/api/admin/accounts"));
diff --git a/tests/auth-migration.test.ts b/tests/auth-migration.test.ts
index 78bf8312..5d318ff3 100644
--- a/tests/auth-migration.test.ts
+++ b/tests/auth-migration.test.ts
@@ -89,6 +89,13 @@ function veryOldLocked(dir: string): boolean {
return !!d.password && !verify("") && !verify("owner password") && !d.secret && !d.tokens?.length && !d.accounts?.length;
}
+/** The auth.json files set aside unread after the move (auth.json.stray-<UTC time>). */
+const strays = (dir: string) =>
+ fs
+ .readdirSync(dir)
+ .filter((f) => f.startsWith("auth.json.stray-"))
+ .sort();
+
/** 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"));
@@ -213,7 +220,7 @@ describe("a new install", () => {
expect(srv.store.authStoreMode()).toBe("done");
});
- it("moves in an auth.json put there before the first change; one put back after is never read on its own", async () => {
+ it("moves in an auth.json put there before the first change; one put back after keeps serving, is set aside unread, and the owner is told", async () => {
const dir = tempDir("fuobe-auth-drop-");
let srv = await server(dir);
expect(srv.auth.authEnabled()).toBe(false);
@@ -221,25 +228,45 @@ 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, and nobody gets in (503) until it goes.
+ // Put aside, then an auth.json without a password put back (read, it would open the studio).
globalThis.__fuobeAuthClock = () => Date.now() + 11 * MIN;
expect(srv.store.authStoreMode()).toBe("done");
+ const putBack = JSON.stringify({ secret: "", tokens: [] }, null, 2);
legacyWrite(dir, { secret: "", tokens: [] });
const errors = vi.spyOn(console, "error").mockImplementation(() => {});
+ const warns = vi.spyOn(console, "warn").mockImplementation(() => {});
srv = await server(dir);
- expect(srv.store.authStoreMode()).toBe("failed");
- expect(srv.store.authStoreFailed()).toBe(true);
+ // The site keeps serving, from the database: sign-in on, the password as it was.
+ expect(srv.store.authStoreMode()).toBe("done");
+ expect(srv.store.authStoreFailed()).toBe(false);
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));
+ expect(srv.auth.checkPassword("dropped password")).toBe(true);
+ expect(srv.auth.readAccountIds().size).toBe(0);
+ // Set aside, unread and as it was, readable by the server's user only; the note back in place of auth.json.
+ const stray = strays(dir);
+ expect(stray).toHaveLength(1);
+ expect(fs.readFileSync(path.join(dir, stray[0]), "utf8")).toBe(putBack);
+ if (process.platform !== "win32") expect(fs.statSync(path.join(dir, stray[0])).mode & 0o777).toBe(0o600);
+ expect(isNote(dir)).toBe(true);
+ // The owner is told: the file's name and its counts, nothing from inside it.
+ expect(srv.store.signInNotices()).toEqual([{ file: stray[0], foundAt: expect.any(Number), reason: "stray", counts: { accounts: 0, tokens: 0, accountsNotInDatabase: 0 } }]);
+ expect(warns.mock.calls.flat().join("\n")).toContain(stray[0]);
+ expect(errors).not.toHaveBeenCalled();
+ vi.restoreAllMocks();
+ // Visitors see the site, not an error: /login answers and a page asks for sign-in.
+ const { proxy } = await import("@/proxy");
+ const { NextRequest } = await import("next/server");
+ expect(proxy(new NextRequest("http://localhost:3000/login")).status).toBe(200);
+ expect(proxy(new NextRequest("http://localhost:3000/")).status).toBe(307);
+ // Another start: nothing new to set aside, the notice stays while the file is there.
srv = await server(dir);
expect(srv.store.authStoreMode()).toBe("done");
+ expect(strays(dir)).toEqual(stray);
+ expect(srv.store.signInNotices()).toHaveLength(1);
+ // The owner deletes the file: the notice goes.
+ fs.rmSync(path.join(dir, stray[0]));
+ expect(srv.store.signInNotices()).toEqual([]);
expect(srv.auth.checkPassword("dropped password")).toBe(true);
- expect(isNote(dir)).toBe(true);
});
});
@@ -505,6 +532,11 @@ describe("going back to an older build, and forward again", () => {
expect(srv.store.authStoreMode()).toBe("done");
expect(backups()).toHaveLength(2);
expect(isNote(dir)).toBe(true);
+ // The export and its way back are never taken for a stray file.
+ globalThis.__fuobeAuthClock = () => Date.now() + 13 * MIN;
+ expect(srv.store.authStoreMode()).toBe("done");
+ expect(strays(dir)).toEqual([]);
+ expect(srv.store.signInNotices()).toEqual([]);
});
it("an export the older build never used: back to the database as it was", async () => {
@@ -550,7 +582,7 @@ describe("going back to an older build, and forward again", () => {
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 () => {
+ it("a backup copied back over auth.json: unchanged it is put aside again; changed by an older build it is set aside, the site keeps serving, and nothing is swept", async () => {
const { dir, after } = await moved("fuobe-auth-putback-");
let srv = await server(dir);
expect(srv.store.authStoreMode()).toBe("done");
@@ -561,28 +593,41 @@ describe("going back to an older build, and forward again", () => {
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.
+ expect(strays(dir)).toEqual([]);
+ // Copied back, and an older build signed someone up there (and that account made a file here).
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));
+ vi.spyOn(console, "warn").mockImplementation(() => {});
srv = await server(dir);
expect(srv.store.authStoreMode()).toBe("done");
+ expect(srv.store.authStoreFailed()).toBe(false);
+ // The database's accounts go on; the file's new account isn't one.
+ expect(srv.auth.accountById(after.id)).toBeDefined();
+ expect(srv.auth.checkAccount("[email protected]", "long enough")?.id).toBe(after.id);
+ expect(srv.auth.checkAccount("[email protected]", "putback password")).toBeNull();
+ expect(strays(dir)).toHaveLength(1);
+ expect(isNote(dir)).toBe(true);
+ expect(srv.store.signInNotices()[0].counts).toEqual({ accounts: 5, tokens: 3, accountsNotInDatabase: 1 });
+ // The sweep keeps the files of the account only that file lists, while it is there.
+ const { saveFile, getAsset } = await import("@/server/storage");
+ const { sweepAccountFiles } = await import("@/server/account-sweep");
+ const png = Buffer.from("89504e470d0a1a0a0000000d4948445200000001000000010806000000", "hex");
+ const theirs = saveFile({ data: png, contentType: "image/png", source: "upload", accountId: "acctputback000001" });
+ expect((await sweepAccountFiles()).accounts).toBe(0);
+ expect(getAsset(theirs.id)).toBeDefined();
+ // A running server notices a file put back within a minute (and sets it aside under a name of its own).
legacyWrite(dir, old);
expect(srv.store.authStoreMode()).toBe("done");
+ expect(strays(dir)).toHaveLength(1);
globalThis.__fuobeAuthClock = () => Date.now() + 61_000;
- vi.spyOn(console, "error").mockImplementation(() => {});
- expect(srv.store.authStoreMode()).toBe("failed");
+ expect(srv.store.authStoreMode()).toBe("done");
+ expect(strays(dir)).toHaveLength(2);
+ expect(isNote(dir)).toBe(true);
vi.restoreAllMocks();
globalThis.__fuobeAuthClock = undefined;
- // Moved in when asked: the file as it is.
+ // Moved in when asked: the owner copies the file back and starts once with FUOBE_AUTH_REIMPORT=1.
+ fs.copyFileSync(path.join(dir, strays(dir)[0]), authFile(dir));
process.env.FUOBE_AUTH_REIMPORT = "1";
try {
srv = await server(dir);
@@ -593,6 +638,138 @@ describe("going back to an older build, and forward again", () => {
} finally {
delete process.env.FUOBE_AUTH_REIMPORT;
}
+ // Once the set-aside files are gone, the sweep may remove files of accounts the database doesn't have.
+ for (const f of strays(dir)) fs.rmSync(path.join(dir, f));
+ expect(srv.store.signInNotices()).toEqual([]);
+ });
+});
+
+describe("an auth.json that turns up after the move", () => {
+ /** An older install moved in and put aside: the database is the store. */
+ async function settled(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;
+ return o;
+ }
+
+ it("with another password, secret, tokens and accounts: none of it takes effect, and nothing of it is logged", async () => {
+ const { dir, fx } = await settled("fuobe-auth-stray-");
+ const secret = crypto.randomBytes(32).toString("hex");
+ const token = `fuobe_${crypto.randomBytes(24).toString("base64url")}`;
+ const intruder = { id: "acctintruder00001", email: "[email protected]", hash: hashPw("intruder password"), createdAt: Date.now() };
+ const stray = {
+ password: hashPw("stray password"),
+ secret,
+ tokens: [{ id: "tokx", name: "x", hash: sha(token), prefix: token.slice(0, 12), createdAt: Date.now() }],
+ accounts: [intruder],
+ publicSignup: false,
+ };
+ legacyWrite(dir, stray);
+ const logs = [vi.spyOn(console, "warn").mockImplementation(() => {}), vi.spyOn(console, "error").mockImplementation(() => {}), vi.spyOn(console, "info").mockImplementation(() => {})];
+ const srv = await server(dir);
+ expect(srv.store.authStoreMode()).toBe("done");
+ // The database's password, cookies, tokens and accounts work as before.
+ expect(srv.auth.checkPassword("owner password")).toBe(true);
+ expect(srv.auth.validSession(fx.cookies.owner)).toBe(true);
+ expect(srv.auth.validToken(`Bearer ${fx.tokens[0]}`)).toBe(true);
+ expect(srv.auth.checkAccount("[email protected]", "first password")?.id).toBe("acct00000000000001");
+ expect(srv.auth.publicSignupSetting()).toBe(true);
+ // The file's never do: its password, its token, its account, a cookie signed with its secret.
+ expect(srv.auth.checkPassword("stray password")).toBe(false);
+ expect(srv.auth.validToken(`Bearer ${token}`)).toBe(false);
+ expect(srv.auth.checkAccount("[email protected]", "intruder password")).toBeNull();
+ const exp = Date.now() + DAY;
+ expect(srv.auth.validSession(`${exp}.${mac(`${secret}.${sha(stray.password)}`, String(exp))}`)).toBe(false);
+ expect(srv.auth.validSession(`${exp}.${intruder.id}.${mac(`${secret}.${sha(intruder.hash)}`, `${exp}.${intruder.id}`)}`)).toBe(false);
+ expect((srv.db().prepare("SELECT secret, password_hash FROM auth_install").get() as { secret: string; password_hash: string })).toEqual({
+ secret: fx.data.secret,
+ password_hash: fx.data.password,
+ });
+ expect(srv.auth.readAccountIds().has(intruder.id)).toBe(false);
+ // An older build pointed at this folder reads the note again, and stays locked.
+ expect(isNote(dir)).toBe(true);
+ expect(veryOldLocked(dir)).toBe(true);
+ // Counts only, in the log and the notice.
+ expect(srv.store.signInNotices()[0].counts).toEqual({ accounts: 1, tokens: 1, accountsNotInDatabase: 1 });
+ const logged = logs.flatMap((l) => l.mock.calls.flat()).join("\n");
+ for (const s of [intruder.email, intruder.hash, secret, stray.password, sha(token), ...fx.data.accounts.map((a) => a.email)]) expect(logged).not.toContain(s);
+ expect(JSON.stringify(srv.store.signInNotices())).not.toContain("intruder");
+ vi.restoreAllMocks();
+ });
+
+ it("a file that isn't sign-in data, and FUOBE_AUTH_REIMPORT=1 with data that can't go in: set aside, and the site keeps serving", async () => {
+ const { dir, fx } = await settled("fuobe-auth-stray-bad-");
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ fs.writeFileSync(authFile(dir), "{ not json");
+ let srv = await server(dir);
+ expect(srv.store.authStoreMode()).toBe("done");
+ expect(srv.auth.validSession(fx.cookies.owner)).toBe(true);
+ expect(isNote(dir)).toBe(true);
+ expect(srv.store.signInNotices()).toMatchObject([{ reason: "unreadable", counts: null }]);
+ const bad = structuredClone(fx.data);
+ bad.accounts[1].email = bad.accounts[0].email;
+ bad.password = hashPw("a password that must not win");
+ legacyWrite(dir, bad);
+ process.env.FUOBE_AUTH_REIMPORT = "1";
+ try {
+ srv = await server(dir);
+ expect(srv.store.authStoreMode()).toBe("done");
+ } finally {
+ delete process.env.FUOBE_AUTH_REIMPORT;
+ }
+ expect(srv.store.authStoreFailed()).toBe(false);
+ expect(srv.auth.checkPassword("owner password")).toBe(true);
+ expect(srv.auth.checkPassword("a password that must not win")).toBe(false);
+ expect(srv.auth.listAccounts()).toHaveLength(4);
+ expect(isNote(dir)).toBe(true);
+ expect(srv.store.signInNotices().map((n) => n.reason)).toEqual(["import-failed", "unreadable"]);
+ vi.restoreAllMocks();
+ });
+
+ it("a file that turns up during a change: the change is saved in the database, and the file is set aside at the next look", async () => {
+ const { dir } = await settled("fuobe-auth-stray-write-");
+ const srv = await server(dir);
+ expect(srv.store.authStoreMode()).toBe("done");
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ const made = srv.store.authWrite(() => {
+ legacyWrite(dir, { password: hashPw("mid-write password"), secret: "b".repeat(64), tokens: [] });
+ return srv.auth.normalizeEmail("[email protected]");
+ });
+ expect(made).toBe("[email protected]");
+ srv.auth.setPassword("changed password");
+ expect(srv.auth.checkPassword("changed password")).toBe(true);
+ // Not read while it waits for the next look.
+ expect(srv.auth.checkPassword("mid-write password")).toBe(false);
+ globalThis.__fuobeAuthClock = () => Date.now() + 61_000;
+ expect(srv.store.authStoreMode()).toBe("done");
+ expect(strays(dir)).toHaveLength(1);
+ expect(isNote(dir)).toBe(true);
+ expect(srv.auth.checkPassword("changed password")).toBe(true);
+ expect(srv.auth.checkPassword("mid-write password")).toBe(false);
+ vi.restoreAllMocks();
+ });
+
+ it.skipIf(process.platform === "win32")("a link in place of auth.json: kept as a link, what it points to never read or changed", async () => {
+ const { dir } = await settled("fuobe-auth-stray-link-");
+ const elsewhere = path.join(tempDir("fuobe-auth-elsewhere-"), "other.json");
+ fs.writeFileSync(elsewhere, JSON.stringify({ password: hashPw("linked password"), secret: "c".repeat(64), tokens: [] }), { mode: 0o644 });
+ fs.rmSync(authFile(dir));
+ fs.symlinkSync(elsewhere, authFile(dir));
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ const srv = await server(dir);
+ expect(srv.store.authStoreMode()).toBe("done");
+ expect(srv.auth.checkPassword("linked password")).toBe(false);
+ expect(fs.lstatSync(authFile(dir)).isSymbolicLink()).toBe(false);
+ expect(isNote(dir)).toBe(true);
+ const [kept] = strays(dir);
+ expect(fs.readlinkSync(path.join(dir, kept))).toBe(elsewhere);
+ expect(fs.statSync(elsewhere).mode & 0o777).toBe(0o644);
+ expect(srv.store.signInNotices()).toMatchObject([{ reason: "unreadable", counts: null }]);
+ vi.restoreAllMocks();
});
});
@@ -649,6 +826,30 @@ describe("a crash, or another server, while moving in", () => {
expect(JSON.parse(after.marker()!.counts_json as string)).toMatchObject({ accounts: 4 });
}, 60_000);
+ it("servers looking at a stray auth.json at the same moment set it aside once, and all keep serving", async () => {
+ const { dir, srv } = await olderInstall("fuobe-auth-stray-race-");
+ expect(srv.store.authStoreMode()).toBe("bridge");
+ globalThis.__fuobeAuthClock = () => Date.now() + 11 * MIN;
+ expect(srv.store.authStoreMode()).toBe("done");
+ globalThis.__fuobeAuthClock = undefined;
+ globalThis.__fuobeDb?.close();
+ globalThis.__fuobeDb = undefined;
+ legacyWrite(dir, { password: hashPw("raced password"), secret: "d".repeat(64), tokens: [] });
+ 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: "done", accounts: 4 }));
+ expect(fs.readdirSync(dir).filter((f) => f.startsWith("auth.json.stray-"))).toHaveLength(1);
+ expect(isNote(dir)).toBe(true);
+ const after = await server(dir);
+ expect(after.store.signInNotices()).toHaveLength(1);
+ expect(after.auth.checkPassword("owner password")).toBe(true);
+ expect(after.auth.checkPassword("raced password")).toBe(false);
+ }, 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.
@@ -738,10 +939,47 @@ describe("an auth.json that can't be read, or can't go in", () => {
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);
+ await expectBackSoon(proxy, NextRequest);
});
}
+
+ it("a database whose sign-in tables can't be used: fails closed, and visitors get a calm page, never why", async () => {
+ const dir = tempDir("fuobe-auth-db-broken-");
+ // A table of the same name with other columns (made by something else) is never used.
+ const Database = (await import("better-sqlite3")).default;
+ const d = new Database(path.join(dir, "fuobe.db"));
+ d.exec("CREATE TABLE auth_accounts (id TEXT PRIMARY KEY, name TEXT)");
+ d.close();
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ const srv = await server(dir);
+ expect(srv.store.authStoreMode()).toBe("failed");
+ expect(srv.auth.authEnabled()).toBe(true);
+ expect(srv.auth.checkPassword("")).toBe(false);
+ expect(() => srv.auth.setPassword("a password")).toThrow();
+ expect(srv.store.signInNotices()).toEqual([]);
+ const { proxy } = await import("@/proxy");
+ const { NextRequest } = await import("next/server");
+ await expectBackSoon(proxy, NextRequest);
+ vi.restoreAllMocks();
+ });
});
+/** Every request gets a calm "back in a moment" (503, so a deploy never switches to it), and no word about why. */
+async function expectBackSoon(proxy: (r: import("next/server").NextRequest) => Response, Req: typeof import("next/server").NextRequest) {
+ const page = proxy(new Req("http://localhost:3000/login"));
+ expect(page.status).toBe(503);
+ expect(page.headers.get("content-type")).toMatch(/text\/html/);
+ expect(page.headers.get("retry-after")).toBe("30");
+ const html = await page.text();
+ expect(html).toContain("Back in a moment");
+ const api = proxy(new Req("http://localhost:3000/api/auth/me"));
+ expect(api.status).toBe(503);
+ const body = await api.text();
+ expect(JSON.parse(body).error).toMatch(/back in a moment/);
+ for (const text of [html, body]) for (const word of [/sign-in/i, /database/i, /auth\.json/i, /\blogs?\b/i, /can't read/i]) expect(text).not.toMatch(word);
+}
+
describe("100,000 accounts", () => {
it("move in once, and every lookup stays quick", async () => {
const dir = tempDir("fuobe-auth-100k-");