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.

Security: sign everyone out from Settings, and no cookie outlives a session

Adarshf3c16f301a7e
diff --git a/docs/SELF-HOSTING.md b/docs/SELF-HOSTING.md
index ddd9591b..ad9067a7 100644
--- a/docs/SELF-HOSTING.md
+++ b/docs/SELF-HOSTING.md
@@ -70,6 +70,8 @@ claude mcp add --transport http fuobe http://localhost:3000/api/mcp --header "Au
Share links are the one exception: `/s/<token>` and its files open for anyone who has the link, after the host and cross-site checks. Without a password, anyone who can open a share link can open the whole studio too.
+A sign-in lasts 30 days. If you think someone else has signed in as you, open **Settings → Security** and press **Sign everyone out**. It ends every sign-in on every device, yours included, and can revoke every API token too. Your password stays the same. A Settings password change also signs everyone out, but a new `FUOBE_PASSWORD` does not: use **Sign everyone out** after you change it.
+
Public sign-up, guest browsing and connecting your own GPU to a shared install are described in [public-signup.md](public-signup.md).
## Environment variables
diff --git a/src/app/api/auth/sessions/route.ts b/src/app/api/auth/sessions/route.ts
new file mode 100644
index 00000000..7348cf03
--- /dev/null
+++ b/src/app/api/auth/sessions/route.ts
@@ -0,0 +1,20 @@
+import { z } from "zod";
+import { authEnabled, SESSION_COOKIE, sessionCookieOf, signOutEveryone, validSession } from "@/server/auth";
+
+/**
+ * Settings → Security → Sign everyone out: a new session secret, so every signed-in browser (the owner's, this one
+ * too, and every account's) has to sign in again. It works while FUOBE_PASSWORD is set. Only from the owner's
+ * signed-in browser (an API token can't do it). With { tokens: true }, every API token is revoked too.
+ */
+export async function POST(request: Request) {
+ if (!authEnabled()) return Response.json({ error: "Set a password first. Without one, nobody signs in." }, { status: 400 });
+ if (!validSession(sessionCookieOf(request))) return Response.json({ error: "Sign everyone out from the owner's signed-in browser" }, { status: 403 });
+ const parsed = z.object({ tokens: z.boolean().optional() }).safeParse(await request.json().catch(() => ({})));
+ const tokensRevoked = parsed.success && parsed.data.tokens === true;
+ signOutEveryone({ tokens: tokensRevoked });
+ const secure = new URL(request.url).protocol === "https:" ? "; Secure" : "";
+ return Response.json(
+ { ok: true, tokensRevoked },
+ { headers: { "Set-Cookie": `${SESSION_COOKIE}=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax${secure}`, "Cache-Control": "no-store" } },
+ );
+}
diff --git a/src/components/security-settings.tsx b/src/components/security-settings.tsx
index fbfc8dd1..602d96ba 100644
--- a/src/components/security-settings.tsx
+++ b/src/components/security-settings.tsx
@@ -5,7 +5,18 @@ import { Copy, KeyRound, Loader2, LogOut, ShieldAlert, ShieldCheck, Trash2 } fro
import { useRouter } from "next/navigation";
import { useId, useState } from "react";
import { toast } from "sonner";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
+import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
@@ -195,6 +206,65 @@ function Tokens({ status, onChange }: { status: AuthStatus; onChange: () => void
);
}
+/**
+ * A new session secret: every sign-in on every device ends (this browser's too, and every account's), and the owner
+ * signs in again with the same password. It works when the password is set on the server (FUOBE_PASSWORD), where a
+ * password change can't sign anyone out. Optionally revokes every API token as well.
+ */
+function SignOutEveryone({ tokens }: { tokens: number }) {
+ const router = useRouter();
+ const [open, setOpen] = useState(false);
+ const [revoke, setRevoke] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const id = useId();
+ const run = async () => {
+ setBusy(true);
+ try {
+ await call("/api/auth/sessions", "POST", { tokens: revoke });
+ // This browser is signed out too.
+ router.replace("/login?owner=1");
+ } catch (e) {
+ toast.error((e as Error).message);
+ setBusy(false);
+ }
+ };
+ return (
+ <div className="space-y-1.5 sm:w-[36rem] sm:max-w-full">
+ <div className="flex items-center gap-3">
+ <h3 className="flex-1 text-[13px] font-medium">Sign everyone out</h3>
+ <Button size="sm" variant="secondary" className="h-8" disabled={busy} onClick={() => setOpen(true)}>
+ {busy ? <Loader2 className="animate-spin" /> : <LogOut />} Sign everyone out
+ </Button>
+ </div>
+ <p className="text-[12px] text-muted-foreground">
+ Ends every sign-in on every device: yours, this browser&apos;s and every account&apos;s. Use it if you think someone else signed in as you. Your password stays the same.
+ </p>
+ <AlertDialog open={open} onOpenChange={setOpen}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Sign everyone out?</AlertDialogTitle>
+ <AlertDialogDescription>Everyone has to sign in again, you too. You go to the sign-in page next.</AlertDialogDescription>
+ </AlertDialogHeader>
+ {tokens > 0 && (
+ <div className="flex items-start gap-2">
+ <Checkbox id={`${id}-tokens`} className="mt-0.5" checked={revoke} onCheckedChange={(v) => setRevoke(!!v)} />
+ <Label htmlFor={`${id}-tokens`} className="text-[13px] leading-snug font-normal">
+ Also revoke every API token ({tokens}). Scripts and agents that use one stop working until you give them a new one.
+ </Label>
+ </div>
+ )}
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction variant="destructive" onClick={() => void run()}>
+ Sign everyone out
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ );
+}
+
interface PublicSignupStatus {
setting: boolean;
fromEnv: boolean | null;
@@ -272,6 +342,7 @@ export function SecuritySettings() {
)}
{!s.fromEnv && <PasswordForm status={s} onDone={refresh} />}
{s.enabled && <PublicSignup />}
+ {s.enabled && <SignOutEveryone tokens={s.tokens.length} />}
<Tokens status={s} onChange={refresh} />
</div>
);
diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.ts
index 31cbeb87..344087c8 100644
--- a/src/lib/guest-access.ts
+++ b/src/lib/guest-access.ts
@@ -196,8 +196,11 @@ export const CONNECT_GPU_MESSAGE = "Connect your GPU to run this. Free accounts
/** Install-wide settings, keys and tokens: changes are the owner's (403 for an account). */
const OWNER_WRITES = new Set(["/api/settings", "/api/settings/models", "/api/loras", "/api/llm", "/api/providers/test", "/api/auth/public"]);
-/** Owner only, reads included: the password, the API tokens, the assistant's connectors, the MCP endpoint and the accounts admin. */
-const OWNER_ALL = [/^\/api\/auth\/(password|tokens)$/, /^\/api\/assist\/connectors(\/|$)/, /^\/api\/mcp$/, /^\/api\/admin(\/|$)/];
+/**
+ * Owner only, reads included: the password, the API tokens, signing everyone out, the assistant's connectors, the MCP
+ * endpoint and the accounts admin.
+ */
+const OWNER_ALL = [/^\/api\/auth\/(password|tokens|sessions)$/, /^\/api\/assist\/connectors(\/|$)/, /^\/api\/mcp$/, /^\/api\/admin(\/|$)/];
export function ownerOnly(method: string, pathname: string): boolean {
if (OWNER_ALL.some((r) => r.test(pathname))) return true;
diff --git a/src/server/auth.ts b/src/server/auth.ts
index c57e09e6..9c176b09 100644
--- a/src/server/auth.ts
+++ b/src/server/auth.ts
@@ -24,6 +24,7 @@ const FILE = path.join(DATA_DIR, "auth.json");
export const SESSION_COOKIE = "fuobe_session";
const SESSION_DAYS = 30;
+const SESSION_MS = SESSION_DAYS * 86_400_000;
export interface ApiToken {
id: string;
@@ -59,7 +60,10 @@ export interface Account {
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. */
+ /**
+ * Signs session cookies. Kept apart from the password (FUOBE_PASSWORD or the Settings one): replaced when the Settings
+ * password changes and by Settings → Security → Sign everyone out, which both sign every browser out.
+ */
secret: string;
tokens: ApiToken[];
accounts?: Account[];
@@ -151,7 +155,7 @@ export function createSession(accountId?: string): { value: string; maxAge: numb
d = withSecret(d);
write(d);
}
- const exp = Date.now() + SESSION_DAYS * 86_400_000;
+ const exp = Date.now() + SESSION_MS;
const payload = accountId ? `${exp}.${accountId}` : String(exp);
return { value: `${payload}.${sign(d.secret, payload)}`, maxAge: SESSION_DAYS * 86_400 };
}
@@ -159,6 +163,16 @@ export function createSession(accountId?: string): { value: string; maxAge: numb
/** Who a session cookie belongs to: the owner, an account that still exists, or nobody. */
export type Viewer = { kind: "owner" } | { kind: "account"; account: Account };
+/**
+ * A cookie's expiry: the digits createSession wrote, not past and no further ahead than a session lasts. Whoever got hold
+ * of the secret could sign any expiry; a far one is refused, so such a cookie ends with the session lifetime too.
+ */
+function liveExpiry(exp: string, now = Date.now()): boolean {
+ if (!/^\d{1,16}$/.test(exp)) return false;
+ const t = Number(exp);
+ return t >= now && t <= now + SESSION_MS;
+}
+
export function sessionViewer(value: string | undefined): Viewer | null {
if (!value) return null;
const parts = value.split(".");
@@ -166,13 +180,23 @@ export function sessionViewer(value: string | undefined): Viewer | null {
const exp = parts[0];
const mac = parts[parts.length - 1];
const d = read();
- if (!d.secret || !exp || !mac || !(Number(exp) >= Date.now())) return null;
+ if (!d.secret || !mac || !liveExpiry(exp)) return null;
if (!same(Buffer.from(mac), Buffer.from(sign(d.secret, parts.slice(0, -1).join("."))))) return null;
if (parts.length === 2) return { kind: "owner" };
const account = d.accounts?.find((a) => a.id === parts[1]);
return account && !account.disabled ? { kind: "account", account } : null;
}
+/**
+ * Settings → Security → Sign everyone out: a new secret, so every session cookie (the owner's and every account's,
+ * this browser's too) stops working at once. Works while FUOBE_PASSWORD is set, which the Settings password change
+ * can't. With `tokens`, every API token is revoked as well. The password stays as it is.
+ */
+export function signOutEveryone(opts: { tokens?: boolean } = {}): void {
+ const d = read();
+ write({ ...d, secret: crypto.randomBytes(32).toString("hex"), ...(opts.tokens && { tokens: [] }) });
+}
+
/** The owner's session (the install password's): what Settings → Security and the tokens need. */
export function validSession(value: string | undefined): boolean {
return sessionViewer(value)?.kind === "owner";
diff --git a/tests/sign-out-everyone.test.ts b/tests/sign-out-everyone.test.ts
new file mode 100644
index 00000000..797b2a47
--- /dev/null
+++ b/tests/sign-out-everyone.test.ts
@@ -0,0 +1,129 @@
+import crypto from "node:crypto";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import { NextRequest } from "next/server";
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-signout-"));
+process.env.FUOBE_DATA_DIR = dir;
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_PUBLIC_SIGNUP;
+const auth = await import("@/server/auth");
+const { proxy } = await import("@/proxy");
+const route = await import("@/app/api/auth/sessions/route");
+afterAll(() => {
+ delete process.env.FUOBE_PASSWORD;
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+
+const DAY = 86_400_000;
+const secret = () => (JSON.parse(fs.readFileSync(path.join(dir, "auth.json"), "utf8")) as { secret: string }).secret;
+/** A cookie signed with the real secret, as someone who read auth.json could make one. */
+const forge = (payload: string) => `${payload}.${crypto.createHmac("sha256", secret()).update(payload).digest("base64url")}`;
+
+function req(method: string, init: { cookie?: string; headers?: Record<string, string> } = {}) {
+ const headers: Record<string, string> = { ...init.headers };
+ if (init.cookie) headers.cookie = `${auth.SESSION_COOKIE}=${init.cookie}`;
+ return new NextRequest("http://localhost:3000/api/auth/sessions", { method, headers });
+}
+
+beforeAll(() => {
+ // fuobe.com: the password comes from the server's environment, so Settings can't change it.
+ process.env.FUOBE_PASSWORD = "from the environment";
+});
+afterEach(() => delete process.env.FUOBE_PUBLIC_SIGNUP);
+
+describe("H-1: a cookie's expiry is capped at the session lifetime", () => {
+ it("refuses a forged owner cookie that expires far in the future, and keeps a real one", () => {
+ const real = auth.createSession().value;
+ expect(auth.validSession(real)).toBe(true);
+ expect(auth.validSession(forge("9999999999999"))).toBe(false);
+ expect(auth.validSession(forge(String(Date.now() + 31 * DAY)))).toBe(false);
+ // Signed just now for the full 30 days: still fine.
+ expect(auth.validSession(forge(String(Date.now() + 30 * DAY - 1000)))).toBe(true);
+ });
+
+ it("refuses a forged account cookie that expires far in the future", () => {
+ const a = auth.createAccount("[email protected]", "long enough");
+ expect(auth.sessionViewer(auth.createSession(a.id).value)?.kind).toBe("account");
+ expect(auth.sessionViewer(forge(`9999999999999.${a.id}`))).toBeNull();
+ });
+
+ it("refuses an expiry that isn't plain digits", () => {
+ // Both read as a time a day from now by Number(), but no real cookie looks like this.
+ expect(auth.validSession(forge(`0x${(Date.now() + DAY).toString(16)}`))).toBe(false);
+ expect(auth.validSession(forge(`${String(Date.now() + DAY).slice(0, -3)}e3`))).toBe(false);
+ });
+});
+
+describe("H-1: Sign everyone out", () => {
+ it("replaces the secret even while FUOBE_PASSWORD is set: every owner and account session ends, the password still works", () => {
+ const owner = auth.createSession().value;
+ const a = auth.createAccount("[email protected]", "long enough");
+ const account = auth.createSession(a.id).value;
+ const before = secret();
+ auth.signOutEveryone();
+ expect(secret()).not.toBe(before);
+ expect(secret()).toMatch(/^[0-9a-f]{64}$/);
+ expect(auth.validSession(owner)).toBe(false);
+ expect(auth.sessionViewer(account)).toBeNull();
+ expect(auth.checkPassword("from the environment")).toBe(true);
+ expect(auth.validSession(auth.createSession().value)).toBe(true);
+ expect(auth.checkAccount("[email protected]", "long enough")?.id).toBe(a.id);
+ });
+
+ it("keeps API tokens unless asked to revoke them too", () => {
+ const { token } = auth.createToken("CI");
+ auth.signOutEveryone();
+ expect(auth.validToken(`Bearer ${token}`)).toBe(true);
+ auth.signOutEveryone({ tokens: true });
+ expect(auth.validToken(`Bearer ${token}`)).toBe(false);
+ expect(auth.authStatus().tokens).toEqual([]);
+ });
+
+ it("is a POST the owner's signed-in browser makes, and signs that browser out too", async () => {
+ const owner = auth.createSession().value;
+ const other = auth.createSession().value;
+ const { token } = auth.createToken("kept");
+ const res = await route.POST(req("POST", { cookie: owner, headers: { "content-type": "application/json" } }));
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ ok: true, tokensRevoked: false });
+ // The cookie of the browser that pressed it is cleared, and it no longer works anywhere.
+ expect(res.headers.get("set-cookie")).toMatch(/^fuobe_session=;.*Max-Age=0/i);
+ expect(auth.validSession(owner)).toBe(false);
+ expect(auth.validSession(other)).toBe(false);
+ expect(auth.validToken(`Bearer ${token}`)).toBe(true);
+ });
+
+ it("revokes every API token when the owner asks", async () => {
+ const owner = auth.createSession().value;
+ const { token } = auth.createToken("gone");
+ const res = await route.POST(new NextRequest("http://localhost:3000/api/auth/sessions", { method: "POST", headers: { cookie: `${auth.SESSION_COOKIE}=${owner}`, "content-type": "application/json" }, body: JSON.stringify({ tokens: true }) }));
+ expect(res.status).toBe(200);
+ expect((await res.json()).tokensRevoked).toBe(true);
+ expect(auth.validToken(`Bearer ${token}`)).toBe(false);
+ });
+
+ it("refuses an API token, an account and a guest", async () => {
+ const before = secret();
+ const { token } = auth.createToken("script");
+ expect((await route.POST(req("POST", { headers: { authorization: `Bearer ${token}` } }))).status).toBe(403);
+ const a = auth.createAccount("[email protected]", "long enough");
+ expect((await route.POST(req("POST", { cookie: auth.createSession(a.id).value }))).status).toBe(403);
+ expect((await route.POST(req("POST"))).status).toBe(403);
+ expect(secret()).toBe(before);
+ });
+
+ it("is the owner's only in the proxy too", async () => {
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ const a = auth.createAccount("[email protected]", "long enough");
+ const r = proxy(req("POST", { cookie: auth.createSession(a.id).value }));
+ expect(r.status).toBe(403);
+ expect((await r.json()).error).toMatch(/owner/);
+ expect(proxy(req("POST")).status).toBe(401);
+ });
+});