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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Accounts: change your password in Settings, which signs your other browsers out
Adarshf3db08c4e5bb
diff --git a/docs/public-signup.md b/docs/public-signup.mdindex 82958c99..1931f50a 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -119,6 +119,10 @@ An account can delete itself: `DELETE /api/auth/me` with `{ "password" }`. Whendeleted (by itself or by the owner), its runs are stopped and removed, and its uploads and resultsare deleted with it.+An account changes its password in **Settings → Account**: `PATCH /api/auth/me` with+`{ "current", "next" }` (at least 8 characters, 5 tries a minute). Every other browser signed in to+the account is signed out; the browser that changed it gets a new session.+## Your GPUAn account connects its own ComfyUI in **Settings → Your GPU**, or from the "Connect your GPU" card,diff --git a/src/app/api/auth/me/route.ts b/src/app/api/auth/me/route.tsindex 0efe270d..1ae72966 100644--- a/src/app/api/auth/me/route.ts+++ b/src/app/api/auth/me/route.ts@@ -1,7 +1,7 @@import { cookies } from "next/headers";import { connection } from "next/server";import { z } from "zod";-import { accountGpu, authEnabled, publicSignup, SESSION_COOKIE, sessionCookieOf, sessionViewer, validToken, verifyAccount } from "@/server/auth";+import { AccountError, accountGpu, authEnabled, createSession, publicSignup, SESSION_COOKIE, sessionCookieOf, sessionViewer, setAccountPassword, validToken, verifyAccount } from "@/server/auth";import { runnerFacts } from "@/server/computer/tasks";import { getSetting } from "@/server/settings";import { removeAccount } from "@/server/account-sweep";@@ -48,3 +48,34 @@ export async function DELETE(request: Request) {jar.delete(SESSION_COOKIE);return new Response(null, { status: 204 });}++const NewPassword = z.object({+ current: z.string().max(500),+ next: z.string().min(8, "Use at least 8 characters").max(500, "Use at most 500 characters"),+});++/**+ * An account changes its password (the current one first, to be sure). Its other sign-ins end; this browser gets a new+ * session cookie. Five password checks a minute per account, as for deleting it.+ */+export async function PATCH(request: Request) {+ const jar = await cookies();+ const session = sessionViewer(sessionCookieOf(request));+ if (session?.kind !== "account") return Response.json({ error: "Sign in to change your password" }, { status: 403 });+ const parsed = NewPassword.safeParse(await request.json().catch(() => null));+ if (!parsed.success) {+ const next = parsed.error.issues.find((i) => i.path[0] === "next");+ return Response.json({ error: next?.message ?? "Enter your current password and a new one" }, { status: 400 });+ }+ const rate = hit(`password-me:${session.account.id}`, 5, 60_000);+ if (!rate.ok) return Response.json({ error: "Too many tries. Wait a minute, then try again." }, { status: 429, headers: { "Retry-After": String(rate.retryAfterS) } });+ try {+ await setAccountPassword(session.account.id, parsed.data.current, parsed.data.next);+ } catch (e) {+ if (e instanceof AccountError) return Response.json({ error: e.message }, { status: e.status });+ throw e;+ }+ const s = createSession(session.account.id);+ jar.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/components/gpu/account-gpu-section.tsx b/src/components/gpu/account-gpu-section.tsxindex 6840c78d..f931cb5a 100644--- a/src/components/gpu/account-gpu-section.tsx+++ b/src/components/gpu/account-gpu-section.tsx@@ -1,13 +1,11 @@"use client";-import { LogOut } from "lucide-react";import { ConnectChoice } from "@/components/gpu/connect-choice";-import { Button } from "@/components/ui/button";import { useHydrated, useViewer } from "@/lib/api";/**- * Settings for an account (public sign-up): "Your GPU", at the top of the page, and signing out. Nothing for the owner- * or a guest, and nothing until hydrated: the server's HTML has none.+ * Settings for an account (public sign-up): "Your GPU", at the top of the page (signing out is in Account, below).+ * Nothing for the owner or a guest, and nothing until hydrated: the server's HTML has none.*/export function AccountGpuSection() {const hydrated = useHydrated();@@ -20,19 +18,8 @@ export function AccountGpuSection() {Your GPU</h2><p className="mt-1 text-[13px] text-muted-foreground">- Signed in as {account.email}. Connect your own ComfyUI to run open-source models. The studio's owner can see what you upload and make here.+ Connect your own ComfyUI to run open-source models. The studio's owner can see what you upload and make here.</p>- <Button- size="sm"- variant="ghost"- className="mt-2 -ml-2 h-7 text-muted-foreground"- onClick={async () => {- await fetch("/api/auth/logout", { method: "POST" });- window.location.reload();- }}- >- <LogOut /> Sign out- </Button></div><ConnectChoice /></section>diff --git a/src/components/owner-settings.tsx b/src/components/owner-settings.tsxindex c059949d..c1594ec4 100644--- a/src/components/owner-settings.tsx+++ b/src/components/owner-settings.tsx@@ -1,13 +1,15 @@"use client";-import { Info, Loader2, Scale, Trash2 } from "lucide-react";+import { Eye, EyeOff, Info, KeyRound, Loader2, LogOut, Scale, Trash2 } from "lucide-react";import Link from "next/link";import { useId, useState } from "react";+import { toast } from "sonner";import { Button } from "@/components/ui/button";import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";-import { signInHref, useHydrated, useViewer } from "@/lib/api";+import { signInHref, signOut, useHydrated, useViewer } from "@/lib/api";+import { cn } from "@/lib/utils";/** Settings' line under its title: what this viewer finds on the page. Nothing until the viewer is known (as below). */export function SettingsIntro() {@@ -80,10 +82,14 @@ function Licences() {);}-/** An account's own: deleting it (its password again, DELETE /api/auth/me) takes its runs, files and GPU with it. */+/**+ * An account's own: changing its password, signing out, and deleting it (its password again, DELETE /api/auth/me),+ * which takes its runs, files and GPU with it.+ */function AccountSection({ email }: { email: string }) {const id = useId();const [open, setOpen] = useState(false);+ const [changing, setChanging] = useState(false);const [password, setPassword] = useState("");const [busy, setBusy] = useState(false);const [error, setError] = useState("");@@ -113,12 +119,26 @@ function AccountSection({ email }: { email: string }) {</h2><p className="mt-1 text-[13px] [overflow-wrap:anywhere] text-muted-foreground">{email}</p></div>- <div className="min-w-0 space-y-2">- <p className="max-w-xl text-[13px] text-muted-foreground">Deleting your account removes your uploads, your runs and their files, your GPU connection and your saved fal.ai and Replicate keys, and signs you out. It can't be undone.</p>- <Button size="sm" variant="outline" className="text-destructive" onClick={() => setOpen(true)}>- <Trash2 /> Delete account- </Button>+ <div className="min-w-0 space-y-6">+ <div className="flex flex-wrap gap-2">+ <Button size="sm" variant="secondary" onClick={() => setChanging(true)}>+ <KeyRound /> Change password+ </Button>+ <Button size="sm" variant="ghost" onClick={() => void signOut()}>+ <LogOut /> Sign out+ </Button>+ </div>+ <div className="space-y-2">+ <p className="max-w-xl text-[13px] text-pretty text-muted-foreground">+ Deleting your account removes your uploads, your runs and their files, your GPU connection and your saved fal.ai and Replicate keys, and signs you out. It can't+ be undone.+ </p>+ <Button size="sm" variant="outline" className="text-destructive" onClick={() => setOpen(true)}>+ <Trash2 /> Delete account+ </Button>+ </div></div>+ <ChangePassword open={changing} onOpenChange={setChanging} /><Dialogopen={open}onOpenChange={(o) => {@@ -173,3 +193,130 @@ function AccountSection({ email }: { email: string }) {</section>);}++/** A password field with a button that shows what was typed (as on the sign-in page). */+function PasswordInput({ id, shown, onShow, ...props }: React.ComponentProps<typeof Input> & { id: string; shown: boolean; onShow: () => void }) {+ return (+ <div className="relative">+ <Input id={id} type={shown ? "text" : "password"} className="pr-10" {...props} />+ <button+ type="button"+ onClick={onShow}+ aria-label="Show password"+ aria-pressed={shown}+ aria-controls={id}+ className="absolute top-1/2 right-1 grid size-7 -translate-y-1/2 place-items-center rounded-md text-muted-foreground outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"+ >+ {shown ? <EyeOff className="size-4" /> : <Eye className="size-4" />}+ </button>+ </div>+ );+}++/**+ * Settings → Account → Change password (PATCH /api/auth/me): the current password, then the new one. Every other+ * browser signed in to the account is signed out; this one stays signed in.+ */+function ChangePassword({ open, onOpenChange }: { open: boolean; onOpenChange: (open: boolean) => void }) {+ const id = useId();+ const [current, setCurrent] = useState("");+ const [next, setNext] = useState("");+ const [shown, setShown] = useState(false);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState("");+ const short = next.length > 0 && next.length < 8;+ const reset = () => {+ setCurrent("");+ setNext("");+ setShown(false);+ setError("");+ };+ const save = async (e: React.FormEvent) => {+ e.preventDefault();+ setBusy(true);+ setError("");+ try {+ const res = await fetch("/api/auth/me", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ current, next }) });+ if (res.ok) {+ toast.success("Password changed", { description: "You're still signed in here. Any other browser signed in to your account is signed out." });+ reset();+ onOpenChange(false);+ } else {+ const body = (await res.json().catch(() => ({}))) as { error?: string };+ setError(body.error ?? `The password wasn't changed (${res.status})`);+ }+ } catch {+ setError("The password wasn't changed: the studio didn't answer. Try again.");+ }+ setBusy(false);+ };+ return (+ <Dialog+ open={open}+ onOpenChange={(o) => {+ if (busy) return;+ onOpenChange(o);+ reset();+ }}+ >+ <DialogContent className="sm:max-w-md">+ <form onSubmit={save} className="space-y-4">+ <DialogHeader>+ <DialogTitle>Change your password</DialogTitle>+ <DialogDescription>Any other browser signed in to your account is signed out. You stay signed in here.</DialogDescription>+ </DialogHeader>+ <div className="space-y-1.5">+ <Label htmlFor={`${id}-current`} className="text-[13px]">+ Current password+ </Label>+ <PasswordInput+ id={`${id}-current`}+ shown={shown}+ onShow={() => setShown((s) => !s)}+ autoComplete="current-password"+ value={current}+ onChange={(e) => setCurrent(e.target.value)}+ aria-invalid={!!error}+ aria-describedby={error ? `${id}-error` : undefined}+ autoFocus+ />+ </div>+ <div className="space-y-1.5">+ <Label htmlFor={`${id}-new`} className="text-[13px]">+ New password+ </Label>+ <PasswordInput+ id={`${id}-new`}+ shown={shown}+ onShow={() => setShown((s) => !s)}+ autoComplete="new-password"+ value={next}+ onChange={(e) => setNext(e.target.value)}+ aria-invalid={short}+ aria-describedby={`${id}-hint`}+ />+ <p id={`${id}-hint`} className={cn("text-[12px]", short ? "text-destructive" : "text-muted-foreground")}>+ {short ? `At least 8 characters (${8 - next.length} more)` : "At least 8 characters"}+ </p>+ </div>+ {error && (+ <p id={`${id}-error`} role="alert" className="text-[13px] text-destructive">+ {error}+ </p>+ )}+ <DialogFooter>+ <DialogClose asChild>+ <Button type="button" variant="ghost" disabled={busy}>+ Cancel+ </Button>+ </DialogClose>+ <Button type="submit" disabled={busy || !current || next.length < 8}>+ {busy && <Loader2 className="animate-spin" />}+ Change password+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/src/server/auth.ts b/src/server/auth.tsindex 580e1d84..78370c7c 100644--- a/src/server/auth.ts+++ b/src/server/auth.ts@@ -66,6 +66,8 @@ export interface Account {/** scrypt hash of the password ("salt:hash", hex), as the install password's. */hash: string;createdAt: number;+ /** When the account last changed its password (Settings → Account): its sign-ins from before then were ended. */+ passwordChangedAt?: number;/** The last sign-up or log-in. */lastLoginAt?: number;/** Switched off by the owner (Settings → Accounts): signed out, and can't log in. */@@ -212,14 +214,16 @@ export function setPassword(pw: string | null): void {const sign = (secret: string, payload: string) => crypto.createHmac("sha256", secret).update(payload).digest("base64url");+const fingerprint = (s: string) => crypto.createHash("sha256").update(s).digest("hex");+/**- * 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.+ * The key a session is signed with: the secret and a password's fingerprint. The owner's password (FUOBE_PASSWORD, or+ * the Settings one): a new one (after a restart, or in Settings) ends every owner sign-in at once, and the secret alone+ * (auth.json) can't make an owner cookie. An account's own password hash: its new password ends its other sign-ins,+ * and the owner's new password signs no 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")}`;+function keyFor(d: AuthFile, who: "owner" | Pick<Account, "hash">): string {+ return `${d.secret}.${fingerprint(who === "owner" ? envPassword() || d.password || "" : who.hash)}`;}/**@@ -234,9 +238,18 @@ 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(keyFor(d, !accountId), payload)}`, maxAge: SESSION_DAYS * 86_400 };+ // An account that isn't there gets a cookie nothing takes (sessionViewer finds no account for it).+ const who = accountId ? { hash: d.accounts?.find((a) => a.id === accountId)?.hash ?? "" } : "owner";+ return { value: `${payload}.${sign(keyFor(d, who), payload)}`, maxAge: SESSION_DAYS * 86_400 };}+/**+ * An account cookie made before account keys held the password's fingerprint was signed with the secret alone. It is+ * still taken (it ends with its 30 days, so a deploy signs nobody out) until the account first changes its password.+ */+const legacyAccountMac = (d: AuthFile, account: Account, payload: string, mac: string) =>+ !account.passwordChangedAt && same(Buffer.from(mac), Buffer.from(sign(d.secret, payload)));+/** Who a session cookie belongs to: the owner, an account that still exists, or nobody. */export type Viewer = { kind: "owner" } | { kind: "account"; account: Account };@@ -258,12 +271,16 @@ 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(keyFor(d, parts.length === 2), parts.slice(0, -1).join("."))))) return null;+ const payload = parts.slice(0, -1).join(".");+ // An account's key holds its password's fingerprint: the account comes first.+ const account = parts.length === 3 ? d.accounts?.find((a) => a.id === parts[1]) : undefined;+ if (parts.length === 3 && !account) return null;+ const signed = same(Buffer.from(mac), Buffer.from(sign(keyFor(d, account ?? "owner"), payload)));+ if (!signed && !(account && legacyAccountMac(d, account, payload, mac))) return null;// Signed out with Sign out: a copy of the cookie (another tab's, a stolen one) is refused too.if (d.signedOut?.length && d.signedOut.some((s) => s.hash === cookieHash(value))) 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;+ if (!account) return { kind: "owner" };+ return account.disabled ? null : { kind: "account", account };}const cookieHash = (value: string) => crypto.createHash("sha256").update(value).digest("hex");@@ -351,6 +368,25 @@ export async function verifyAccount(email: string, password: string): Promise<Acreturn account && ok ? account : null;}+/**+ * An account changes its own password (Settings → Account): the current one first. A new hash changes the account's+ * session key (keyFor), so every sign-in it had ends, this browser's too: the caller gives this browser a new cookie.+ */+export async function setAccountPassword(id: string, current: string, next: string): Promise<Account> {+ if (next.length < 8) throw new AccountError("Use at least 8 characters", 400);+ const account = accountById(id);+ if (!account) throw new AccountError("No such account", 404);+ if (!(await verifyAccount(account.email, current))) throw new AccountError("The current password is wrong", 403);+ const salt = crypto.randomBytes(16);+ const hash = `${salt.toString("hex")}:${(await scrypt(next, salt)).toString("hex")}`;+ // Read again: the file may have changed while the passwords were hashed.+ const d = read();+ if (!d.accounts?.some((a) => a.id === id)) throw new AccountError("No such account", 404);+ const changed = { hash, passwordChangedAt: Date.now() };+ write({ ...d, accounts: d.accounts.map((a) => (a.id === id ? { ...a, ...changed } : a)) });+ return { ...account, ...changed };+}+/** How often a log-in is written down: each write rewrites the whole accounts file. */const LOGIN_RECORD_MS = 60 * 60_000;diff --git a/tests/public-signup.test.ts b/tests/public-signup.test.tsindex a8182420..a8991033 100644--- a/tests/public-signup.test.ts+++ b/tests/public-signup.test.ts@@ -1,3 +1,4 @@+import crypto from "node:crypto";import fs from "node:fs";import os from "node:os";import path from "node:path";@@ -5,6 +6,9 @@ import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitestimport { NextRequest } from "next/server";// Route handlers call connection(); outside a request scope it would throw.vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));+// Route handlers set the session cookie through cookies() (no request scope in a test): a jar that only records.+const jar = vi.hoisted(() => ({ set: vi.fn(), delete: vi.fn(), get: vi.fn() }));+vi.mock("next/headers", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/headers")>()), cookies: async () => jar }));const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-signup-"));process.env.FUOBE_DATA_DIR = dir;@@ -408,3 +412,73 @@ describe("one reading of the session cookie (audit: proxy and routes must agreeexpect(run.status).toBe(401);});});++describe("an account changes its password (Settings → Account)", () => {+ const me = () => import("@/app/api/auth/me/route");+ const patch = (cookie: string, body: unknown) =>+ new Request("http://localhost:3000/api/auth/me", {+ method: "PATCH",+ headers: { "content-type": "application/json", cookie: `${auth.SESSION_COOKIE}=${cookie}` },+ body: JSON.stringify(body),+ });+ const secret = () => (JSON.parse(fs.readFileSync(path.join(dir, "auth.json"), "utf8")) as { secret: string }).secret;+ /** An account cookie signed with the secret alone, as before account keys held the password's fingerprint. */+ const legacy = (id: string) => {+ const payload = `${Date.now() + 86_400_000}.${id}`;+ return `${payload}.${crypto.createHmac("sha256", secret()).update(payload).digest("base64url")}`;+ };+ afterEach(() => jar.set.mockClear());++ it("needs the current password, ends every other sign-in, and keeps this browser signed in", async () => {+ const a = auth.createAccount("[email protected]", "first password");+ const here = auth.createSession(a.id).value;+ const elsewhere = auth.createSession(a.id).value;+ const old = legacy(a.id);+ const owner = auth.createSession().value;+ // A cookie from before this change still works, until the account changes its password.+ expect(auth.sessionViewer(old)?.kind).toBe("account");++ const wrong = await (await me()).PATCH(patch(here, { current: "not my password", next: "second password" }));+ expect(wrong.status).toBe(403);+ expect((await wrong.json()).error).toMatch(/current password is wrong/);+ const short = await (await me()).PATCH(patch(here, { current: "first password", next: "short" }));+ expect(short.status).toBe(400);+ expect((await short.json()).error).toMatch(/8 characters/);+ expect(auth.sessionViewer(here)?.kind).toBe("account");+ expect(jar.set).not.toHaveBeenCalled();++ const ok = await (await me()).PATCH(patch(here, { current: "first password", next: "second password" }));+ expect(ok.status).toBe(200);+ // Every cookie the account had is refused now: this browser's old one, another browser's, one from before.+ for (const cookie of [here, elsewhere, old]) expect(auth.sessionViewer(cookie)).toBeNull();+ // This browser has a new one, which works.+ expect(jar.set).toHaveBeenCalledWith(auth.SESSION_COOKIE, expect.any(String), expect.objectContaining({ httpOnly: true, path: "/" }));+ const fresh = jar.set.mock.calls[0][1] as string;+ expect(auth.sessionViewer(fresh)).toMatchObject({ kind: "account", account: { id: a.id } });+ expect(legacy(a.id)).not.toBe(fresh);+ expect(auth.sessionViewer(legacy(a.id))).toBeNull();+ // The new password logs in, the old one doesn't, and the owner is still signed in.+ expect(auth.checkAccount("[email protected]", "second password")?.id).toBe(a.id);+ expect(auth.checkAccount("[email protected]", "first password")).toBeNull();+ expect(auth.validSession(owner)).toBe(true);+ // The old cookie can't try again.+ expect((await (await me()).PATCH(patch(here, { current: "second password", next: "third password" }))).status).toBe(403);+ });++ it("allows five tries a minute, then answers 429", async () => {+ const a = auth.createAccount("[email protected]", "the real one");+ const cookie = auth.createSession(a.id).value;+ for (let i = 0; i < 5; i++) expect((await (await me()).PATCH(patch(cookie, { current: `guess ${i}`, next: "a new password" }))).status).toBe(403);+ const sixth = await (await me()).PATCH(patch(cookie, { current: "the real one", next: "a new password" }));+ expect(sixth.status).toBe(429);+ expect(sixth.headers.get("retry-after")).toMatch(/^\d+$/);+ expect(auth.checkAccount("[email protected]", "the real one")?.id).toBe(a.id);+ });++ it("refuses a guest and the owner: it's an account's own password", async () => {+ const owner = auth.createSession().value;+ expect((await (await me()).PATCH(patch(owner, { current: "install password", next: "a new password" }))).status).toBe(403);+ expect((await (await me()).PATCH(patch("", { current: "x", next: "a new password" }))).status).toBe(403);+ expect(auth.checkPassword("install password")).toBe(true);+ });+});