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.

Accounts 1 fixes: old long passwords sign in, FUOBE_SIGNIN locks Settings

Claude935e7fa6eff3
diff --git a/README.md b/README.md
index 1f1b7f96..cde71e45 100644
--- a/README.md
+++ b/README.md
@@ -81,11 +81,16 @@ Share links are the one exception: `/s/<token>` and its files open for anyone wh
| Variable | What it does |
|---|---|
-| `FUOBE_PASSWORD` | Turns sign-in on; a password set this way can't be changed from Settings |
+| `FUOBE_PASSWORD` (or `FUOBE_OWNER_PASSWORD`) | The owner's break-glass password, up to 500 characters: synced at every start (a new value signs every browser out) and turns sign-in on. Settings can't change it while it is set; once you unset it, it stays the password and sign-in stays on, and you change or remove it in Settings → Security |
+| `FUOBE_SIGNIN` | `on` or `off` pins sign-in, whatever Settings says (Settings shows "Set by the server"). `on` needs a password (`FUOBE_PASSWORD`, or one set in Settings first), or Fuobe doesn't start |
+| `FUOBE_SECRET` | The root secret sessions are signed with: 64 hex characters, or at least 32 characters. Without it Fuobe makes `data/secret.key`; back that file up with the database. A different key than the data folder was made with stops the start, unless `FUOBE_ACCEPT_NEW_SECRET=1` (everyone signs in again) |
| `FUOBE_ALLOWED_ORIGINS` | Extra hosts Fuobe is reached at, comma-separated. Without a password, Fuobe answers only on IP addresses, localhost, single-label and LAN names (`.local`, `.lan`, `.home.arpa`, `.internal`) and the machine's hostname; add any other domain (a reverse proxy, a tunnel, a Tailscale name), or `*` to turn the check off. Also counts as "same site" for the cross-site write check behind a proxy that forwards neither Host nor X-Forwarded-Host |
-| `FUOBE_TRUST_PROXY=1` | Behind a reverse proxy: trust the last `X-Forwarded-For` hop, so wrong passwords, and too many wrong share links, lock out only that visitor (60 s). Without it, everyone shares one limit: passwords are slowed to one attempt every 4 s and never locked, and wrong share links past 100 a minute get 429 while real links still open |
+| `FUOBE_TRUSTED_PROXIES` (or `FUOBE_TRUST_PROXY=1`, one hop) | Behind a reverse proxy: how many `X-Forwarded-For` hops to trust (`1`, `2`…), or the proxies' addresses as a comma-separated CIDR list. Then wrong passwords, and too many wrong share links, lock out only that visitor (60 s), and sign-ins record the visitor's address. 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) and no address is recorded |
+| `FUOBE_SITE_URL` | The address people open Fuobe at. An `https://` address makes the sign-in cookies `__Host-` (Secure, whole site) |
+| `FUOBE_INSTALL_NAME` | The name the sign-in card shows ("Sign in to …", default Fuobe) |
+| `FUOBE_MODE` | `personal` (the only mode so far; without `FUOBE_SIGNIN` or a password it is Just me on this computer). `studio` and `platform` stop the start with one line until accounts arrive |
| `FUOBE_ALLOW_PRIVATE_URLS=1` | Let inputs, product links and project sources be fetched from private / LAN addresses (they are refused by default), and let Assist connectors use plain http beyond localhost (without it a connector needs https unless it is on localhost; a private https address is accepted, with a warning that Claude can only reach it through a public tunnel) |
-| `FUOBE_DATA_DIR` | Where the database, files and `auth.json` live (default `./data`) |
+| `FUOBE_DATA_DIR` | Where the database, files and `secret.key` live (default `./data`). An `auth.json` from before accounts is imported once at the first start and then left in place, unread |
| `FUOBE_DEMO_MODE` | `auto` (default: demo outputs only when a model's provider isn't connected), `on` or `off` |
| `FUOBE_SKILLS_DIR` | Where Assist's built-in skills are read from (default `./skills`) |
| `FUOBE_ENGINE_MODE`, `FUOBE_CLOUD_PROVIDER`, `FUOBE_ENHANCE_PROVIDER` | The Settings choices above |
@@ -97,6 +102,7 @@ Uploads up to 200 MB work with sign-in on. Inputs given as URLs are fetched only
- **Get the new code and rebuild.** Pull `main`. On Windows, run `start.bat` as usual: it installs packages on every start and rebuilds because the code changed. On Mac or Linux, run `pnpm install`, then `pnpm build` (or just `pnpm dev`). Round 4 adds only one dependency, `@types/three` (for development; PR #9, PR #10 and PR #12 add none, so `pnpm install` has nothing new for them); round 3 added `@xyflow/react`, `@google/model-viewer`, `three` and `unpdf`. In a checkout without `.next`, run `pnpm exec next typegen` (or a dev or build run) before `pnpm typecheck`.
- **Your data upgrades on its own.** The database migrations run once each at start-up, in order, and an existing `data/` folder (or `FUOBE_DATA_DIR`) keeps everything it holds. Round 4 adds five migrations: one for the Library's nested folders, pins and review status (PR #6), two new tables in PR #9, `lora_mirrors` (each LoRA copy Fuobe makes) and `content_series` (Content Factory), and two in PR #12: `shares` (share links; only a hash of each link's token is stored) and Assist's `assist_schedules` and `assist_connectors`, with four new columns on `assist_thread_state`. They are added at the first start, and PR #12's only add tables and columns. PR #7 and PR #10 add none. Settings → Models & licences keeps its switches in the existing settings table (`models.access`), and Soul ID uses the existing trainings table. The list is in [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md#storage-srcserverdbts-storagets-settingsts).
+- **Sign-in moves to accounts.** The first start copies the database to `data/backups/fuobe-<time>-pre-accounts.db` (without sign-in sessions), moves the password and API tokens from `data/auth.json` into the database (the file stays, unread) and makes `data/secret.key`: back that up with the database, since a different key stops the start. With a password, each browser signs in once more; API tokens, MCP clients, the CLI, share links and `FUOBE_PASSWORD` keep working. Without one nothing changes: Just me on this computer. Adds `better-auth` 1.7.10 and `kysely` 0.29.6 (both MIT).
- **Canvases are saved in a new form (PR #10).** A board is rewritten with pages the next time it is saved, and older Fuobe builds can't read it after that. Back up the data folder if you might go back to an earlier version. Scripts that read a canvas through the API: `GET /api/canvases/:id` now returns `canvas.pages` (each page with its graph), not `canvas.graph`.
- **If you ran one of the round-3 package branches** (`r3/*`, `r3b/*`) before they were merged, start with a fresh data folder. Those branches numbered their migrations differently, so tables can be missing. Move the old folder aside rather than deleting it if it holds results you want. A folder used by the `r4/assist-connectors` branch before its review fixes needs the same: its migration changed in place. The same goes for a folder used by the `r4/content-factory` branch on its own: there Content Factory's table took the Library migration's number, so the Library's folders, pins and review status would never be added.
- **Start on Home now runs the job** in Image, Video or Edit instead of only opening the studio. With a saved key for the default model this is a paid run; the line under the box says first what will run and what it costs. **⌘K / Ctrl+K** opens the search palette instead of going Home.
diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.ts
index 0015aa23..03bc2ace 100644
--- a/src/app/api/auth/login/route.ts
+++ b/src/app/api/auth/login/route.ts
@@ -2,6 +2,7 @@ import { z } from "zod";
import { LoginGuard } from "@/server/auth";
import { appendAudit } from "@/server/identity/audit-log";
import { signInOwner, type SignInResult } from "@/server/identity/owner";
+import { PASSWORD_SIGN_IN_MAX } from "@/server/identity/password";
import { refusal } from "@/server/identity/refusals";
import { signInRequired } from "@/server/mode";
@@ -11,7 +12,7 @@ import { signInRequired } from "@/server/mode";
* sign-in stays in memory. Kept at this path so today's page and scripts work unchanged.
*/
-const Body = z.object({ password: z.string().min(1).max(500) });
+const Body = z.object({ password: z.string().min(1).max(PASSWORD_SIGN_IN_MAX) });
declare global {
var __fuobeLoginGuard: LoginGuard | undefined;
diff --git a/src/app/api/auth/password/route.ts b/src/app/api/auth/password/route.ts
index ab6bbbb9..bb6bd631 100644
--- a/src/app/api/auth/password/route.ts
+++ b/src/app/api/auth/password/route.ts
@@ -1,6 +1,7 @@
import { connection } from "next/server";
import { z } from "zod";
import { checkOwnerPassword, changeOwnerPassword, ownerPasswordStatus, signInOwner } from "@/server/identity/owner";
+import { PASSWORD_SIGN_IN_MAX } from "@/server/identity/password";
import { resolvePrincipal } from "@/server/identity/principal";
import { listTokens } from "@/server/identity/tokens";
import { signInRequired } from "@/server/mode";
@@ -11,7 +12,7 @@ import { signInRequired } from "@/server/mode";
* every other browser out and keeps this one signed in.
*/
-const Body = z.object({ current: z.string().max(500).optional(), password: z.string().max(500).nullable() });
+const Body = z.object({ current: z.string().max(PASSWORD_SIGN_IN_MAX).optional(), password: z.string().max(PASSWORD_SIGN_IN_MAX).nullable() });
async function status(request: Request) {
const { actor } = await resolvePrincipal(request);
diff --git a/src/components/security-settings.tsx b/src/components/security-settings.tsx
index d74a722d..589d999a 100644
--- a/src/components/security-settings.tsx
+++ b/src/components/security-settings.tsx
@@ -19,7 +19,10 @@ interface TokenInfo {
}
interface AuthStatus {
enabled: boolean;
+ /** FUOBE_PASSWORD sets the password. */
fromEnv: boolean;
+ /** FUOBE_SIGNIN pins sign-in on or off (null when unset). */
+ signinFromEnv?: boolean | null;
tokens: TokenInfo[];
}
@@ -77,7 +80,7 @@ function PasswordForm({ status, onDone }: { status: AuthStatus; onDone: () => vo
{busy && <Loader2 className="animate-spin" />}
{status.enabled ? "Change password" : "Require a password"}
</Button>
- {status.enabled && (
+ {status.enabled && status.signinFromEnv !== true && (
<Button size="sm" variant="ghost" className="text-destructive" disabled={busy || !current} onClick={() => void run(null)}>
Remove password
</Button>
@@ -204,7 +207,10 @@ export function SecuritySettings() {
{s.enabled ? (
<div className="flex items-start gap-2.5 rounded-xl bg-brand-faint px-3 py-2.5 text-[13px]">
<ShieldCheck className="mt-0.5 size-4 shrink-0 text-brand-text" />
- <p className="flex-1">Sign-in is required for every page and API call.{s.fromEnv && " The password is set by FUOBE_PASSWORD on the server."}</p>
+ <p className="flex-1">
+ Sign-in is required for every page and API call.{s.fromEnv && " The password is set by FUOBE_PASSWORD on the server."}
+ {s.signinFromEnv === true && " Set by the server (FUOBE_SIGNIN=on), so the password can be changed but not removed."}
+ </p>
<Button
size="sm"
variant="ghost"
@@ -221,10 +227,14 @@ export function SecuritySettings() {
) : (
<div className="flex items-start gap-2.5 rounded-xl bg-amber-500/10 px-3 py-2.5 text-[13px] text-amber-800 dark:text-amber-300">
<ShieldAlert className="mt-0.5 size-4 shrink-0" />
- <p>No password: anyone who can reach this server can use your keys and GPU. Fine on your own computer — set a password before you open it to a network.</p>
+ <p>
+ {s.signinFromEnv === false
+ ? "Sign-in is off: set by the server (FUOBE_SIGNIN=off). Anyone who can reach this server can use your keys and GPU. Restart without it to require a password."
+ : "No password: anyone who can reach this server can use your keys and GPU. Fine on your own computer — set a password before you open it to a network."}
+ </p>
</div>
)}
- {!s.fromEnv && <PasswordForm status={s} onDone={refresh} />}
+ {!s.fromEnv && s.signinFromEnv !== false && <PasswordForm status={s} onDone={refresh} />}
<Tokens status={s} onChange={refresh} />
</div>
);
diff --git a/src/server/identity/auth.ts b/src/server/identity/auth.ts
index 0da40f46..b573f337 100644
--- a/src/server/identity/auth.ts
+++ b/src/server/identity/auth.ts
@@ -10,7 +10,7 @@ import { hostAllowed, trustedProxies } from "../auth";
import { DATA_DIR, db } from "../db";
import { INSTALL, installMode, installValue, siteUrl } from "../mode";
import { appendAudit } from "./audit-log";
-import { hashPassword, needsRehash, PASSWORD_MAX, PASSWORD_MIN, verifyPassword } from "./password";
+import { hashPassword, needsRehash, PASSWORD_MAX, PASSWORD_MIN, PASSWORD_SIGN_IN_MAX, verifyPassword } from "./password";
import { refusal } from "./refusals";
import { AUTH_TABLES } from "./schema";
import { deriveKey } from "./secret";
@@ -38,7 +38,10 @@ import { deriveKey } from "./secret";
* - Router traffic (/api/identity/*) may reach only the allowlisted endpoints; Fuobe's own auth.api calls pass.
* Sign-up and social sign-in are off the list until the sign-in package adds them with their policy.
* - A new Better Auth user needs a Fuobe intent (claiming the owner, the auth.json import) until the meter
- * package sets accounts.multi_user, so no second account can exist before isolation and limits do.
+ * package sets accounts.multi_user, so no second account can exist before isolation and limits do. Each intent
+ * has its own check: the owner's two refuse once the owner has a live sign-in account.
+ * - Passwords: new ones are 8 to 128 characters on every path; sign-in takes up to 500, so a longer password from
+ * before accounts (or FUOBE_PASSWORD) still works.
*/
declare global {
@@ -104,8 +107,20 @@ export const ROUTER_BLOCKED: PathRule[] = [
export const routerAllows = (p: string): boolean => !ROUTER_BLOCKED.some((r) => matches(r, p)) && ROUTER_ALLOWED.some((r) => matches(r, p));
-/** Why Fuobe is creating a Better Auth user. Packages add theirs (invite, sso, scim, admin). */
-export const CREATE_INTENTS = new Set<string>(["claim-owner", "bootstrap-import"]);
+/**
+ * Why Fuobe is creating a Better Auth user, each with its own check (a refusal code, or null to go ahead). The two
+ * core intents only ever make the owner's sign-in account, so they refuse once the owner has a live one. Packages
+ * add theirs (invite, sso, scim, admin) with registerCreateIntent.
+ */
+export type CreateIntentCheck = () => string | null;
+export const CREATE_INTENTS = new Map<string, CreateIntentCheck>([
+ ["claim-owner", () => (ownerClaimable() ? null : "OWNER_CLAIMED")],
+ ["bootstrap-import", () => (ownerClaimable() ? null : "OWNER_CLAIMED")],
+]);
+
+export function registerCreateIntent(intent: string, check: CreateIntentCheck): void {
+ CREATE_INTENTS.set(intent, check);
+}
const createIntent = new AsyncLocalStorage<string>();
@@ -142,6 +157,20 @@ export const SESSION_AFTER: SessionAfter[] = [
(p, s) => appendAudit({ action: "auth.sign_in", actorId: p.id, via: "session", targetKind: "session", targetId: s.id, ip: s.ipAddress, userAgent: s.userAgent }),
];
+/**
+ * Endpoints that set a new password, and the body field that holds it. New passwords keep the 8 to 128 rule
+ * (§7.2) on every path, Fuobe's own calls included; Better Auth's own limit is the higher sign-in one, so passwords
+ * from before accounts (and FUOBE_PASSWORD) still sign in. Packages that load a plugin with its own path add it.
+ */
+export const NEW_PASSWORD_FIELDS: Record<string, string> = {
+ "/sign-up/email": "password",
+ "/reset-password": "newPassword",
+ "/change-password": "newPassword",
+ "/set-password": "newPassword",
+ "/admin/create-user": "password",
+ "/admin/set-user-password": "newPassword",
+};
+
/** Better Auth cookies Fuobe renames (and makes __Host- on https). Plugins add theirs (two_factor, passkey…). */
export const AUTH_COOKIES = ["session_token", "session_data", "dont_remember", "account_data"];
@@ -171,6 +200,14 @@ export function ensurePendingPerson(authUserId: string): PersonRow {
return personFor(authUserId)!;
}
+/** Whether the owner can still be given a sign-in account: none linked, or the linked one is gone. */
+export function ownerClaimable(): boolean {
+ const row = db()
+ .prepare(`SELECT u.auth_user_id AS linked, EXISTS (SELECT 1 FROM "${AUTH_TABLES.user}" a WHERE a.id = u.auth_user_id) AS live FROM users u WHERE u.id = 'u_owner'`)
+ .get() as { linked: string | null; live: number } | undefined;
+ return !!row && (!row.linked || !row.live);
+}
+
/** Link a new Better Auth user to the Fuobe person its intent names. */
function linkPerson(authUserId: string, intent: string | null): void {
if (intent === "claim-owner" || intent === "bootstrap-import") {
@@ -275,7 +312,9 @@ export function buildAuthOptions(site: AuthSite) {
emailAndPassword: {
enabled: true,
minPasswordLength: PASSWORD_MIN,
- maxPasswordLength: PASSWORD_MAX,
+ // The sign-in limit, not the new-password one: Better Auth checks it before verifying, and a longer password
+ // from before accounts must still sign in. New passwords meet PASSWORD_MAX in the before hook.
+ maxPasswordLength: PASSWORD_SIGN_IN_MAX,
revokeSessionsOnPasswordReset: true,
password: { hash: hashPassword, verify: verifyPassword },
},
@@ -290,10 +329,14 @@ export function buildAuthOptions(site: AuthSite) {
create: {
before: async () => {
const intent = currentCreateIntent();
- if (installValue(INSTALL.multiUser) === "1") return;
- if (!intent || !CREATE_INTENTS.has(intent)) {
- throw new APIError("FORBIDDEN", { message: "New accounts can't be created on this Fuobe.", code: "SIGN_UP_CLOSED" });
+ const check = intent ? CREATE_INTENTS.get(intent) : undefined;
+ if (check) {
+ const code = check();
+ if (code) throw new APIError("FORBIDDEN", { message: "This Fuobe's owner already has a sign-in account.", code });
+ return;
}
+ if (installValue(INSTALL.multiUser) === "1") return;
+ throw new APIError("FORBIDDEN", { message: "New accounts can't be created on this Fuobe.", code: "SIGN_UP_CLOSED" });
},
after: async (user: { id: string }) => linkPerson(user.id, currentCreateIntent()),
},
@@ -318,8 +361,14 @@ export function buildAuthOptions(site: AuthSite) {
},
},
hooks: {
- // The router allowlist: only browser traffic carries ctx.request; Fuobe's auth.api calls pass.
+ // New passwords stay within 8 to 128 characters; then the router allowlist.
before: createAuthMiddleware(async (ctx) => {
+ const field = NEW_PASSWORD_FIELDS[ctx.path];
+ const next = field && ctx.body && typeof ctx.body === "object" ? (ctx.body as Record<string, unknown>)[field] : undefined;
+ if (typeof next === "string" && next.length > PASSWORD_MAX) {
+ throw new APIError("BAD_REQUEST", { message: `Use at most ${PASSWORD_MAX} characters.`, code: "PASSWORD_TOO_LONG" });
+ }
+ // The router allowlist: only browser traffic carries ctx.request; Fuobe's auth.api calls pass.
if (!ctx.request) return;
if (!routerAllows(ctx.path)) throw new APIError("FORBIDDEN", { message: "That isn't available on this Fuobe.", code: "ENDPOINT_BLOCKED" });
if (ctx.path === "/update-user" && ctx.body && typeof ctx.body === "object") {
diff --git a/src/server/identity/bootstrap.ts b/src/server/identity/bootstrap.ts
index 68afc966..524ae092 100644
--- a/src/server/identity/bootstrap.ts
+++ b/src/server/identity/bootstrap.ts
@@ -5,10 +5,11 @@ import Database from "better-sqlite3";
import { readLegacyAuth } from "../auth";
import { snapshotDatabase, type Snapshot } from "../backup/snapshot";
import { DATA_DIR, db, IDENTITY_MIGRATION } from "../db";
-import { envMode, envOwnerPassword, INSTALL, installValue, legacyPasswordSet, setInstallValue } from "../mode";
+import { envMode, envOwnerPassword, envOwnerPasswordName, envSignIn, INSTALL, installValue, legacyPasswordSet, setInstallValue } from "../mode";
import * as ops from "./admin-ops";
import { appendAudit } from "./audit-log";
import { ensureOwnerAuthUser, ownerAuthUserId } from "./owner";
+import { PASSWORD_SIGN_IN_MAX } from "./password";
import { resetSecretCache, secretFingerprint } from "./secret";
import { importLegacyToken } from "./tokens";
@@ -27,7 +28,11 @@ import { importLegacyToken } from "./tokens";
* The file stays in place, unread, for one release as a rollback aid. Old session cookies are not accepted:
* password installs sign in once more.
* 5. FUOBE_PASSWORD (or FUOBE_OWNER_PASSWORD), at every start: the owner's break-glass password. A changed value
- * replaces the old one and signs every browser out.
+ * replaces the old one and signs every browser out. It stays the owner's password after the variable is unset
+ * (sign-in stays on), and can then be changed or removed in Settings → Security.
+ * 6. FUOBE_SIGNIN=on needs a password to sign in with: without one the server doesn't start.
+ *
+ * A bad value stops the server with one line naming it (StartupError), never a stack trace.
*/
export class StartupError extends Error {}
@@ -69,9 +74,23 @@ function checkModeEnv(): void {
}
}
+/** FUOBE_PASSWORD must fit the sign-in form (it did before accounts too), or nobody could ever type it in. */
+function checkEnvPassword(): void {
+ const pw = envOwnerPassword();
+ if (pw.length > PASSWORD_SIGN_IN_MAX) {
+ throw new StartupError(`${envOwnerPasswordName()} is longer than ${PASSWORD_SIGN_IN_MAX} characters, so it could never be typed in to sign in. Use a shorter one.`);
+ }
+}
+
function checkSecret(): void {
resetSecretCache();
- const fingerprint = secretFingerprint();
+ let fingerprint: string;
+ try {
+ fingerprint = secretFingerprint();
+ } catch (e) {
+ // A FUOBE_SECRET that is too short, or a damaged data/secret.key: one line naming it.
+ throw new StartupError((e as Error).message);
+ }
const stored = installValue(INSTALL.secretCheck);
if (stored === fingerprint) return;
if (stored && process.env.FUOBE_ACCEPT_NEW_SECRET !== "1") {
@@ -90,6 +109,7 @@ function checkSecret(): void {
/** Run the bootstrap. Throws StartupError when the server must not start. */
export async function bootstrapIdentity(): Promise<BootstrapReport> {
checkModeEnv();
+ checkEnvPassword();
const snapshot = preAccountsSnapshot();
db();
checkSecret();
@@ -130,6 +150,14 @@ export async function bootstrapIdentity(): Promise<BootstrapReport> {
setInstallValue(INSTALL.signin, "on");
}
+ // FUOBE_SIGNIN=on with nothing to sign in with would turn every visitor away, the owner too.
+ if (envSignIn() === true) {
+ const id = ownerAuthUserId();
+ if (!id || !(await ops.hasPassword(id))) {
+ throw new StartupError("FUOBE_SIGNIN=on needs the owner's password: set FUOBE_PASSWORD as well, or set a password in Settings → Security before turning FUOBE_SIGNIN on.");
+ }
+ }
+
report.signin = installValue(INSTALL.signin) === "on" ? "on" : "off";
return report;
}
@@ -140,6 +168,9 @@ export async function startIdentity(): Promise<void> {
const report = await bootstrapIdentity();
if (report.snapshot) console.log(`Fuobe saved a copy of the database before accounts: ${report.snapshot.db}`);
if (report.importedPassword) console.log("Fuobe moved the password to accounts: sign in once more in each browser.");
+ if (report.syncedEnvPassword) {
+ console.log(`Fuobe set the owner's password from ${envOwnerPasswordName()}. It stays the password if you unset the variable: change or remove it in Settings → Security.`);
+ }
} catch (e) {
console.error(e instanceof StartupError ? `Fuobe can't start: ${e.message}` : e);
process.exit(1);
diff --git a/src/server/identity/owner.ts b/src/server/identity/owner.ts
index 104bb915..77ed68e7 100644
--- a/src/server/identity/owner.ts
+++ b/src/server/identity/owner.ts
@@ -2,7 +2,7 @@ import "server-only";
import { isAPIError } from "better-auth/api";
import { REFUSAL_COPY } from "@/lib/sign-in-refusals";
import { db } from "../db";
-import { bumpIdentityConfig, envOwnerPassword, INSTALL, setInstallValue } from "../mode";
+import { bumpIdentityConfig, envOwnerPassword, envOwnerPasswordName, envSignIn, INSTALL, setInstallValue } from "../mode";
import * as ops from "./admin-ops";
import { appendAudit } from "./audit-log";
import { getAuth } from "./auth";
@@ -75,9 +75,12 @@ export async function signOut(headers: Headers): Promise<string[]> {
}
}
-/** Settings → Security's view: whether a password is required, and whether the server sets it. */
-export function ownerPasswordStatus(): { fromEnv: boolean } {
- return { fromEnv: !!envOwnerPassword() };
+/**
+ * Settings → Security's view of what the server sets: the password (FUOBE_PASSWORD) and whether sign-in is on
+ * (FUOBE_SIGNIN, null when unset). Either one locks its control ("Set by the server", §7.9).
+ */
+export function ownerPasswordStatus(): { fromEnv: boolean; signinFromEnv: boolean | null } {
+ return { fromEnv: !!envOwnerPassword(), signinFromEnv: envSignIn() };
}
/**
@@ -85,7 +88,12 @@ export function ownerPasswordStatus(): { fromEnv: boolean } {
* in. Setting one turns sign-in on; removing it turns sign-in off.
*/
export async function changeOwnerPassword(next: string | null, by: ops.By): Promise<void> {
- if (envOwnerPassword()) throw new Error("The password is set by FUOBE_PASSWORD on the server");
+ if (envOwnerPassword()) throw new Error(`The password is set by ${envOwnerPasswordName()} on the server`);
+ // FUOBE_SIGNIN wins over the stored switch: refuse what it would silently undo (an install nobody can sign in to,
+ // or "sign-in is now required" on one that stays open).
+ const pinned = envSignIn();
+ if (pinned === true && next === null) throw new Error("Sign-in is required by FUOBE_SIGNIN on the server, so the password can't be removed. Change it instead.");
+ if (pinned === false && next !== null) throw new Error("Sign-in is turned off by FUOBE_SIGNIN on the server. Restart without it to require a password.");
if (next !== null) {
const problem = passwordProblem(next);
if (problem) throw new Error(problem);
diff --git a/src/server/identity/password.ts b/src/server/identity/password.ts
index 1affb92e..cdd6bcb0 100644
--- a/src/server/identity/password.ts
+++ b/src/server/identity/password.ts
@@ -14,7 +14,14 @@ import { promisify } from "node:util";
const scrypt = promisify(crypto.scrypt) as (pw: crypto.BinaryLike, salt: crypto.BinaryLike, len: number, opts: crypto.ScryptOptions) => Promise<Buffer>;
export const PASSWORD_MIN = 8;
+/** The longest new password (§7.2): Settings, sign-up, resets and changes. */
export const PASSWORD_MAX = 128;
+/**
+ * The longest password that may still sign in: what Fuobe accepted before accounts (Settings and the sign-in form
+ * took up to 500 characters, FUOBE_PASSWORD had to fit the same form). Imported and FUOBE_PASSWORD passwords up to
+ * this length keep working; the bootstrap refuses a longer FUOBE_PASSWORD with one line.
+ */
+export const PASSWORD_SIGN_IN_MAX = 500;
const V2 = { N: 2 ** 15, r: 8, p: 3, keyLength: 64 } as const;
const LEGACY = { N: 2 ** 14, r: 8, p: 1, keyLength: 32 } as const;
diff --git a/src/server/mode.ts b/src/server/mode.ts
index e3bf5f2c..cd8e43eb 100644
--- a/src/server/mode.ts
+++ b/src/server/mode.ts
@@ -77,6 +77,11 @@ export function envOwnerPassword(): string {
return process.env.FUOBE_OWNER_PASSWORD || process.env.FUOBE_PASSWORD || "";
}
+/** Which variable the break-glass password came from, for messages. */
+export function envOwnerPasswordName(): "FUOBE_OWNER_PASSWORD" | "FUOBE_PASSWORD" {
+ return process.env.FUOBE_OWNER_PASSWORD ? "FUOBE_OWNER_PASSWORD" : "FUOBE_PASSWORD";
+}
+
/** A password in the pre-accounts auth.json: the install had sign-in before this build. */
export function legacyPasswordSet(): boolean {
try {
diff --git a/tests/auth.test.ts b/tests/auth.test.ts
index 65872c69..87789a55 100644
--- a/tests/auth.test.ts
+++ b/tests/auth.test.ts
@@ -6,7 +6,10 @@ import crypto from "node:crypto";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
-import { afterAll, describe, expect, it } from "vitest";
+import { afterAll, describe, expect, it, vi } from "vitest";
+
+// Real scrypt hashes (N=2^15) and fresh module loads per case: slow under a parallel run.
+vi.setConfig({ testTimeout: 60_000 });
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-auth-"));
process.env.FUOBE_DATA_DIR = dir;
diff --git a/tests/identity-better-auth.test.ts b/tests/identity-better-auth.test.ts
index 531cacad..4085aa07 100644
--- a/tests/identity-better-auth.test.ts
+++ b/tests/identity-better-auth.test.ts
@@ -8,7 +8,10 @@ import { execFileSync } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
-import { afterAll, describe, expect, it } from "vitest";
+import { afterAll, describe, expect, it, vi } from "vitest";
+
+// Real scrypt hashes (N=2^15) and fresh module loads per case: slow under a parallel run.
+vi.setConfig({ testTimeout: 60_000 });
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-ba-"));
process.env.FUOBE_DATA_DIR = dir;
@@ -113,16 +116,57 @@ describe("the router allowlist (§7.1)", () => {
it("carries Fuobe's request scope into database hooks: a create under an intent goes through, and its session check still runs", async () => {
const before = authUsers();
- // The owner is already linked, so the new user gets a pending person of its own (never active), and the
- // sign-in that sign-up attempts is refused with that code. Better Auth's transactions are off: the user stays.
- await expect(
- identity.withCreateIntent("claim-owner", () => identity.getAuth().api.signUpEmail({ body: { email: "[email protected]", password: "another long password", name: "Scope" } })),
- ).rejects.toMatchObject({ body: { code: "ACCOUNT_PENDING" } });
+ // A package's own intent (as invites will register one). Its user isn't the owner, so it gets a pending person
+ // of its own (never active), and the sign-in that sign-up attempts is refused with that code. Better Auth's
+ // transactions are off: the user stays.
+ identity.registerCreateIntent("test-scope", () => null);
+ try {
+ await expect(
+ identity.withCreateIntent("test-scope", () => identity.getAuth().api.signUpEmail({ body: { email: "[email protected]", password: "another long password", name: "Scope" } })),
+ ).rejects.toMatchObject({ body: { code: "ACCOUNT_PENDING" } });
+ } finally {
+ identity.CREATE_INTENTS.delete("test-scope");
+ }
expect(authUsers()).toBe(before + 1);
const person = db().prepare("SELECT u.status, u.source FROM users u JOIN auth_user a ON a.id = u.auth_user_id WHERE a.email = ?").get("[email protected]");
expect(person).toEqual({ status: "pending", source: "unknown" });
});
+ it("refuses the owner's intents once the owner has a live sign-in account, so they never make a second user", async () => {
+ expect(identity.ownerClaimable()).toBe(false);
+ const before = authUsers();
+ for (const intent of ["claim-owner", "bootstrap-import"]) {
+ await expect(
+ identity.withCreateIntent(intent, () => identity.getAuth().api.signUpEmail({ body: { email: `${intent}@example.com`, password: "another long password", name: "Again" } })),
+ intent,
+ ).rejects.toMatchObject({ body: { code: "OWNER_CLAIMED" } });
+ }
+ // multi_user (the meter package) doesn't loosen them either.
+ db().prepare("INSERT INTO settings (key, value) VALUES ('accounts.multi_user', '1')").run();
+ try {
+ await expect(
+ identity.withCreateIntent("claim-owner", () => identity.getAuth().api.signUpEmail({ body: { email: "[email protected]", password: "another long password", name: "Again" } })),
+ ).rejects.toMatchObject({ body: { code: "OWNER_CLAIMED" } });
+ } finally {
+ db().prepare("DELETE FROM settings WHERE key = 'accounts.multi_user'").run();
+ }
+ expect(authUsers()).toBe(before);
+ });
+
+ it("keeps new passwords to 128 characters on every path, while Better Auth's own limit is the sign-in one (500)", async () => {
+ identity.registerCreateIntent("test-long", () => null);
+ try {
+ await expect(
+ identity.withCreateIntent("test-long", () => identity.getAuth().api.signUpEmail({ body: { email: "[email protected]", password: "x".repeat(129), name: "Long" } })),
+ ).rejects.toMatchObject({ body: { code: "PASSWORD_TOO_LONG", message: "Use at most 128 characters." } });
+ } finally {
+ identity.CREATE_INTENTS.delete("test-long");
+ }
+ expect(db().prepare("SELECT 1 FROM auth_user WHERE email = '[email protected]'").get()).toBeUndefined();
+ expect((await identity.getAuth().$context).password.config.maxPasswordLength).toBe(500);
+ for (const p of Object.keys(identity.NEW_PASSWORD_FIELDS)) expect(p.startsWith("/"), p).toBe(true);
+ });
+
it("refuses a session for a pending person with its code", async () => {
await expect(identity.getAuth().api.signInEmail({ body: { email: "[email protected]", password: "another long password" } })).rejects.toMatchObject({
body: { code: "ACCOUNT_PENDING" },
diff --git a/tests/identity-bootstrap.test.ts b/tests/identity-bootstrap.test.ts
index 3f4c1e86..3aa91b8a 100644
--- a/tests/identity-bootstrap.test.ts
+++ b/tests/identity-bootstrap.test.ts
@@ -11,6 +11,9 @@ import Database from "better-sqlite3";
import { NextRequest } from "next/server";
import { afterAll, afterEach, describe, expect, it, vi } from "vitest";
+// Real scrypt hashes (N=2^15) and fresh module loads per case: slow under a parallel run.
+vi.setConfig({ testTimeout: 60_000 });
+
const ENV = ["FUOBE_PASSWORD", "FUOBE_OWNER_PASSWORD", "FUOBE_SIGNIN", "FUOBE_MODE", "FUOBE_SECRET", "FUOBE_ACCEPT_NEW_SECRET", "FUOBE_DEV_PLATFORM", "FUOBE_SITE_URL", "FUOBE_TRUST_PROXY", "FUOBE_TRUSTED_PROXIES"];
for (const k of ENV) delete process.env[k];
const dirs: string[] = [];
@@ -50,6 +53,7 @@ async function load(dir: string) {
principal: await import("@/server/identity/principal"),
proxy: (await import("@/proxy")).proxy,
login: await import("@/app/api/auth/login/route"),
+ password: await import("@/app/api/auth/password/route"),
};
}
@@ -92,6 +96,16 @@ function writeAuthJson(dir: string, opts: { password?: string; tokens?: boolean
return data;
}
+const BY = { actorId: "u_owner", via: "local" };
+/** A password of exactly `n` characters. */
+const longPassword = (n: number) => "correct horse battery staple ".repeat(Math.ceil(n / 29)).slice(0, n);
+/** Set-Cookie lines → the Cookie header a browser would send next. */
+const cookieOf = (setCookies: string[]) =>
+ setCookies
+ .filter((c) => !/max-age=0/i.test(c))
+ .map((c) => c.split(";")[0])
+ .join("; ");
+
const req = (url: string, headers: Record<string, string> = {}) => new NextRequest(url, { headers: { host: new URL(url).host, ...headers } });
const loginPost = (password: string) =>
new Request("http://localhost:3000/api/auth/login", { method: "POST", headers: { "content-type": "application/json", host: "localhost:3000", origin: "http://localhost:3000" }, body: JSON.stringify({ password }) });
@@ -246,10 +260,11 @@ describe("the secret key's fingerprint (§7.15)", () => {
expect((await boot(dir)).report.signin).toBe("on");
});
- it("refuses a FUOBE_SECRET that is too short", async () => {
+ it("refuses a FUOBE_SECRET that is too short, as a start-up error", async () => {
process.env.FUOBE_SECRET = "short";
const m = await load(newDir());
await expect(m.bootstrap.bootstrapIdentity()).rejects.toThrow(/FUOBE_SECRET is too short/);
+ await expect(m.bootstrap.bootstrapIdentity()).rejects.toBeInstanceOf(m.bootstrap.StartupError);
});
});
@@ -265,3 +280,152 @@ describe("FUOBE_MODE", () => {
await expect((await load(newDir())).bootstrap.bootstrapIdentity()).rejects.toThrow(/isn't a mode/);
});
});
+
+describe("long passwords (they signed in before accounts, so they still do)", () => {
+ it("an auth.json password over 128 characters signs in, and is rewritten", async () => {
+ const dir = newDir();
+ await preAccountsDb(dir);
+ const pw = longPassword(150);
+ writeAuthJson(dir, { password: pw });
+ const m = await boot(dir);
+ expect(m.report).toMatchObject({ importedPassword: true, signin: "on" });
+ expect((await m.login.POST(loginPost(pw))).status).toBe(200);
+ const id = m.owner.ownerAuthUserId()!;
+ expect(await m.ops.passwordNeedsRehash(id)).toBe(false);
+ expect((await m.owner.signInOwner(pw, new Headers())).ok).toBe(true);
+ });
+
+ it("FUOBE_PASSWORD up to 500 characters signs in; a longer one stops the start with one line", async () => {
+ process.env.FUOBE_PASSWORD = longPassword(129);
+ const m = await boot(newDir());
+ expect(m.report).toMatchObject({ syncedEnvPassword: true, signin: "on" });
+ expect((await m.login.POST(loginPost(longPassword(129)))).status).toBe(200);
+
+ process.env.FUOBE_PASSWORD = longPassword(500);
+ expect((await (await boot(newDir())).owner.signInOwner(longPassword(500), new Headers())).ok).toBe(true);
+
+ // Nor was there a shortest one: a short FUOBE_PASSWORD still signs in (Better Auth checks no minimum at sign-in).
+ process.env.FUOBE_PASSWORD = "pw1";
+ expect((await (await boot(newDir())).login.POST(loginPost("pw1"))).status).toBe(200);
+
+ process.env.FUOBE_PASSWORD = longPassword(501);
+ const tooLong = await load(newDir());
+ await expect(tooLong.bootstrap.bootstrapIdentity()).rejects.toThrow(/^FUOBE_PASSWORD is longer than 500 characters/);
+ await expect(tooLong.bootstrap.bootstrapIdentity()).rejects.toBeInstanceOf(tooLong.bootstrap.StartupError);
+ delete process.env.FUOBE_PASSWORD;
+ process.env.FUOBE_OWNER_PASSWORD = longPassword(501);
+ await expect((await load(newDir())).bootstrap.bootstrapIdentity()).rejects.toThrow(/^FUOBE_OWNER_PASSWORD is longer/);
+ });
+
+ it("a new password still stops at 128 characters", async () => {
+ const m = await boot(newDir());
+ await expect(m.owner.changeOwnerPassword(longPassword(129), BY)).rejects.toThrow(/at most 128/);
+ await m.owner.changeOwnerPassword(longPassword(128), BY);
+ expect(await m.owner.checkOwnerPassword(longPassword(128))).toBe(true);
+ });
+});
+
+describe("FUOBE_SIGNIN locks the switch (§7.9)", () => {
+ it("on, with no password to sign in with, stops the start with one line", async () => {
+ process.env.FUOBE_SIGNIN = "on";
+ const m = await load(newDir());
+ await expect(m.bootstrap.bootstrapIdentity()).rejects.toThrow(/^FUOBE_SIGNIN=on needs the owner's password/);
+ await expect(m.bootstrap.bootstrapIdentity()).rejects.toBeInstanceOf(m.bootstrap.StartupError);
+ // With FUOBE_PASSWORD (or an auth.json password) it starts.
+ process.env.FUOBE_PASSWORD = "break glass pw";
+ expect((await boot(newDir())).report.signin).toBe("on");
+ delete process.env.FUOBE_PASSWORD;
+ const dir = newDir();
+ await preAccountsDb(dir);
+ writeAuthJson(dir, { password: "the old password" });
+ expect((await boot(dir)).report.signin).toBe("on");
+ });
+
+ it("on: the Settings password can be changed but not removed (no install nobody can sign in to)", async () => {
+ const dir = newDir();
+ await (await boot(dir)).owner.changeOwnerPassword("settings password", BY);
+ process.env.FUOBE_SIGNIN = "on";
+ const m = await boot(dir);
+ expect(m.owner.ownerPasswordStatus()).toEqual({ fromEnv: false, signinFromEnv: true });
+ await expect(m.owner.changeOwnerPassword(null, BY)).rejects.toThrow(/FUOBE_SIGNIN/);
+ expect(m.mode.signInRequired()).toBe(true);
+ expect(await m.owner.checkOwnerPassword("settings password")).toBe(true);
+
+ // As Settings → Security sends it, from the signed-in browser: refused, and the password still works.
+ const signedIn = await m.owner.signInOwner("settings password", new Headers());
+ expect(signedIn.ok).toBe(true);
+ const cookie = cookieOf(signedIn.ok ? signedIn.setCookies : []);
+ const remove = await m.password.POST(
+ new Request("http://localhost:3000/api/auth/password", {
+ method: "POST",
+ headers: { "content-type": "application/json", host: "localhost:3000", origin: "http://localhost:3000", cookie },
+ body: JSON.stringify({ current: "settings password", password: null }),
+ }),
+ );
+ expect(remove.status).toBe(400);
+ expect(((await remove.json()) as { error: string }).error).toMatch(/FUOBE_SIGNIN/);
+ expect((await m.login.POST(loginPost("settings password"))).status).toBe(200);
+
+ // Changing it still works.
+ await m.owner.changeOwnerPassword("another settings pw", BY);
+ expect(await m.owner.checkOwnerPassword("another settings pw")).toBe(true);
+ });
+
+ it("off: the install stays open, and Settings can't claim to require a password", async () => {
+ process.env.FUOBE_SIGNIN = "off";
+ const m = await boot(newDir());
+ expect(m.mode.signInRequired()).toBe(false);
+ expect(m.owner.ownerPasswordStatus()).toEqual({ fromEnv: false, signinFromEnv: false });
+ await expect(m.owner.changeOwnerPassword("a new password", BY)).rejects.toThrow(/FUOBE_SIGNIN/);
+ expect(m.owner.ownerAuthUserId()).toBeNull();
+ expect(m.mode.signInRequired()).toBe(false);
+ });
+});
+
+describe("FUOBE_PASSWORD after it is unset", () => {
+ it("stays the owner's password with sign-in on, and Settings can then change or remove it", async () => {
+ const dir = newDir();
+ process.env.FUOBE_PASSWORD = "temporary env pw";
+ await boot(dir);
+ delete process.env.FUOBE_PASSWORD;
+ const m = await boot(dir);
+ expect(m.report).toMatchObject({ syncedEnvPassword: false, signin: "on" });
+ expect(await m.owner.checkOwnerPassword("temporary env pw")).toBe(true);
+ expect(m.owner.ownerPasswordStatus().fromEnv).toBe(false);
+ await m.owner.changeOwnerPassword(null, BY);
+ expect(m.mode.signInRequired()).toBe(false);
+ });
+});
+
+describe("start-up errors", () => {
+ it("are one line naming the problem, never a stack trace", async () => {
+ const exit = vi.spyOn(process, "exit").mockImplementation((() => undefined) as never);
+ const err = vi.spyOn(console, "error").mockImplementation(() => {});
+ try {
+ process.env.FUOBE_SECRET = "short";
+ await (await load(newDir())).bootstrap.startIdentity();
+ delete process.env.FUOBE_SECRET;
+ const damaged = newDir();
+ fs.writeFileSync(path.join(damaged, "secret.key"), Buffer.alloc(10), { mode: 0o600 });
+ await (await load(damaged)).bootstrap.startIdentity();
+ process.env.FUOBE_SIGNIN = "on";
+ await (await load(newDir())).bootstrap.startIdentity();
+
+ expect(exit.mock.calls).toEqual([[1], [1], [1]]);
+ expect(err.mock.calls.map((c) => c.length)).toEqual([1, 1, 1]);
+ const lines = err.mock.calls.map((c) => c[0] as unknown);
+ for (const line of lines) {
+ expect(typeof line).toBe("string");
+ expect(line as string).toMatch(/^Fuobe can't start: /);
+ // No stack trace: a single line.
+ expect(line as string).not.toMatch(/\n/);
+ }
+ expect(lines[0]).toMatch(/FUOBE_SECRET is too short/);
+ expect(lines[1]).toMatch(/secret\.key is damaged/);
+ expect(lines[2]).toMatch(/FUOBE_SIGNIN=on needs/);
+ } finally {
+ exit.mockRestore();
+ err.mockRestore();
+ }
+ });
+});
diff --git a/tests/identity-load.test.ts b/tests/identity-load.test.ts
index 500beedd..6265d0d2 100644
--- a/tests/identity-load.test.ts
+++ b/tests/identity-load.test.ts
@@ -7,7 +7,10 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { monitorEventLoopDelay } from "node:perf_hooks";
-import { afterAll, describe, expect, it } from "vitest";
+import { afterAll, describe, expect, it, vi } from "vitest";
+
+// Real scrypt hashes (N=2^15) and fresh module loads per case: slow under a parallel run.
+vi.setConfig({ testTimeout: 60_000 });
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-load-"));
process.env.FUOBE_DATA_DIR = dir;
diff --git a/tests/identity-proxy.test.ts b/tests/identity-proxy.test.ts
index aa14dda3..bf517069 100644
--- a/tests/identity-proxy.test.ts
+++ b/tests/identity-proxy.test.ts
@@ -9,6 +9,9 @@ import path from "node:path";
import { NextRequest } from "next/server";
import { afterAll, describe, expect, it, vi } from "vitest";
+// Real scrypt hashes (N=2^15) and fresh module loads per case: slow under a parallel run.
+vi.setConfig({ testTimeout: 60_000 });
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-proxy-"));
process.env.FUOBE_DATA_DIR = dir;
for (const k of ["FUOBE_PASSWORD", "FUOBE_OWNER_PASSWORD", "FUOBE_SIGNIN", "FUOBE_MODE", "FUOBE_SECRET", "FUOBE_TRUST_PROXY", "FUOBE_TRUSTED_PROXIES", "FUOBE_SITE_URL"]) delete process.env[k];
diff --git a/tests/identity-snapshot.test.ts b/tests/identity-snapshot.test.ts
index abd4d982..c04ad877 100644
--- a/tests/identity-snapshot.test.ts
+++ b/tests/identity-snapshot.test.ts
@@ -5,7 +5,10 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import Database from "better-sqlite3";
-import { afterAll, describe, expect, it } from "vitest";
+import { afterAll, describe, expect, it, vi } from "vitest";
+
+// Real scrypt hashes (N=2^15) and fresh module loads per case: slow under a parallel run.
+vi.setConfig({ testTimeout: 60_000 });
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-snap-"));
process.env.FUOBE_DATA_DIR = dir;