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: a new password ends owner sign-ins, and sign-outs end an open live feed

Adarsh89127d7270ac
diff --git a/docs/SELF-HOSTING.md b/docs/SELF-HOSTING.md
index ad9067a7..4554ae32 100644
--- a/docs/SELF-HOSTING.md
+++ b/docs/SELF-HOSTING.md
@@ -70,7 +70,7 @@ 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.
+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 (an open live feed too), and can revoke every API token too. Your password stays the same. A new password also ends every owner sign-in: a Settings password change at once (it signs accounts out too), and a new `FUOBE_PASSWORD` when the server restarts (accounts stay signed in). API tokens are not tied to the password: revoke them in **Settings → Security**, or tick **Also revoke every API token** when you sign everyone out.
Public sign-up, guest browsing and connecting your own GPU to a shared install are described in [public-signup.md](public-signup.md).
diff --git a/src/app/api/generations/stream/route.ts b/src/app/api/generations/stream/route.ts
index ae67c849..c2e94882 100644
--- a/src/app/api/generations/stream/route.ts
+++ b/src/app/api/generations/stream/route.ts
@@ -1,4 +1,5 @@
import { connection } from "next/server";
+import { authVersion, isOwnerRequest, sessionCookieOf } from "@/server/auth";
import { ensureRunner } from "@/server/generations";
import { generationEventStream } from "@/server/live";
@@ -8,10 +9,26 @@ import { generationEventStream } from "@/server/live";
* event: deleted data: {"id": "…"}
* : ping every 15 s
* Sent on every insert or update of a generation row (status, progress, outputs…).
+ *
+ * The owner's feed only. The proxy checks who is asking when the stream opens; while it stays open (it can for days),
+ * the sign-in is checked again whenever the sign-in file changes and on every ping, and the stream ends once it no
+ * longer holds: after Sign everyone out, a new password, a revoked token, or the sign-in's own end.
*/
export async function GET(request: Request) {
// Never prerendered, and the runner that produces the updates is running.
await connection();
+ const cookie = sessionCookieOf(request);
+ if (!isOwnerRequest(request, cookie)) return Response.json({ error: "Sign in first" }, { status: 401, headers: { "Cache-Control": "no-store" } });
ensureRunner();
- return generationEventStream(request.signal);
+ let seen = authVersion();
+ let ok = true;
+ const allowed = (ping: boolean) => {
+ const now = authVersion();
+ if (ping || now !== seen) {
+ seen = now;
+ ok = isOwnerRequest(request, cookie);
+ }
+ return ok;
+ };
+ return generationEventStream(request.signal, { allowed });
}
diff --git a/src/components/security-settings.tsx b/src/components/security-settings.tsx
index 602d96ba..bf58db40 100644
--- a/src/components/security-settings.tsx
+++ b/src/components/security-settings.tsx
@@ -208,8 +208,9 @@ 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.
+ * signs in again with the same password. It works when the password is set on the server (FUOBE_PASSWORD), which
+ * Settings can't change. Optionally revokes every API token as well: offered even when the list looked empty when the
+ * page loaded, since a token made since then would otherwise stay.
*/
function SignOutEveryone({ tokens }: { tokens: number }) {
const router = useRouter();
@@ -245,14 +246,12 @@ function SignOutEveryone({ tokens }: { tokens: number }) {
<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>
- )}
+ <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 > 0 ? ` (${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()}>
diff --git a/src/server/auth.ts b/src/server/auth.ts
index ec26f3de..cca31921 100644
--- a/src/server/auth.ts
+++ b/src/server/auth.ts
@@ -61,8 +61,8 @@ interface AuthFile {
/** scrypt hash of the UI-set password ("salt:hash", hex). */
password?: string;
/**
- * 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.
+ * Signs session cookies (an owner's with the password's fingerprint too: keyFor). Replaced when the Settings password
+ * changes and by Settings → Security → Sign everyone out, which both sign every browser out.
*/
secret: string;
tokens: ApiToken[];
@@ -99,6 +99,10 @@ function read(): AuthFile {
}
}
+declare global {
+ var __fuobeAuthWrites: number | undefined;
+}
+
function write(data: AuthFile): void {
if (data.unreadable) throw new Error("The sign-in file (auth.json) can't be read. Fix or restore it: Fuobe won't write over it.");
fs.mkdirSync(DATA_DIR, { recursive: true });
@@ -106,8 +110,15 @@ function write(data: AuthFile): void {
fs.writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 0o600 });
fs.renameSync(tmp, FILE);
cache = null;
+ globalThis.__fuobeAuthWrites = (globalThis.__fuobeAuthWrites ?? 0) + 1;
}
+/**
+ * Changes when this server writes the sign-in file (a sign-out of everyone, a new password, a token revoked…): a request
+ * that stays open, like the live feed, checks who is asking again when it changes.
+ */
+export const authVersion = () => globalThis.__fuobeAuthWrites ?? 0;
+
function withSecret(data: AuthFile): AuthFile {
return data.secret ? data : { ...data, secret: crypto.randomBytes(32).toString("hex") };
}
@@ -181,9 +192,19 @@ export function setPassword(pw: string | null): void {
const sign = (secret: string, payload: string) => crypto.createHmac("sha256", secret).update(payload).digest("base64url");
+/**
+ * The key a session is signed with. An owner's also holds the password's fingerprint, so a new password (FUOBE_PASSWORD
+ * after a restart, or the Settings one) ends every owner sign-in at once, and the secret alone (auth.json) can't make an
+ * owner cookie. An account's is the secret alone, so the owner's new password doesn't sign every account out.
+ */
+function keyFor(d: AuthFile, owner: boolean): string {
+ if (!owner) return d.secret;
+ return `${d.secret}.${crypto.createHash("sha256").update(envPassword() || d.password || "").digest("hex")}`;
+}
+
/**
* A session cookie: "<expiry>.<mac>" for the owner, "<expiry>.<account id>.<mac>" for an account.
- * The two sign different text, so neither can be turned into the other.
+ * The two sign different text with different keys, so neither can be turned into the other.
*/
export function createSession(accountId?: string): { value: string; maxAge: number } {
let d = read();
@@ -193,7 +214,7 @@ export function createSession(accountId?: string): { value: string; maxAge: numb
}
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 };
+ return { value: `${payload}.${sign(keyFor(d, !accountId), payload)}`, maxAge: SESSION_DAYS * 86_400 };
}
/** Who a session cookie belongs to: the owner, an account that still exists, or nobody. */
@@ -217,7 +238,7 @@ export function sessionViewer(value: string | undefined): Viewer | null {
const mac = parts[parts.length - 1];
const d = read();
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 (!same(Buffer.from(mac), Buffer.from(sign(keyFor(d, parts.length === 2), 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;
diff --git a/src/server/live.ts b/src/server/live.ts
index 0b3399b7..7dc7f91f 100644
--- a/src/server/live.ts
+++ b/src/server/live.ts
@@ -104,8 +104,12 @@ const PING_MS = 15_000;
* A server-sent events stream of generation changes: `event: generation` (the Generation JSON,
* exactly as GET /api/generations returns it), `event: deleted` ({"id"}), `: ping` every 15 s.
* The listener and the ping are removed as soon as the client goes away.
+ *
+ * `allowed`: whether whoever opened the stream may still read it, asked before every event and on every ping (`ping`
+ * true: look again even when nothing changed, so a sign-in that expires is caught too). The stream ends at the first
+ * no: a sign-in ended by Sign everyone out, a new password or a revoked token never receives another event.
*/
-export function generationEventStream(signal: AbortSignal, opts: { pingMs?: number } = {}): Response {
+export function generationEventStream(signal: AbortSignal, opts: { pingMs?: number; allowed?: (ping: boolean) => boolean } = {}): Response {
let stop = () => {};
const body = new ReadableStream<Uint8Array>({
start(controller) {
@@ -118,8 +122,20 @@ export function generationEventStream(signal: AbortSignal, opts: { pingMs?: numb
stop();
}
};
- const off = subscribe((e) => send(`event: ${e.type}\ndata: ${e.json}\n\n`));
- const ping = setInterval(() => send(": ping\n\n"), opts.pingMs ?? PING_MS);
+ const still = (ping: boolean) => {
+ let ok = false;
+ try {
+ ok = !opts.allowed || opts.allowed(ping);
+ } catch {}
+ if (!ok) stop();
+ return ok;
+ };
+ const off = subscribe((e) => {
+ if (still(false)) send(`event: ${e.type}\ndata: ${e.json}\n\n`);
+ });
+ const ping = setInterval(() => {
+ if (still(true)) send(": ping\n\n");
+ }, opts.pingMs ?? PING_MS);
stop = () => {
if (!open) return;
open = false;
diff --git a/tests/sign-out-everyone.test.ts b/tests/sign-out-everyone.test.ts
index 797b2a47..f992ab21 100644
--- a/tests/sign-out-everyone.test.ts
+++ b/tests/sign-out-everyone.test.ts
@@ -22,8 +22,13 @@ afterAll(() => {
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")}`;
+const hmac = (key: string, payload: string) => crypto.createHmac("sha256", key).update(payload).digest("base64url");
+const passwordTag = () => crypto.createHash("sha256").update(process.env.FUOBE_PASSWORD ?? "").digest("hex");
+/**
+ * A cookie signed as the server signs it, as someone who read auth.json and also knew the password could make one: an
+ * owner's ("<expiry>") with the secret and the password, an account's ("<expiry>.<id>") with the secret alone.
+ */
+const forge = (payload: string) => `${payload}.${hmac(payload.includes(".") ? secret() : `${secret()}.${passwordTag()}`, payload)}`;
function req(method: string, init: { cookie?: string; headers?: Record<string, string> } = {}) {
const headers: Record<string, string> = { ...init.headers };
@@ -60,6 +65,99 @@ describe("H-1: a cookie's expiry is capped at the session lifetime", () => {
});
});
+describe("H-1: owner sign-ins are tied to the password", () => {
+ it("a new FUOBE_PASSWORD ends every owner sign-in at the restart, and no account's", () => {
+ const owner = auth.createSession().value;
+ const a = auth.createAccount("[email protected]", "long enough");
+ const account = auth.createSession(a.id).value;
+ process.env.FUOBE_PASSWORD = "a brand new password";
+ try {
+ expect(auth.validSession(owner)).toBe(false);
+ expect(auth.sessionViewer(account)?.kind).toBe("account");
+ expect(auth.validSession(auth.createSession().value)).toBe(true);
+ } finally {
+ process.env.FUOBE_PASSWORD = "from the environment";
+ }
+ });
+
+ it("the secret alone (someone who read auth.json, not the password) can't make an owner cookie", () => {
+ const exp = String(Date.now() + DAY);
+ expect(auth.validSession(`${exp}.${hmac(secret(), exp)}`)).toBe(false);
+ expect(auth.validSession(forge(exp))).toBe(true);
+ });
+});
+
+describe("H-1: Sign everyone out also ends an open live feed", () => {
+ const stream = () => import("@/app/api/generations/stream/route");
+ /** A read left waiting when the time ran out: the next call takes it over, so no chunk is lost. */
+ const waiting = new WeakMap<object, Promise<ReadableStreamReadResult<Uint8Array>>>();
+ /** What a stream sends within `ms`, and whether it ended. */
+ async function readFor(reader: ReadableStreamDefaultReader<Uint8Array>, ms: number): Promise<{ text: string; done: boolean }> {
+ const dec = new TextDecoder();
+ let text = "";
+ const until = Date.now() + ms;
+ for (;;) {
+ const left = until - Date.now();
+ if (left <= 0) return { text, done: false };
+ const read = waiting.get(reader) ?? reader.read();
+ waiting.set(reader, read);
+ const r = await Promise.race([read, new Promise<null>((resolve) => setTimeout(() => resolve(null), left))]);
+ if (r === null) return { text, done: false };
+ waiting.delete(reader);
+ if (r.done) return { text, done: true };
+ text += dec.decode(r.value);
+ }
+ }
+ let n = 0;
+ /** A new run in the owner's library (a row change is what the feed sends). */
+ async function aRun(): Promise<string> {
+ const { db } = await import("@/server/db");
+ const id = `live-${++n}-${Date.now()}`;
+ db()
+ .prepare(
+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, prompt, request_json, created_at, updated_at) VALUES (?, 'image', 'mock-image', 'cloud', 'mock', 'text-to-image', 'image', 'queued', ?, '{}', ?, ?)",
+ )
+ .run(id, `prompt ${id}`, Date.now(), Date.now());
+ return id;
+ }
+
+ it("a stream opened before Sign everyone out sends nothing after it, and closes", async () => {
+ const owner = auth.createSession().value;
+ const ac = new AbortController();
+ const res = await (await stream()).GET(new NextRequest("http://localhost:3000/api/generations/stream", { headers: { cookie: `${auth.SESSION_COOKIE}=${owner}` }, signal: ac.signal }));
+ const reader = res.body!.getReader();
+ try {
+ expect((await readFor(reader, 200)).text).toMatch(/^retry: 2000/);
+ const before = await aRun();
+ expect((await readFor(reader, 300)).text).toContain(`"id":"${before}"`);
+ auth.signOutEveryone();
+ const after = await aRun();
+ const rest = await readFor(reader, 500);
+ expect(rest.text).not.toContain(after);
+ expect(rest.done).toBe(true);
+ } finally {
+ ac.abort();
+ }
+ });
+
+ it("the same for a stream opened with an API token that is then revoked", async () => {
+ const { token, info } = auth.createToken("feed");
+ const ac = new AbortController();
+ const res = await (await stream()).GET(new NextRequest("http://localhost:3000/api/generations/stream", { headers: { authorization: `Bearer ${token}` }, signal: ac.signal }));
+ const reader = res.body!.getReader();
+ try {
+ await readFor(reader, 100);
+ auth.revokeToken(info.id);
+ const after = await aRun();
+ const rest = await readFor(reader, 500);
+ expect(rest.text).not.toContain(after);
+ expect(rest.done).toBe(true);
+ } finally {
+ ac.abort();
+ }
+ });
+});
+
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;