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.

Access protection: optional password sign-in and API tokens

Claudebeb3a5645a83
diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.ts
new file mode 100644
index 00000000..fd7ca6dd
--- /dev/null
+++ b/src/app/api/auth/login/route.ts
@@ -0,0 +1,29 @@
+import { cookies } from "next/headers";
+import { z } from "zod";
+import { authEnabled, checkPassword, createSession, SESSION_COOKIE } from "@/server/auth";
+
+const Body = z.object({ password: z.string().min(1).max(500) });
+const failures = new Map<string, { n: number; until: number }>();
+
+export async function POST(request: Request) {
+ if (!authEnabled()) return Response.json({ ok: true });
+ const ip = request.headers.get("x-forwarded-for")?.split(",")[0].trim() || "local";
+ const f = failures.get(ip);
+ if (f && f.until > Date.now()) return Response.json({ error: "Too many attempts. Wait a minute and try again." }, { status: 429 });
+ const parsed = Body.safeParse(await request.json().catch(() => null));
+ if (!parsed.success || !checkPassword(parsed.data.password)) {
+ const n = (f?.n ?? 0) + 1;
+ failures.set(ip, { n, until: n >= 5 ? Date.now() + 60_000 : 0 });
+ return Response.json({ error: "Wrong password" }, { status: 401 });
+ }
+ failures.delete(ip);
+ const s = createSession();
+ (await cookies()).set(SESSION_COOKIE, s.value, {
+ httpOnly: true,
+ sameSite: "lax",
+ secure: new URL(request.url).protocol === "https:",
+ path: "/",
+ maxAge: s.maxAge,
+ });
+ return Response.json({ ok: true });
+}
diff --git a/src/app/api/auth/logout/route.ts b/src/app/api/auth/logout/route.ts
new file mode 100644
index 00000000..240babb1
--- /dev/null
+++ b/src/app/api/auth/logout/route.ts
@@ -0,0 +1,7 @@
+import { cookies } from "next/headers";
+import { SESSION_COOKIE } from "@/server/auth";
+
+export async function POST() {
+ (await cookies()).delete(SESSION_COOKIE);
+ return Response.json({ ok: true });
+}
diff --git a/src/app/api/auth/password/route.ts b/src/app/api/auth/password/route.ts
new file mode 100644
index 00000000..98f33be8
--- /dev/null
+++ b/src/app/api/auth/password/route.ts
@@ -0,0 +1,33 @@
+import { cookies } from "next/headers";
+import { connection } from "next/server";
+import { z } from "zod";
+import { authEnabled, authStatus, checkPassword, createSession, SESSION_COOKIE, setPassword, validSession } from "@/server/auth";
+
+const Body = z.object({ current: z.string().max(500).optional(), password: z.string().max(500).nullable() });
+
+export async function GET() {
+ await connection();
+ return Response.json(authStatus());
+}
+
+/** Set, change or remove the password. Changing it needs the current one; this browser stays signed in. */
+export async function POST(request: Request) {
+ const parsed = Body.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: "Invalid request" }, { status: 400 });
+ const { current, password } = parsed.data;
+ const jar = await cookies();
+ if (authEnabled() && !validSession(jar.get(SESSION_COOKIE)?.value)) return Response.json({ error: "Change the password from a signed-in browser" }, { status: 403 });
+ if (authEnabled() && !checkPassword(current ?? "")) return Response.json({ error: "The current password is wrong" }, { status: 403 });
+ try {
+ setPassword(password);
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: 400 });
+ }
+ if (password) {
+ const s = createSession();
+ jar.set(SESSION_COOKIE, s.value, { httpOnly: true, sameSite: "lax", secure: new URL(request.url).protocol === "https:", path: "/", maxAge: s.maxAge });
+ } else {
+ jar.delete(SESSION_COOKIE);
+ }
+ return Response.json(authStatus());
+}
diff --git a/src/app/api/auth/tokens/route.ts b/src/app/api/auth/tokens/route.ts
new file mode 100644
index 00000000..f7916d18
--- /dev/null
+++ b/src/app/api/auth/tokens/route.ts
@@ -0,0 +1,35 @@
+import { cookies } from "next/headers";
+import { connection } from "next/server";
+import { z } from "zod";
+import { authEnabled, authStatus, createToken, revokeToken, SESSION_COOKIE, validSession } from "@/server/auth";
+
+/** Tokens are managed from a signed-in browser only: a token can't mint or revoke tokens. */
+async function browserOnly(): Promise<Response | null> {
+ if (!authEnabled() || validSession((await cookies()).get(SESSION_COOKIE)?.value)) return null;
+ return Response.json({ error: "Manage API tokens from a signed-in browser" }, { status: 403 });
+}
+
+export async function GET() {
+ await connection();
+ const denied = await browserOnly();
+ if (denied) return denied;
+ return Response.json({ tokens: authStatus().tokens });
+}
+
+/** Create a token; the full value is in this response only. */
+export async function POST(request: Request) {
+ const denied = await browserOnly();
+ if (denied) return denied;
+ const parsed = z.object({ name: z.string().max(60) }).safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: "Name the token" }, { status: 400 });
+ return Response.json(createToken(parsed.data.name), { status: 201 });
+}
+
+export async function DELETE(request: Request) {
+ const denied = await browserOnly();
+ if (denied) return denied;
+ const id = new URL(request.url).searchParams.get("id");
+ if (!id) return Response.json({ error: "Which token?" }, { status: 400 });
+ revokeToken(id);
+ return new Response(null, { status: 204 });
+}
diff --git a/src/app/login/page.tsx b/src/app/login/page.tsx
new file mode 100644
index 00000000..9d5f993c
--- /dev/null
+++ b/src/app/login/page.tsx
@@ -0,0 +1,15 @@
+import type { Metadata } from "next";
+import { Suspense } from "react";
+import { LoginForm } from "@/components/login-form";
+
+export const metadata: Metadata = { title: "Sign in" };
+
+export default function Page() {
+ return (
+ <main className="grid min-h-svh place-items-center bg-sidebar px-4">
+ <Suspense>
+ <LoginForm />
+ </Suspense>
+ </main>
+ );
+}
diff --git a/src/components/login-form.tsx b/src/components/login-form.tsx
new file mode 100644
index 00000000..433a1fc8
--- /dev/null
+++ b/src/components/login-form.tsx
@@ -0,0 +1,56 @@
+"use client";
+
+import { Loader2, Lock } from "lucide-react";
+import { useSearchParams } from "next/navigation";
+import { useState } from "react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+
+export function LoginForm() {
+ const params = useSearchParams();
+ const [password, setPassword] = useState("");
+ const [error, setError] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+ // Only same-site paths: never bounce to another origin after signing in.
+ const next = (() => {
+ const n = params.get("next") ?? "/";
+ return n.startsWith("/") && !n.startsWith("//") ? n : "/";
+ })();
+
+ const submit = async (e: React.FormEvent) => {
+ e.preventDefault();
+ setBusy(true);
+ setError(null);
+ const res = await fetch("/api/auth/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ password }) });
+ if (res.ok) {
+ window.location.assign(next);
+ return;
+ }
+ setError(((await res.json().catch(() => ({}))) as { error?: string }).error ?? "Couldn't sign in");
+ setBusy(false);
+ };
+
+ return (
+ <form onSubmit={submit} className="w-full max-w-sm animate-fade-up rounded-2xl border bg-background p-7 shadow-soft">
+ <div className="mb-5 grid size-11 place-items-center rounded-xl bg-primary text-primary-foreground">
+ <Lock className="size-5" />
+ </div>
+ <h1 className="font-heading text-[28px] leading-tight">Welcome back</h1>
+ <p className="mt-1 text-[13px] text-muted-foreground">This Fuobe studio is password protected.</p>
+ <Input
+ type="password"
+ autoFocus
+ autoComplete="current-password"
+ placeholder="Password"
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ className="mt-5 h-11"
+ aria-invalid={!!error}
+ />
+ {error && <p className="mt-2 text-[13px] text-destructive">{error}</p>}
+ <Button type="submit" className="mt-4 h-11 w-full" disabled={!password || busy}>
+ {busy && <Loader2 className="animate-spin" />} Sign in
+ </Button>
+ </form>
+ );
+}
diff --git a/src/components/security-settings.tsx b/src/components/security-settings.tsx
new file mode 100644
index 00000000..3530d6dc
--- /dev/null
+++ b/src/components/security-settings.tsx
@@ -0,0 +1,202 @@
+"use client";
+
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { Copy, KeyRound, Loader2, LogOut, ShieldAlert, ShieldCheck, Trash2 } from "lucide-react";
+import { useRouter } from "next/navigation";
+import { useId, useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { timeAgo } from "@/lib/format";
+
+interface TokenInfo {
+ id: string;
+ name: string;
+ prefix: string;
+ createdAt: number;
+ lastUsedAt?: number;
+}
+interface AuthStatus {
+ enabled: boolean;
+ fromEnv: boolean;
+ tokens: TokenInfo[];
+}
+
+async function call<T>(url: string, method: string, body?: unknown): Promise<T> {
+ const res = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
+ if (res.status === 204) return undefined as T;
+ const j = (await res.json().catch(() => ({}))) as T & { error?: string };
+ if (!res.ok) throw new Error(j.error ?? `Request failed (${res.status})`);
+ return j;
+}
+
+function PasswordForm({ status, onDone }: { status: AuthStatus; onDone: () => void }) {
+ const [current, setCurrent] = useState("");
+ const [next, setNext] = useState("");
+ const [confirm, setConfirm] = useState("");
+ const [busy, setBusy] = useState(false);
+ const id = useId();
+ const run = async (password: string | null) => {
+ setBusy(true);
+ try {
+ await call("/api/auth/password", "POST", { current: current || undefined, password });
+ toast.success(password === null ? "Password removed — the studio is open again" : status.enabled ? "Password changed" : "Password set — sign-in is now required");
+ setCurrent("");
+ setNext("");
+ setConfirm("");
+ onDone();
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ };
+ const mismatch = confirm.length > 0 && next !== confirm;
+ return (
+ <div className="space-y-3">
+ {status.enabled && (
+ <div className="space-y-1.5">
+ <Label htmlFor={`${id}-current`} className="text-[13px]">Current password</Label>
+ <Input id={`${id}-current`} type="password" autoComplete="current-password" value={current} onChange={(e) => setCurrent(e.target.value)} className="w-72" />
+ </div>
+ )}
+ <div className="grid gap-3 sm:grid-cols-2 sm:w-[36rem]">
+ <div className="space-y-1.5">
+ <Label htmlFor={`${id}-new`} className="text-[13px]">{status.enabled ? "New password" : "Password"}</Label>
+ <Input id={`${id}-new`} type="password" autoComplete="new-password" placeholder="At least 8 characters" value={next} onChange={(e) => setNext(e.target.value)} />
+ </div>
+ <div className="space-y-1.5">
+ <Label htmlFor={`${id}-repeat`} className="text-[13px]">Repeat it</Label>
+ <Input id={`${id}-repeat`} type="password" autoComplete="new-password" value={confirm} onChange={(e) => setConfirm(e.target.value)} aria-invalid={mismatch} />
+ </div>
+ </div>
+ {mismatch && <p className="text-[12px] text-destructive">The passwords don&apos;t match</p>}
+ <div className="flex flex-wrap gap-2">
+ <Button size="sm" disabled={busy || next.length < 8 || next !== confirm || (status.enabled && !current)} onClick={() => void run(next)}>
+ {busy && <Loader2 className="animate-spin" />}
+ {status.enabled ? "Change password" : "Require a password"}
+ </Button>
+ {status.enabled && (
+ <Button size="sm" variant="ghost" className="text-destructive" disabled={busy || !current} onClick={() => void run(null)}>
+ Remove password
+ </Button>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function Tokens({ status, onChange }: { status: AuthStatus; onChange: () => void }) {
+ const [name, setName] = useState("");
+ const [fresh, setFresh] = useState<string | null>(null);
+ const create = async () => {
+ try {
+ const r = await call<{ token: string }>("/api/auth/tokens", "POST", { name });
+ setFresh(r.token);
+ setName("");
+ onChange();
+ } catch (e) {
+ toast.error((e as Error).message);
+ }
+ };
+ return (
+ <div className="space-y-3">
+ <div className="space-y-1">
+ <Label className="text-[13px]">API tokens</Label>
+ <p className="text-[12px] text-muted-foreground">
+ For scripts and agents (the REST API and the MCP endpoint at <code className="font-mono">/api/mcp</code>). Send as <code className="font-mono">Authorization: Bearer fuobe_…</code>. Only needed once a password is set.
+ </p>
+ </div>
+ {fresh && (
+ <div className="rounded-xl border border-primary/40 bg-brand-faint p-3">
+ <p className="text-[12px] font-medium">Copy this token now — it won&apos;t be shown again.</p>
+ <div className="mt-2 flex items-center gap-2">
+ <code className="min-w-0 flex-1 truncate rounded-md bg-background px-2 py-1.5 font-mono text-[12px]">{fresh}</code>
+ <Button
+ size="sm"
+ variant="secondary"
+ onClick={() => {
+ void navigator.clipboard.writeText(fresh);
+ toast("Copied");
+ }}
+ >
+ <Copy /> Copy
+ </Button>
+ </div>
+ </div>
+ )}
+ {status.tokens.length > 0 && (
+ <ul className="divide-y rounded-xl border sm:w-[36rem]">
+ {status.tokens.map((t) => (
+ <li key={t.id} className="flex items-center gap-3 px-3 py-2">
+ <KeyRound className="size-4 text-muted-foreground" />
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-[13px] font-medium">{t.name}</p>
+ <p className="font-mono text-[11px] text-muted-foreground">
+ {t.prefix}… · created {timeAgo(t.createdAt)}
+ {t.lastUsedAt ? ` · used ${timeAgo(t.lastUsedAt)}` : " · never used"}
+ </p>
+ </div>
+ <Button
+ size="icon"
+ variant="ghost"
+ className="size-8 text-muted-foreground hover:text-destructive"
+ aria-label={`Revoke ${t.name}`}
+ onClick={async () => {
+ await call(`/api/auth/tokens?id=${t.id}`, "DELETE").catch((e) => toast.error((e as Error).message));
+ onChange();
+ }}
+ >
+ <Trash2 className="size-3.5" />
+ </Button>
+ </li>
+ ))}
+ </ul>
+ )}
+ <div className="flex gap-2 sm:w-[36rem]">
+ <Input placeholder="Token name, e.g. “Claude Desktop”" value={name} onChange={(e) => setName(e.target.value)} />
+ <Button size="sm" variant="secondary" className="h-9" disabled={!name.trim()} onClick={() => void create()}>
+ Create token
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+export function SecuritySettings() {
+ const qc = useQueryClient();
+ const router = useRouter();
+ const status = useQuery({ queryKey: ["auth"], queryFn: () => call<AuthStatus>("/api/auth/password", "GET") });
+ const refresh = () => void qc.invalidateQueries({ queryKey: ["auth"] });
+ if (!status.data) return <Loader2 className="size-5 animate-spin text-muted-foreground" />;
+ const s = status.data;
+ return (
+ <div className="space-y-6">
+ {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>
+ <Button
+ size="sm"
+ variant="ghost"
+ className="-my-1 h-7"
+ onClick={async () => {
+ await fetch("/api/auth/logout", { method: "POST" });
+ router.replace("/login");
+ }}
+ >
+ <LogOut /> Sign out
+ </Button>
+ </div>
+ ) : (
+ <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>
+ </div>
+ )}
+ {!s.fromEnv && <PasswordForm status={s} onDone={refresh} />}
+ <Tokens status={s} onChange={refresh} />
+ </div>
+ );
+}
diff --git a/src/components/settings-form.tsx b/src/components/settings-form.tsx
index cd276b94..b93df437 100644
--- a/src/components/settings-form.tsx
+++ b/src/components/settings-form.tsx
@@ -9,6 +9,7 @@ import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { cn } from "@/lib/utils";
+import { SecuritySettings } from "@/components/security-settings";
interface PublicSetting {
name: string;
@@ -300,7 +301,7 @@ export function SettingsForm() {
<Section
title="Prompt enhancement"
- description="The Enhance toggle rewrites short ideas into rich prompts. Use Claude, a local Ollama model (fully open source), or the built-in offline rewriter. In Open source only mode, Automatic skips Claude."
+ description="The Enhance toggle rewrites short ideas into rich prompts, and storyboards split stories into frames. Use Claude, a local Ollama model (fully open source), or the built-in offline rewriter. Claude also powers the Assist agent. In Open source only mode, Automatic skips Claude."
>
<div className="space-y-1.5">
<Label className="text-[13px]">Enhancer</Label>
@@ -323,6 +324,14 @@ export function SettingsForm() {
</div>
</Section>
+ <Section
+ id="security"
+ title="Security"
+ description="Protect this studio with a password, and create API tokens for scripts and agents. Off by default for local use."
+ >
+ <SecuritySettings />
+ </Section>
+
<Section title="Demo mode" description="Lets you click through everything without keys or a GPU. Demo runs return clearly-labelled placeholder media and cost nothing.">
<Select value={get("demoMode")?.value || "auto"} onValueChange={set("demoMode")}>
<SelectTrigger className="w-72">
diff --git a/src/proxy.ts b/src/proxy.ts
new file mode 100644
index 00000000..6d6ddc85
--- /dev/null
+++ b/src/proxy.ts
@@ -0,0 +1,23 @@
+import { NextResponse, type NextRequest } from "next/server";
+import { authEnabled, SESSION_COOKIE, validSession, validToken } from "@/server/auth";
+
+/** Paths that work signed out: the login page and its API. */
+const OPEN = new Set(["/login", "/api/auth/login"]);
+
+export function proxy(request: NextRequest) {
+ if (!authEnabled()) return NextResponse.next();
+ const { pathname, search } = request.nextUrl;
+ if (OPEN.has(pathname)) return NextResponse.next();
+ if (validSession(request.cookies.get(SESSION_COOKIE)?.value) || validToken(request.headers.get("authorization"))) return NextResponse.next();
+ if (pathname.startsWith("/api/")) {
+ return NextResponse.json({ error: "Sign in, or send an API token as Authorization: Bearer fuobe_…" }, { status: 401, headers: { "WWW-Authenticate": 'Bearer realm="fuobe"' } });
+ }
+ const login = new URL("/login", request.url);
+ if (pathname !== "/") login.searchParams.set("next", pathname + search);
+ return NextResponse.redirect(login);
+}
+
+export const config = {
+ // Everything except build assets and the public folder's files.
+ matcher: ["/((?!_next/static|_next/image|favicon.ico|samples/|.*\\.svg$).*)"],
+};
diff --git a/src/server/auth.ts b/src/server/auth.ts
new file mode 100644
index 00000000..fe82f2ef
--- /dev/null
+++ b/src/server/auth.ts
@@ -0,0 +1,157 @@
+/**
+ * Access protection. Off until a password is set (Settings → Security, or FUOBE_PASSWORD).
+ * Then every page and API call needs a session cookie (from /login) or an API token
+ * (`Authorization: Bearer fuobe_…`).
+ *
+ * Kept in a small JSON file next to the database, not in SQLite, so the proxy can check
+ * requests with nothing but `fs` and `crypto`.
+ */
+import crypto from "node:crypto";
+import fs from "node:fs";
+import path from "node:path";
+
+const DATA_DIR = path.resolve(/*turbopackIgnore: true*/ process.env.FUOBE_DATA_DIR ?? path.join(process.cwd(), "data"));
+const FILE = path.join(DATA_DIR, "auth.json");
+
+export const SESSION_COOKIE = "fuobe_session";
+const SESSION_DAYS = 30;
+
+export interface ApiToken {
+ id: string;
+ name: string;
+ /** sha256 of the token; the token itself is shown once. */
+ hash: string;
+ prefix: string;
+ createdAt: number;
+ lastUsedAt?: number;
+}
+
+interface AuthFile {
+ /** scrypt hash of the UI-set password ("salt:hash", hex). */
+ password?: string;
+ /** Signs session cookies; replaced when the password changes, which signs everyone out. */
+ secret: string;
+ tokens: ApiToken[];
+}
+
+let cache: { mtime: number; data: AuthFile } | null = null;
+
+function read(): AuthFile {
+ try {
+ const mtime = fs.statSync(FILE).mtimeMs;
+ if (cache?.mtime === mtime) return cache.data;
+ const data = JSON.parse(fs.readFileSync(FILE, "utf8")) as AuthFile;
+ cache = { mtime, data };
+ return data;
+ } catch {
+ return { secret: "", tokens: [] };
+ }
+}
+
+function write(data: AuthFile): void {
+ fs.mkdirSync(DATA_DIR, { recursive: true });
+ const tmp = `${FILE}.${process.pid}.tmp`;
+ fs.writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 0o600 });
+ fs.renameSync(tmp, FILE);
+ cache = null;
+}
+
+function withSecret(data: AuthFile): AuthFile {
+ return data.secret ? data : { ...data, secret: crypto.randomBytes(32).toString("hex") };
+}
+
+const envPassword = () => process.env.FUOBE_PASSWORD || "";
+
+export function authStatus(): { enabled: boolean; fromEnv: boolean; tokens: Omit<ApiToken, "hash">[] } {
+ const d = read();
+ return { enabled: !!(envPassword() || d.password), fromEnv: !!envPassword(), tokens: d.tokens.map(publicToken) };
+}
+
+const publicToken = (t: ApiToken): Omit<ApiToken, "hash"> => ({ id: t.id, name: t.name, prefix: t.prefix, createdAt: t.createdAt, lastUsedAt: t.lastUsedAt });
+
+export const authEnabled = () => !!(envPassword() || read().password);
+
+// ---------------------------------------------------------------------------
+// Passwords
+
+function hashPassword(pw: string): string {
+ const salt = crypto.randomBytes(16);
+ return `${salt.toString("hex")}:${crypto.scryptSync(pw, salt, 32).toString("hex")}`;
+}
+
+const same = (a: Buffer, b: Buffer) => a.length === b.length && crypto.timingSafeEqual(a, b);
+
+export function checkPassword(pw: string): boolean {
+ const env = envPassword();
+ if (env) return same(crypto.createHash("sha256").update(pw).digest(), crypto.createHash("sha256").update(env).digest());
+ const stored = read().password;
+ if (!stored) return false;
+ const [salt, hash] = stored.split(":");
+ return same(crypto.scryptSync(pw, Buffer.from(salt, "hex"), 32), Buffer.from(hash, "hex"));
+}
+
+/** Set, change or (with null) remove the UI password. Signs every browser out. */
+export function setPassword(pw: string | null): void {
+ if (envPassword()) throw new Error("The password is set by FUOBE_PASSWORD on the server");
+ if (pw !== null && pw.length < 8) throw new Error("Use at least 8 characters");
+ const d = read();
+ write({ ...d, password: pw === null ? undefined : hashPassword(pw), secret: crypto.randomBytes(32).toString("hex") });
+}
+
+// ---------------------------------------------------------------------------
+// Sessions
+
+const sign = (secret: string, payload: string) => crypto.createHmac("sha256", secret).update(payload).digest("base64url");
+
+export function createSession(): { value: string; maxAge: number } {
+ let d = read();
+ if (!d.secret) {
+ d = withSecret(d);
+ write(d);
+ }
+ const exp = Date.now() + SESSION_DAYS * 86_400_000;
+ return { value: `${exp}.${sign(d.secret, String(exp))}`, maxAge: SESSION_DAYS * 86_400 };
+}
+
+export function validSession(value: string | undefined): boolean {
+ if (!value) return false;
+ const [exp, mac] = value.split(".");
+ const secret = read().secret;
+ if (!secret || !exp || !mac || Number(exp) < Date.now()) return false;
+ return same(Buffer.from(mac), Buffer.from(sign(secret, exp)));
+}
+
+// ---------------------------------------------------------------------------
+// API tokens
+
+const tokenHash = (t: string) => crypto.createHash("sha256").update(t).digest("hex");
+
+export function createToken(name: string): { token: string; info: Omit<ApiToken, "hash"> } {
+ const token = `fuobe_${crypto.randomBytes(24).toString("base64url")}`;
+ const t: ApiToken = { id: crypto.randomBytes(6).toString("hex"), name: name.trim() || "API token", hash: tokenHash(token), prefix: token.slice(0, 12), createdAt: Date.now() };
+ const d = withSecret(read());
+ write({ ...d, tokens: [...d.tokens, t] });
+ return { token, info: publicToken(t) };
+}
+
+export function revokeToken(id: string): void {
+ const d = read();
+ write({ ...d, tokens: d.tokens.filter((t) => t.id !== id) });
+}
+
+const touched = new Map<string, number>();
+
+export function validToken(header: string | null): boolean {
+ const m = /^Bearer\s+(fuobe_[\w-]+)$/i.exec(header ?? "");
+ if (!m) return false;
+ const h = Buffer.from(tokenHash(m[1]));
+ const d = read();
+ const hit = d.tokens.find((t) => same(Buffer.from(t.hash), h));
+ if (!hit) return false;
+ // Record use at most once an hour per token (avoids a write per request).
+ if (Date.now() - (touched.get(hit.id) ?? 0) > 3_600_000) {
+ touched.set(hit.id, Date.now());
+ write({ ...d, tokens: d.tokens.map((t) => (t.id === hit.id ? { ...t, lastUsedAt: Date.now() } : t)) });
+ }
+ return true;
+}
diff --git a/tests/auth.test.ts b/tests/auth.test.ts
new file mode 100644
index 00000000..13c39f13
--- /dev/null
+++ b/tests/auth.test.ts
@@ -0,0 +1,59 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, describe, expect, it } from "vitest";
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-auth-"));
+process.env.FUOBE_DATA_DIR = dir;
+delete process.env.FUOBE_PASSWORD;
+const auth = await import("@/server/auth");
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+describe("auth", () => {
+ it("is off until a password is set", () => {
+ expect(auth.authEnabled()).toBe(false);
+ expect(auth.checkPassword("anything")).toBe(false);
+ });
+
+ it("hashes the password, checks it and rejects short ones", () => {
+ expect(() => auth.setPassword("short")).toThrow(/8 characters/);
+ auth.setPassword("correct horse");
+ expect(auth.authEnabled()).toBe(true);
+ expect(auth.checkPassword("correct horse")).toBe(true);
+ expect(auth.checkPassword("wrong horse")).toBe(false);
+ expect(fs.readFileSync(path.join(dir, "auth.json"), "utf8")).not.toContain("correct horse");
+ });
+
+ it("signs sessions and signs everyone out when the password changes", () => {
+ const s = auth.createSession();
+ expect(auth.validSession(s.value)).toBe(true);
+ expect(auth.validSession(s.value.replace(/.$/, (c) => (c === "A" ? "B" : "A")))).toBe(false);
+ expect(auth.validSession(`${Date.now() - 1}.${s.value.split(".")[1]}`)).toBe(false);
+ expect(auth.validSession(undefined)).toBe(false);
+ auth.setPassword("another secret");
+ expect(auth.validSession(s.value)).toBe(false);
+ });
+
+ it("issues bearer tokens that can be revoked and stores only their hash", () => {
+ const { token, info } = auth.createToken("CI");
+ expect(token).toMatch(/^fuobe_/);
+ expect(auth.validToken(`Bearer ${token}`)).toBe(true);
+ expect(auth.validToken(`Bearer ${token}x`)).toBe(false);
+ expect(auth.validToken(token)).toBe(false);
+ expect(fs.readFileSync(path.join(dir, "auth.json"), "utf8")).not.toContain(token);
+ expect(auth.authStatus().tokens[0]).toMatchObject({ name: "CI", prefix: token.slice(0, 12) });
+ expect(auth.authStatus().tokens[0]).not.toHaveProperty("hash");
+ auth.revokeToken(info.id);
+ expect(auth.validToken(`Bearer ${token}`)).toBe(false);
+ });
+
+ it("uses FUOBE_PASSWORD when set and refuses UI changes", () => {
+ process.env.FUOBE_PASSWORD = "from the env";
+ expect(auth.checkPassword("from the env")).toBe(true);
+ expect(auth.checkPassword("another secret")).toBe(false);
+ expect(() => auth.setPassword(null)).toThrow(/FUOBE_PASSWORD/);
+ delete process.env.FUOBE_PASSWORD;
+ auth.setPassword(null);
+ expect(auth.authEnabled()).toBe(false);
+ });
+});