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.

Settings → Accounts: the owner's list of sign-ups

Adarshdbc761f95941
diff --git a/docs/public-signup.md b/docs/public-signup.md
index aeb8eb63..b3d70400 100644
--- a/docs/public-signup.md
+++ b/docs/public-signup.md
@@ -58,6 +58,16 @@ An account is signed in, but it sees the owner's studio as a guest does:
generation, an AI helper, a retry) answers 403 with `code: "connect-gpu"`, and the studio shows a
"Connect your GPU to run this" card. An account's own GPU connection comes in a later change.
+## Managing accounts
+
+The owner sees everyone who signed up in **Settings → Accounts**: email, when the account was
+created, its last log-in, whether its own GPU is connected, and the total. The owner can switch an
+account off (it is signed out at once and can't log in) or delete it, and export the list as CSV.
+The API is `GET /api/admin/accounts` (`?format=csv` for the file), `PATCH /api/admin/accounts/<id>`
+with `{ "disabled": true | false }`, and `DELETE /api/admin/accounts/<id>`, for the owner only.
+
+An account can delete itself: `DELETE /api/auth/me` with `{ "password" }`.
+
`GET /api/auth/me` (open to everyone) says who is looking: `{ signedIn, owner, publicSignup,
account? }`.
diff --git a/src/app/(studio)/settings/page.tsx b/src/app/(studio)/settings/page.tsx
index bf59a55f..fa454a9f 100644
--- a/src/app/(studio)/settings/page.tsx
+++ b/src/app/(studio)/settings/page.tsx
@@ -1,4 +1,5 @@
import type { Metadata } from "next";
+import { AccountsAdmin } from "@/components/accounts-admin";
import { PageHeader, PageShell } from "@/components/page-shell";
import { SettingsForm } from "@/components/settings-form";
import { starterPriceLine } from "@/lib/starter-prices";
@@ -10,6 +11,7 @@ export default function Page() {
<PageShell>
<PageHeader title="Settings" description="Choose open source, paid APIs or both, connect providers, point Fuobe at your ComfyUI server, and choose how prompts get enhanced. Keys stay on this server." />
<SettingsForm prices={starterPriceLine()} />
+ <AccountsAdmin />
</PageShell>
);
}
diff --git a/src/app/api/admin/accounts/[id]/route.ts b/src/app/api/admin/accounts/[id]/route.ts
new file mode 100644
index 00000000..6af172c2
--- /dev/null
+++ b/src/app/api/admin/accounts/[id]/route.ts
@@ -0,0 +1,39 @@
+import { cookies } from "next/headers";
+import { z } from "zod";
+import { AccountError, deleteAccount, isOwnerRequest, listAccounts, SESSION_COOKIE, setAccountDisabled } from "@/server/auth";
+
+async function owner(request: Request): Promise<Response | null> {
+ return isOwnerRequest(request, (await cookies()).get(SESSION_COOKIE)?.value) ? null : Response.json({ error: "Only the studio's owner manages accounts" }, { status: 403 });
+}
+
+const failed = (e: unknown) => {
+ if (e instanceof AccountError) return Response.json({ error: e.message }, { status: e.status });
+ throw e;
+};
+
+/** Switch an account off (`{ disabled: true }`: signed out, can't log in) or on again. */
+export async function PATCH(request: Request, ctx: RouteContext<"/api/admin/accounts/[id]">) {
+ const denied = await owner(request);
+ if (denied) return denied;
+ const parsed = z.object({ disabled: z.boolean() }).safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: "Send { disabled: true } or { disabled: false }" }, { status: 400 });
+ const { id } = await ctx.params;
+ try {
+ setAccountDisabled(id, parsed.data.disabled);
+ } catch (e) {
+ return failed(e);
+ }
+ return Response.json(listAccounts().find((a) => a.id === id));
+}
+
+/** Delete an account. */
+export async function DELETE(request: Request, ctx: RouteContext<"/api/admin/accounts/[id]">) {
+ const denied = await owner(request);
+ if (denied) return denied;
+ try {
+ deleteAccount((await ctx.params).id);
+ } catch (e) {
+ return failed(e);
+ }
+ return new Response(null, { status: 204 });
+}
diff --git a/src/app/api/admin/accounts/route.ts b/src/app/api/admin/accounts/route.ts
new file mode 100644
index 00000000..57bcb08b
--- /dev/null
+++ b/src/app/api/admin/accounts/route.ts
@@ -0,0 +1,17 @@
+import { cookies } from "next/headers";
+import { connection } from "next/server";
+import { accountsCsv, isOwnerRequest, listAccounts, SESSION_COOKIE } from "@/server/auth";
+
+/** Settings → Accounts (owner only): everyone who signed up, newest first. `?format=csv` downloads them. */
+export async function GET(request: Request) {
+ await connection();
+ if (!isOwnerRequest(request, (await cookies()).get(SESSION_COOKIE)?.value)) return Response.json({ error: "Only the studio's owner sees accounts" }, { status: 403 });
+ const items = listAccounts();
+ if (new URL(request.url).searchParams.get("format") === "csv") {
+ const day = new Date().toISOString().slice(0, 10);
+ return new Response(accountsCsv(items), {
+ headers: { "Content-Type": "text/csv; charset=utf-8", "Content-Disposition": `attachment; filename="fuobe-accounts-${day}.csv"`, "Cache-Control": "no-store" },
+ });
+ }
+ return Response.json({ total: items.length, items }, { headers: { "Cache-Control": "no-store" } });
+}
diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.ts
index b87bf2ee..58eb309e 100644
--- a/src/app/api/auth/login/route.ts
+++ b/src/app/api/auth/login/route.ts
@@ -1,6 +1,6 @@
import { cookies } from "next/headers";
import { z } from "zod";
-import { authEnabled, checkAccount, checkPassword, createSession, LoginGuard, publicSignup, SESSION_COOKIE } from "@/server/auth";
+import { authEnabled, checkAccount, checkPassword, createSession, LoginGuard, publicSignup, recordLogin, SESSION_COOKIE } from "@/server/auth";
/** The install password alone (the owner), or an account's email and password (public sign-up). */
const Body = z.object({ password: z.string().min(1).max(500), email: z.string().max(254).optional() });
@@ -32,7 +32,9 @@ export async function POST(request: Request) {
guard.fail(key);
return Response.json({ error: "Wrong email or password" }, { status: 401 });
}
+ if (account.disabled) return Response.json({ error: "This account is switched off. Ask the studio's owner." }, { status: 403 });
accountId = account.id;
+ recordLogin(account.id);
} else if (!parsed.success || !checkPassword(parsed.data.password)) {
guard.fail(key);
return Response.json({ error: "Wrong password" }, { status: 401 });
diff --git a/src/app/api/auth/me/route.ts b/src/app/api/auth/me/route.ts
index e5290d01..0ee9eefe 100644
--- a/src/app/api/auth/me/route.ts
+++ b/src/app/api/auth/me/route.ts
@@ -1,6 +1,7 @@
import { cookies } from "next/headers";
import { connection } from "next/server";
-import { authEnabled, publicSignup, SESSION_COOKIE, sessionViewer, validToken } from "@/server/auth";
+import { z } from "zod";
+import { authEnabled, checkAccount, deleteAccount, publicSignup, SESSION_COOKIE, sessionViewer, validToken } from "@/server/auth";
/** Who is looking: the owner, an account, or a guest; and whether sign-up is open. Open to everyone. */
export async function GET(request: Request) {
@@ -19,3 +20,15 @@ export async function GET(request: Request) {
{ headers: { "Cache-Control": "no-store" } },
);
}
+
+/** An account deletes itself (its password again, to be sure). Signs it out. */
+export async function DELETE(request: Request) {
+ const jar = await cookies();
+ const session = sessionViewer(jar.get(SESSION_COOKIE)?.value);
+ if (session?.kind !== "account") return Response.json({ error: "Sign in to the account you want to delete" }, { status: 403 });
+ const parsed = z.object({ password: z.string().min(1).max(500) }).safeParse(await request.json().catch(() => null));
+ if (!parsed.success || !checkAccount(session.account.email, parsed.data.password)) return Response.json({ error: "Wrong password" }, { status: 403 });
+ deleteAccount(session.account.id);
+ jar.delete(SESSION_COOKIE);
+ return new Response(null, { status: 204 });
+}
diff --git a/src/components/accounts-admin.tsx b/src/components/accounts-admin.tsx
new file mode 100644
index 00000000..b647160c
--- /dev/null
+++ b/src/components/accounts-admin.tsx
@@ -0,0 +1,119 @@
+"use client";
+
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { Download, Loader2, Trash2, UserX, UserCheck } from "lucide-react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { useViewer } from "@/lib/api";
+import { timeAgo } from "@/lib/format";
+
+interface AccountRow {
+ id: string;
+ email: string;
+ createdAt: number;
+ lastLoginAt: number | null;
+ disabled: boolean;
+ gpu: boolean;
+}
+
+async function call<T>(url: string, method = "GET", 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;
+}
+
+/** Settings → Accounts (the owner only): who signed up (public sign-up), with switch-off, delete and a CSV export. */
+export function AccountsAdmin() {
+ const owner = useViewer().data?.owner;
+ const qc = useQueryClient();
+ const q = useQuery({ queryKey: ["admin-accounts"], queryFn: () => call<{ total: number; items: AccountRow[] }>("/api/admin/accounts"), enabled: !!owner });
+ if (!owner || !q.data) return null;
+ const refresh = () => void qc.invalidateQueries({ queryKey: ["admin-accounts"] });
+ const act = async (fn: () => Promise<unknown>, done: string) => {
+ try {
+ await fn();
+ toast.success(done);
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ refresh();
+ }
+ };
+ const { total, items } = q.data;
+ return (
+ <section id="accounts" aria-labelledby="accounts-title" className="grid scroll-mt-28 grid-cols-[minmax(0,1fr)] gap-6 border-t py-8 md:scroll-mt-20 md:grid-cols-[260px_minmax(0,1fr)]">
+ <div className="min-w-0">
+ <h2 id="accounts-title" className="text-[15px] font-semibold">
+ Accounts
+ </h2>
+ <p className="mt-1 text-[13px] text-muted-foreground">
+ {total} {total === 1 ? "person has" : "people have"} signed up (Settings → Security → Public sign-up). Accounts never see your library or use your keys and GPU.
+ </p>
+ </div>
+ <div className="min-w-0 space-y-3">
+ <div className="flex flex-wrap items-center gap-2">
+ <Button asChild size="sm" variant="secondary" disabled={!total}>
+ <a href="/api/admin/accounts?format=csv" download>
+ <Download /> Export CSV
+ </a>
+ </Button>
+ {q.isFetching && <Loader2 className="size-4 animate-spin text-muted-foreground" />}
+ </div>
+ {items.length > 0 && (
+ <div className="overflow-x-auto rounded-xl border">
+ <table className="w-full text-left text-[12px]">
+ <thead className="bg-muted/50 text-muted-foreground">
+ <tr>
+ <th className="px-3 py-2 font-medium">Email</th>
+ <th className="px-3 py-2 font-medium">Created</th>
+ <th className="px-3 py-2 font-medium">Last login</th>
+ <th className="px-3 py-2 font-medium">GPU</th>
+ <th className="px-3 py-2" />
+ </tr>
+ </thead>
+ <tbody className="divide-y">
+ {items.map((a) => (
+ <tr key={a.id} className={a.disabled ? "text-muted-foreground" : undefined}>
+ <td className="max-w-56 truncate px-3 py-2 font-medium">
+ {a.email}
+ {a.disabled && <span className="ml-1.5 rounded-sm bg-muted px-1 py-0.5 text-[10px] font-normal">off</span>}
+ </td>
+ <td className="px-3 py-2 whitespace-nowrap">{timeAgo(a.createdAt)}</td>
+ <td className="px-3 py-2 whitespace-nowrap">{a.lastLoginAt ? timeAgo(a.lastLoginAt) : "—"}</td>
+ <td className="px-3 py-2">{a.gpu ? "Connected" : "—"}</td>
+ <td className="px-2 py-1 text-right whitespace-nowrap">
+ <Button
+ size="icon"
+ variant="ghost"
+ className="size-7 text-muted-foreground"
+ aria-label={a.disabled ? `Switch ${a.email} on` : `Switch ${a.email} off`}
+ title={a.disabled ? "Switch on" : "Switch off"}
+ onClick={() => void act(() => call(`/api/admin/accounts/${a.id}`, "PATCH", { disabled: !a.disabled }), a.disabled ? "Switched on" : "Switched off")}
+ >
+ {a.disabled ? <UserCheck className="size-3.5" /> : <UserX className="size-3.5" />}
+ </Button>
+ <Button
+ size="icon"
+ variant="ghost"
+ className="size-7 text-muted-foreground hover:text-destructive"
+ aria-label={`Delete ${a.email}`}
+ title="Delete"
+ onClick={() => {
+ if (window.confirm(`Delete the account ${a.email}?`)) void act(() => call(`/api/admin/accounts/${a.id}`, "DELETE"), "Account deleted");
+ }}
+ >
+ <Trash2 className="size-3.5" />
+ </Button>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+ </div>
+ </section>
+ );
+}
diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.ts
index 28e12fa6..7fc07cb3 100644
--- a/src/lib/guest-access.ts
+++ b/src/lib/guest-access.ts
@@ -151,8 +151,8 @@ 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 and the MCP endpoint. */
-const OWNER_ALL = [/^\/api\/auth\/(password|tokens)$/, /^\/api\/assist\/connectors(\/|$)/, /^\/api\/mcp$/];
+/** 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(\/|$)/];
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 a5ed45b9..cad9b4ef 100644
--- a/src/server/auth.ts
+++ b/src/server/auth.ts
@@ -43,6 +43,10 @@ export interface Account {
/** scrypt hash of the password ("salt:hash", hex), as the install password's. */
hash: string;
createdAt: number;
+ /** The last sign-up or log-in. */
+ lastLoginAt?: number;
+ /** Switched off by the owner (Settings → Accounts): signed out, and can't log in. */
+ disabled?: boolean;
}
interface AuthFile {
@@ -159,7 +163,7 @@ export function sessionViewer(value: string | undefined): Viewer | 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 ? { kind: "account", account } : null;
+ return account && !account.disabled ? { kind: "account", account } : null;
}
/** The owner's session (the install password's): what Settings → Security and the tokens need. */
@@ -191,7 +195,7 @@ export function createAccount(email: string, password: string): Account {
if (password.length < 8) throw new AccountError("Use at least 8 characters", 400);
const d = withSecret(read());
if (d.accounts?.some((a) => a.email === e)) throw new AccountError("An account with this email already exists. Log in instead.", 409);
- const account: Account = { id: crypto.randomBytes(9).toString("hex"), email: e, hash: hashPassword(password), createdAt: Date.now() };
+ const account: Account = { id: crypto.randomBytes(9).toString("hex"), email: e, hash: hashPassword(password), createdAt: Date.now(), lastLoginAt: Date.now() };
write({ ...d, accounts: [...(d.accounts ?? []), account] });
return account;
}
@@ -206,6 +210,61 @@ export function checkAccount(email: string, password: string): Account | null {
return account && ok ? account : null;
}
+/** Remember a log-in (Settings → Accounts shows it). */
+export function recordLogin(id: string): void {
+ const d = read();
+ write({ ...d, accounts: d.accounts?.map((a) => (a.id === id ? { ...a, lastLoginAt: Date.now() } : a)) });
+}
+
+/** What the owner sees of an account (Settings → Accounts): never the password hash. */
+export interface AccountInfo {
+ id: string;
+ email: string;
+ createdAt: number;
+ lastLoginAt: number | null;
+ disabled: boolean;
+ /** Its own ComfyUI is connected ("Your GPU"). */
+ gpu: boolean;
+}
+
+export function listAccounts(): AccountInfo[] {
+ return (read().accounts ?? [])
+ .map((a) => ({ id: a.id, email: a.email, createdAt: a.createdAt, lastLoginAt: a.lastLoginAt ?? null, disabled: !!a.disabled, gpu: "gpu" in a && !!(a as { gpu?: unknown }).gpu }))
+ .sort((a, b) => b.createdAt - a.createdAt);
+}
+
+/** Switch an account off (it is signed out at once) or on again. */
+export function setAccountDisabled(id: string, disabled: boolean): void {
+ const d = read();
+ if (!d.accounts?.some((a) => a.id === id)) throw new AccountError("No such account", 404);
+ write({ ...d, accounts: d.accounts.map((a) => (a.id === id ? { ...a, disabled } : a)) });
+}
+
+/** Delete an account (its sessions stop working at once). */
+export function deleteAccount(id: string): void {
+ const d = read();
+ if (!d.accounts?.some((a) => a.id === id)) throw new AccountError("No such account", 404);
+ write({ ...d, accounts: d.accounts.filter((a) => a.id !== id) });
+}
+
+/** The owner: the install password's session or an API token (everyone while no password is set). */
+export function isOwnerRequest(request: Request, cookie: string | undefined): boolean {
+ return !authEnabled() || validSession(cookie) || validToken(request.headers.get("authorization"));
+}
+
+/** A CSV cell: quoted when it needs to be, and never read as a formula by a spreadsheet. */
+function csvCell(v: string | number | boolean | null): string {
+ let s = v === null ? "" : String(v);
+ if (/^[=+\-@\t\r]/.test(s)) s = `'${s}`;
+ return /[",\n\r]/.test(s) ? `"${s.replaceAll('"', '""')}"` : s;
+}
+
+export function accountsCsv(items = listAccounts()): string {
+ const iso = (t: number | null) => (t ? new Date(t).toISOString() : null);
+ const rows = [["email", "created", "last_login", "gpu_connected", "disabled"], ...items.map((a) => [a.email, iso(a.createdAt), iso(a.lastLoginAt), a.gpu, a.disabled])];
+ return rows.map((r) => r.map(csvCell).join(",")).join("\r\n") + "\r\n";
+}
+
// ---------------------------------------------------------------------------
// Public sign-up: the switch
diff --git a/tests/accounts-admin.test.ts b/tests/accounts-admin.test.ts
new file mode 100644
index 00000000..90caad64
--- /dev/null
+++ b/tests/accounts-admin.test.ts
@@ -0,0 +1,79 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { NextRequest } from "next/server";
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-accounts-admin-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+const auth = await import("@/server/auth");
+const { proxy } = await import("@/proxy");
+afterAll(() => {
+ delete process.env.FUOBE_PUBLIC_SIGNUP;
+ fs.rmSync(dir, { recursive: true, force: true });
+});
+
+const req = (url: string, method = "GET", cookie?: string) =>
+ new NextRequest(`http://localhost:3000${url}`, { method, headers: cookie ? { cookie: `${auth.SESSION_COOKIE}=${cookie}` } : {}, ...(method !== "GET" && { body: "{}" }) });
+
+describe("Settings → Accounts", () => {
+ beforeAll(() => auth.setPassword("install password"));
+
+ it("lists accounts without their hashes, newest first, with last login", () => {
+ const a = auth.createAccount("[email protected]", "long enough");
+ const b = auth.createAccount("[email protected]", "long enough");
+ const list = auth.listAccounts();
+ expect(list.map((x) => x.email).sort()).toEqual(["[email protected]", "[email protected]"]);
+ expect(JSON.stringify(list)).not.toContain(a.hash);
+ expect(list.find((x) => x.id === b.id)).toMatchObject({ disabled: false, gpu: false });
+ expect(list[0].lastLoginAt).toBeGreaterThan(0);
+ const before = auth.listAccounts().find((x) => x.id === a.id)!.lastLoginAt!;
+ auth.recordLogin(a.id);
+ expect(auth.listAccounts().find((x) => x.id === a.id)!.lastLoginAt).toBeGreaterThanOrEqual(before);
+ });
+
+ it("exports CSV that a spreadsheet can't read as a formula", () => {
+ auth.createAccount("[email protected]", "long enough");
+ const csv = auth.accountsCsv();
+ expect(csv.split("\r\n")[0]).toBe("email,created,last_login,gpu_connected,disabled");
+ expect(csv).toContain("'[email protected]");
+ expect(csv).not.toContain("hash");
+ });
+
+ it("switches an account off (signed out, can't log in) and deletes it", () => {
+ const a = auth.createAccount("[email protected]", "long enough");
+ const s = auth.createSession(a.id).value;
+ expect(auth.sessionViewer(s)?.kind).toBe("account");
+ auth.setAccountDisabled(a.id, true);
+ expect(auth.sessionViewer(s)).toBeNull();
+ expect(auth.checkAccount("[email protected]", "long enough")?.disabled).toBe(true);
+ auth.setAccountDisabled(a.id, false);
+ expect(auth.sessionViewer(s)?.kind).toBe("account");
+ auth.deleteAccount(a.id);
+ expect(auth.sessionViewer(s)).toBeNull();
+ expect(auth.listAccounts().some((x) => x.id === a.id)).toBe(false);
+ expect(() => auth.deleteAccount(a.id)).toThrow(/No such account/);
+ });
+
+ it("is the owner's only", () => {
+ const a = auth.createAccount("[email protected]", "long enough");
+ const account = auth.createSession(a.id).value;
+ for (const [m, p] of [
+ ["GET", "/api/admin/accounts"],
+ ["GET", "/api/admin/accounts?format=csv"],
+ ["PATCH", "/api/admin/accounts/x"],
+ ["DELETE", "/api/admin/accounts/x"],
+ ]) {
+ expect(proxy(req(p, m, account)).status, `account ${m} ${p}`).toBe(403);
+ expect(proxy(req(p, m)).status, `guest ${m} ${p}`).toBe(401);
+ }
+ const owner = auth.createSession().value;
+ expect(proxy(req("/api/admin/accounts", "GET", owner)).headers.get("x-middleware-next")).toBe("1");
+ const fake = new Request("http://localhost:3000/api/admin/accounts");
+ expect(auth.isOwnerRequest(fake, owner)).toBe(true);
+ expect(auth.isOwnerRequest(fake, account)).toBe(false);
+ expect(auth.isOwnerRequest(fake, undefined)).toBe(false);
+ });
+});