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
Public sign-up: guest browsing, email accounts, owner-only settings
Adarsh915110c15e29
diff --git a/docs/public-signup.md b/docs/public-signup.mdnew file mode 100644index 00000000..c3783ddb--- /dev/null+++ b/docs/public-signup.md@@ -0,0 +1,65 @@+# Public sign-up and guest browsing++A Fuobe studio with a password can open itself a little to the public: signed-out visitors (guests)+browse it read-only, and anyone can make a free account. It is off by default, so a self-hosted+studio behaves as before: every page and API call needs the install password or an API token.++## Turning it on++Public sign-up works only on a studio that has a password (`FUOBE_PASSWORD` or **Settings →+Security**). Then it is on when one of these is true:++- `FUOBE_PUBLIC_SIGNUP=1` is set on the server. `FUOBE_PUBLIC_SIGNUP=0` keeps it off, whatever+ Settings says. While the variable is set, the Settings switch can't change it.+- The owner turns on **Settings → Security → Public sign-up**.+- The request is for `fuobe.com` or `www.fuobe.com` (the public demo), the server lists that name in+ `FUOBE_ALLOWED_ORIGINS`, and `FUOBE_PUBLIC_SIGNUP` is not `0`. The `Host` header comes from the+ client, so a self-hosted studio that someone reaches by its IP address can't be opened with+ `Host: fuobe.com`.++Turning it off signs out every account at once, and guests are sent to sign in again.++## Guests++A guest can open every page: galleries, presets, the studios, Layers, Cinema, Image to 3D and+Settings, read-only. The pages get the catalog and status reads they need (`/api/status`,+`/api/models`, `/api/search-index`, `/api/comfyui`, `/api/settings/models`, curated moodboards,+built-in skills). The owner's library stays private: the lists come back empty, and other reads of+it (files, uploads, projects, settings values, tokens) answer 401 "Sign up to see your library".++Every change a guest sends (generate, upload, save a setting, create a project…) answers 401. The+studio shows a "Create a free account to run this" card with **Sign up** and **Log in**. Price+checks (the estimate routes, and `?preview=1` on the run routes that support it) stay open, so the+studios can show prices.++## Accounts++- Sign up at `/login?signup=1` (`POST /api/auth/signup` with `{ "email", "password" }`). The+ password needs at least 8 characters. There is no email verification.+- Log in at `/login` (`POST /api/auth/login` with `{ "email", "password" }`). The install password+ still works as before: `POST /api/auth/login` with `{ "password" }`, or **Studio owner** on the+ login page.+- Accounts are stored in `auth.json` in the data folder: the email in lower case, a salted scrypt+ hash of the password (the same scheme as the install password), and the creation time.+- Sign-up and log-in attempts are rate limited per visitor (set `FUOBE_TRUST_PROXY=1` behind a+ reverse proxy, so that each visitor gets their own limit).++An account's session works across the studio, with two limits:++- **Settings, keys and tokens are the owner's.** Changing settings or model switches, the password,+ API tokens, Public sign-up, LoRA downloads, Assist connectors and the MCP endpoint answer 403 for+ an account.+- **Accounts never run on the owner's keys or GPU.** Anything that would reach a model (a+ 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. An+ account can still upload, organise, share and delete in the library, and create and edit+ projects.++Accounts share the studio's one library: an account sees the owner's results and can change them.+Use public sign-up on a studio whose library you are happy to show.++`GET /api/auth/me` (open to everyone) says who is looking: `{ signedIn, owner, publicSignup,+account? }`.++The rules are in `src/lib/guest-access.ts` (which paths guests and accounts may use) and+`src/proxy.ts` (where they are applied). The tests are in `tests/public-signup.test.ts`.diff --git a/src/app/api/assist/skills/route.ts b/src/app/api/assist/skills/route.tsindex 48e34368..4ac33d75 100644--- a/src/app/api/assist/skills/route.ts+++ b/src/app/api/assist/skills/route.ts@@ -1,11 +1,13 @@import { connection } from "next/server";+import { isGuest } from "@/lib/guest-access";import { SkillBody } from "@/server/assist/schemas";import { createSkill, listSkills, SkillError } from "@/server/skills";/** Every skill: built-in (from skills/) and the user's own. */-export async function GET() {+export async function GET(request: Request) {await connection();- return Response.json({ items: listSkills() });+ // A guest (public sign-up) sees the built-in skills, not the owner's own.+ return Response.json({ items: isGuest(request) ? listSkills().filter((s) => s.source === "builtin") : listSkills() });}/** Create a skill from the form (name, title, description, when to use, instructions). */diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.tsindex 99c7da90..b87bf2ee 100644--- a/src/app/api/auth/login/route.ts+++ b/src/app/api/auth/login/route.ts@@ -1,8 +1,9 @@import { cookies } from "next/headers";import { z } from "zod";-import { authEnabled, checkPassword, createSession, LoginGuard, SESSION_COOKIE } from "@/server/auth";+import { authEnabled, checkAccount, checkPassword, createSession, LoginGuard, publicSignup, SESSION_COOKIE } from "@/server/auth";-const Body = z.object({ password: z.string().min(1).max(500) });+/** 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() });declare global {var __fuobeLoginGuard: LoginGuard | undefined;@@ -23,12 +24,21 @@ export async function POST(request: Request) {);}const parsed = Body.safeParse(await request.json().catch(() => null));- if (!parsed.success || !checkPassword(parsed.data.password)) {+ const email = parsed.success ? parsed.data.email?.trim() : undefined;+ let accountId: string | undefined;+ if (email) {+ const account = parsed.success && publicSignup(request.headers.get("host")) ? checkAccount(email, parsed.data.password) : null;+ if (!account) {+ guard.fail(key);+ return Response.json({ error: "Wrong email or password" }, { status: 401 });+ }+ accountId = account.id;+ } else if (!parsed.success || !checkPassword(parsed.data.password)) {guard.fail(key);return Response.json({ error: "Wrong password" }, { status: 401 });}guard.succeed(key);- const s = createSession();+ const s = createSession(accountId);(await cookies()).set(SESSION_COOKIE, s.value, {httpOnly: true,sameSite: "lax",diff --git a/src/app/api/auth/me/route.ts b/src/app/api/auth/me/route.tsnew file mode 100644index 00000000..e5290d01--- /dev/null+++ b/src/app/api/auth/me/route.ts@@ -0,0 +1,21 @@+import { cookies } from "next/headers";+import { connection } from "next/server";+import { authEnabled, 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) {+ await connection();+ const open = publicSignup(request.headers.get("host"));+ const session = sessionViewer((await cookies()).get(SESSION_COOKIE)?.value);+ const owner = !authEnabled() || session?.kind === "owner" || validToken(request.headers.get("authorization"));+ const account = !owner && open && session?.kind === "account" ? session.account : null;+ return Response.json(+ {+ signedIn: owner || !!account,+ owner,+ publicSignup: open,+ ...(account && { account: { email: account.email } }),+ },+ { headers: { "Cache-Control": "no-store" } },+ );+}diff --git a/src/app/api/auth/public/route.ts b/src/app/api/auth/public/route.tsnew file mode 100644index 00000000..4ebf01b8--- /dev/null+++ b/src/app/api/auth/public/route.ts@@ -0,0 +1,33 @@+import { cookies } from "next/headers";+import { connection } from "next/server";+import { z } from "zod";+import { authEnabled, publicSignup, publicSignupFromEnv, publicSignupSetting, SESSION_COOKIE, setPublicSignup, validSession } from "@/server/auth";++const status = (request: Request) => ({+ /** The Settings switch. */+ setting: publicSignupSetting(),+ /** FUOBE_PUBLIC_SIGNUP when set (then the switch does nothing). */+ fromEnv: publicSignupFromEnv(),+ /** On for this address right now. */+ active: publicSignup(request.headers.get("host")),+});++/** Settings → Security: public sign-up (guests browse read-only, anyone can make an account). */+export async function GET(request: Request) {+ await connection();+ return Response.json(status(request));+}++/** Switch it on or off: the owner, from a signed-in browser. */+export async function PUT(request: Request) {+ if (!authEnabled()) return Response.json({ error: "Set a password first: without one the studio is open to everyone who can reach it" }, { status: 400 });+ if (!validSession((await cookies()).get(SESSION_COOKIE)?.value)) return Response.json({ error: "Change this from the owner's signed-in browser" }, { status: 403 });+ const parsed = z.object({ on: z.boolean() }).safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: "Send { on: true } or { on: false }" }, { status: 400 });+ try {+ setPublicSignup(parsed.data.on);+ } catch (e) {+ return Response.json({ error: (e as Error).message }, { status: 400 });+ }+ return Response.json(status(request));+}diff --git a/src/app/api/auth/signup/route.ts b/src/app/api/auth/signup/route.tsnew file mode 100644index 00000000..e7d51edf--- /dev/null+++ b/src/app/api/auth/signup/route.ts@@ -0,0 +1,41 @@+import { cookies } from "next/headers";+import { z } from "zod";+import { AccountError, createAccount, createSession, LoginGuard, publicSignup, SESSION_COOKIE } from "@/server/auth";++const Body = z.object({ email: z.string().max(254), password: z.string().max(500) });++declare global {+ var __fuobeSignupGuard: LoginGuard | undefined;+}+/** Every sign-up counts, made or not: a client makes at most 5 a minute, and everyone slows down past 20. */+const guard = (globalThis.__fuobeSignupGuard ??= new LoginGuard());++/** Public sign-up: an account from an email and a password (8+ characters, no verification), signed in at once. */+export async function POST(request: Request) {+ if (!publicSignup(request.headers.get("host"))) return Response.json({ error: "Sign-up is off on this studio" }, { status: 404 });+ const key = LoginGuard.clientKey(request.headers);+ const wait = guard.blockedFor(key);+ if (wait > 0) {+ const secs = Math.ceil(wait / 1000);+ return Response.json({ error: `Too many sign-ups. Try again in ${secs} second${secs === 1 ? "" : "s"}.` }, { status: 429, headers: { "Retry-After": String(secs) } });+ }+ guard.fail(key);+ const parsed = Body.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: "Enter an email and a password" }, { status: 400 });+ let account;+ try {+ account = createAccount(parsed.data.email, parsed.data.password);+ } catch (e) {+ if (e instanceof AccountError) return Response.json({ error: e.message }, { status: e.status });+ throw e;+ }+ const s = createSession(account.id);+ (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, email: account.email }, { status: 201 });+}diff --git a/src/app/api/moodboards/route.ts b/src/app/api/moodboards/route.tsindex f9d03769..0ab81cb1 100644--- a/src/app/api/moodboards/route.ts+++ b/src/app/api/moodboards/route.ts@@ -1,4 +1,5 @@import { connection } from "next/server";+import { isGuest } from "@/lib/guest-access";import { z } from "zod";import { createMoodboard, curatedMoodboards, listMoodboards } from "@/server/moodboards";@@ -10,9 +11,10 @@ const Body = z.object({});/** Your moodboards (each one's status follows its cover job) and Soul 2.0's curated looks. */-export async function GET() {+export async function GET(request: Request) {await connection();- return Response.json({ items: listMoodboards(), curated: curatedMoodboards() });+ // A guest (public sign-up) sees the curated looks, not the owner's boards.+ return Response.json({ items: isGuest(request) ? [] : listMoodboards(), curated: curatedMoodboards() });}export async function POST(request: Request) {diff --git a/src/app/api/palettes/route.ts b/src/app/api/palettes/route.tsindex d647574e..627ec9a0 100644--- a/src/app/api/palettes/route.ts+++ b/src/app/api/palettes/route.ts@@ -1,4 +1,5 @@import { connection } from "next/server";+import { isGuest } from "@/lib/guest-access";import { z } from "zod";import { createPalette, listPalettes, signatureCaps } from "@/server/palettes";@@ -11,9 +12,9 @@ const Body = z.object({});/** Your colour signatures and the 50 built-in palettes, plus which models take a palette natively. */-export async function GET() {+export async function GET(request: Request) {await connection();- return Response.json({ items: listPalettes(), caps: signatureCaps() });+ return Response.json({ items: isGuest(request) ? [] : listPalettes(), caps: signatureCaps() });}export async function POST(request: Request) {diff --git a/src/app/providers.tsx b/src/app/providers.tsxindex f38c2433..ce7f69ae 100644--- a/src/app/providers.tsx+++ b/src/app/providers.tsx@@ -3,6 +3,7 @@import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { ThemeProvider } from "next-themes";import { useState } from "react";+import { GuestPrompt } from "@/components/guest-prompt";import { Toaster } from "@/components/ui/sonner";import { TooltipProvider } from "@/components/ui/tooltip";@@ -16,6 +17,7 @@ export function Providers({ children }: { children: React.ReactNode }) {<TooltipProvider delayDuration={300}>{children}<Toaster position="top-center" gap={8} offset={29} />+ <GuestPrompt /></TooltipProvider></QueryClientProvider></ThemeProvider>diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsxindex 257de088..91fc16c0 100644--- a/src/components/app-sidebar.tsx+++ b/src/components/app-sidebar.tsx@@ -4,7 +4,7 @@ import { useLinkStatus } from "next/link";import { usePathname, useSearchParams } from "next/navigation";import { useTheme } from "next-themes";import { Fragment, Suspense, useCallback, useEffect, useRef, useState } from "react";-import { ChevronRight, Clapperboard, Moon, Plus, Search, Sun, X } from "lucide-react";+import { ChevronRight, Clapperboard, LogIn, Moon, Plus, Search, Sun, UserPlus, X } from "lucide-react";import {Sidebar,SidebarContent,@@ -29,7 +29,7 @@ import { IntentLink } from "@/components/intent-link";import { JobNotifications } from "@/components/job-notifications";import { NAV, type NavGroupDef } from "@/components/nav-items";import { SkillBuilderProvider } from "@/components/skills/skill-builder-provider";-import { useEngineMode, useStatus } from "@/lib/api";+import { signInHref, useEngineMode, useIsGuest, useStatus } from "@/lib/api";import { useModKey } from "@/lib/keys";import { fullScreenStudio, groupId, NAV_CLOSED_KEY, navActive, parseClosed, sidebarCookie, SIDEBAR_STATE_SCRIPT, sidebarOpenFromCookie } from "@/lib/nav";import { cn } from "@/lib/utils";@@ -309,6 +309,29 @@ function SearchRow() {);}+/** Public sign-up, signed out: "Sign up" and "Log in", coming back to this page. */+function GuestRow() {+ const guest = useIsGuest();+ const pathname = usePathname();+ if (!guest) return null;+ return (+ <SidebarMenuItem className="mt-1 flex gap-1.5 group-data-[collapsible=icon]:flex-col">+ <SidebarMenuButton asChild tooltip="Sign up free" className="h-8 flex-1 justify-center bg-primary text-[13px] text-primary-foreground hover:bg-primary/90 hover:text-primary-foreground">+ <a href={signInHref("signup", pathname)}>+ <UserPlus />+ <span>Sign up</span>+ </a>+ </SidebarMenuButton>+ <SidebarMenuButton asChild tooltip="Log in" className="h-8 flex-1 justify-center border border-sidebar-border text-[13px]">+ <a href={signInHref("login", pathname)}>+ <LogIn />+ <span>Log in</span>+ </a>+ </SidebarMenuButton>+ </SidebarMenuItem>+ );+}+/** The GitHub mark (lucide has no brand icons). */function GitHubMark() {return (@@ -364,6 +387,7 @@ export function AppSidebar() {)}</div><SidebarMenu>+ <GuestRow /><SearchRow /><SidebarMenuItem><SidebarMenuButton asChild tooltip="New creation" className="h-8 text-[13px] has-[[data-pending]]:bg-sidebar-accent">diff --git a/src/components/guest-prompt.tsx b/src/components/guest-prompt.tsxnew file mode 100644index 00000000..f2f092ec--- /dev/null+++ b/src/components/guest-prompt.tsx@@ -0,0 +1,76 @@+"use client";++import { Cpu, Sparkles } from "lucide-react";+import Link from "next/link";+import { useEffect, useState } from "react";+import { Button } from "@/components/ui/button";+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { CONNECT_GPU_EVENT, GUEST_PROMPT_EVENT, signInHref, watchGuestRefusals } from "@/lib/api";++type Prompt = { kind: "guest"; here: string } | { kind: "gpu" };++/**+ * The cards a public studio shows when something is refused (watchGuestRefusals): "Create a free+ * account to run this" for a guest (public sign-up, signed out) who tries to generate, upload or+ * change anything, and "Connect your GPU to run this" for an account (accounts run only on their+ * own ComfyUI, never the owner's keys or GPU). Mounted once, in the app's providers.+ */+export function GuestPrompt() {+ const [prompt, setPrompt] = useState<Prompt | null>(null);+ useEffect(() => {+ watchGuestRefusals();+ const guest = () => setPrompt({ kind: "guest", here: window.location.pathname + window.location.search });+ const gpu = () => setPrompt({ kind: "gpu" });+ window.addEventListener(GUEST_PROMPT_EVENT, guest);+ window.addEventListener(CONNECT_GPU_EVENT, gpu);+ return () => {+ window.removeEventListener(GUEST_PROMPT_EVENT, guest);+ window.removeEventListener(CONNECT_GPU_EVENT, gpu);+ };+ }, []);+ return (+ <Dialog open={prompt !== null} onOpenChange={(o) => !o && setPrompt(null)}>+ <DialogContent className="sm:max-w-sm">+ {prompt?.kind === "gpu" ? (+ <>+ <DialogHeader>+ <div className="mb-1 grid size-10 place-items-center rounded-xl bg-primary text-primary-foreground">+ <Cpu className="size-5" />+ </div>+ <DialogTitle>Connect your GPU to run this</DialogTitle>+ <DialogDescription>+ Free accounts run on their own ComfyUI, never on this studio's keys or GPU. Your ComfyUI must be reachable from the internet, for example through a Cloudflare+ Tunnel or ngrok. Or run Fuobe on your own computer: it's open source.+ </DialogDescription>+ </DialogHeader>+ <DialogFooter className="gap-2 sm:justify-start">+ <Button asChild variant="secondary">+ <a href="https://github.com/workingprototype/fuobe" target="_blank" rel="noreferrer">+ Get Fuobe+ </a>+ </Button>+ </DialogFooter>+ </>+ ) : (+ <>+ <DialogHeader>+ <div className="mb-1 grid size-10 place-items-center rounded-xl bg-primary text-primary-foreground">+ <Sparkles className="size-5" />+ </div>+ <DialogTitle>Create a free account to run this</DialogTitle>+ <DialogDescription>You're browsing as a guest. Sign up with an email and a password to generate, upload and keep your work.</DialogDescription>+ </DialogHeader>+ <DialogFooter className="gap-2 sm:justify-start">+ <Button asChild>+ <Link href={signInHref("signup", prompt?.here)}>Sign up free</Link>+ </Button>+ <Button asChild variant="secondary">+ <Link href={signInHref("login", prompt?.here)}>Log in</Link>+ </Button>+ </DialogFooter>+ </>+ )}+ </DialogContent>+ </Dialog>+ );+}diff --git a/src/components/login-form.tsx b/src/components/login-form.tsxindex a93b01b8..a7c1fa3a 100644--- a/src/components/login-form.tsx+++ b/src/components/login-form.tsx@@ -1,23 +1,47 @@"use client";-import { Loader2, Lock } from "lucide-react";+import { Loader2, Lock, Sparkles } from "lucide-react";+import Link from "next/link";import { useSearchParams } from "next/navigation";import { useState } from "react";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";+import { useViewer } from "@/lib/api";import { safeNext } from "@/lib/safe-redirect";+/** "signup" and "login" are accounts (public sign-up); "owner" is the install password. */+type Mode = "signup" | "login" | "owner";++const COPY: Record<Mode, { title: string; lead: string; button: string }> = {+ signup: { title: "Create your free account", lead: "An email and a password, and you're in. No verification.", button: "Sign up" },+ login: { title: "Welcome back", lead: "Log in with your email and password.", button: "Log in" },+ owner: { title: "Welcome back", lead: "This Fuobe studio is password protected.", button: "Sign in" },+};+export function LoginForm() {const params = useSearchParams();+ const viewer = useViewer();+ const open = !!viewer.data?.publicSignup;+ const [chosen, setChosen] = useState<Mode | null>(null);+ const mode: Mode = !open ? "owner" : (chosen ?? (params.get("signup") === "1" ? "signup" : "login"));+ const [email, setEmail] = useState("");const [password, setPassword] = useState("");const [error, setError] = useState<string | null>(null);const [busy, setBusy] = useState(false);+ const next = safeNext(params.get("next"), typeof window === "undefined" ? "http://localhost" : window.location.origin);++ const choose = (m: Mode) => {+ setChosen(m);+ setError(null);+ };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 }) });+ const url = mode === "signup" ? "/api/auth/signup" : "/api/auth/login";+ const body = mode === "owner" ? { password } : { email, password };+ const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });if (res.ok) {// Only a page on this site: never bounce to another origin after signing in.window.location.assign(safeNext(params.get("next"), window.location.origin));@@ -27,27 +51,81 @@ export function LoginForm() {setBusy(false);};+ if (viewer.isPending) {+ return (+ <div className="grid h-72 w-full max-w-sm place-items-center rounded-2xl border bg-background shadow-soft">+ <Loader2 className="size-5 animate-spin text-muted-foreground" />+ </div>+ );+ }++ const copy = COPY[mode];+ const short = mode === "signup" && password.length > 0 && password.length < 8;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" />+ {mode === "signup" ? <Sparkles className="size-5" /> : <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>+ <h1 className="font-heading text-[28px] leading-tight">{copy.title}</h1>+ <p className="mt-1 text-[13px] text-muted-foreground">{copy.lead}</p>+ {mode !== "owner" && (+ <Input+ type="email"+ autoFocus+ autoComplete="email"+ placeholder="Email"+ value={email}+ onChange={(e) => setEmail(e.target.value)}+ className="mt-5 h-11"+ aria-invalid={!!error}+ />+ )}<Inputtype="password"- autoFocus- autoComplete="current-password"- placeholder="Password"+ autoFocus={mode === "owner"}+ autoComplete={mode === "signup" ? "new-password" : "current-password"}+ placeholder={mode === "signup" ? "Password (at least 8 characters)" : "Password"}value={password}onChange={(e) => setPassword(e.target.value)}- className="mt-5 h-11"- aria-invalid={!!error}+ className={mode === "owner" ? "mt-5 h-11" : "mt-2.5 h-11"}+ aria-invalid={!!error || short}/>{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 type="submit" className="mt-4 h-11 w-full" disabled={!password || (mode !== "owner" && !email) || (mode === "signup" && password.length < 8) || busy}>+ {busy && <Loader2 className="animate-spin" />} {copy.button}</Button>+ {open && (+ <div className="mt-4 space-y-1.5 text-center text-[13px] text-muted-foreground">+ {mode === "signup" ? (+ <p>+ Have an account?{" "}+ <button type="button" className="font-medium text-foreground underline-offset-4 hover:underline" onClick={() => choose("login")}>+ Log in+ </button>+ </p>+ ) : (+ <p>+ New here?{" "}+ <button type="button" className="font-medium text-foreground underline-offset-4 hover:underline" onClick={() => choose("signup")}>+ Create a free account+ </button>+ </p>+ )}+ <p>+ <Link href={next} className="underline-offset-4 hover:underline">+ Keep browsing as a guest+ </Link>+ {mode !== "owner" && (+ <>+ {" · "}+ <button type="button" className="underline-offset-4 hover:underline" onClick={() => choose("owner")}>+ Studio owner+ </button>+ </>+ )}+ </p>+ </div>+ )}</form>);}diff --git a/src/components/security-settings.tsx b/src/components/security-settings.tsxindex 5b9a4677..fbfc8dd1 100644--- a/src/components/security-settings.tsx+++ b/src/components/security-settings.tsx@@ -8,6 +8,7 @@ import { toast } from "sonner";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";+import { Switch } from "@/components/ui/switch";import { copyWithToast } from "@/lib/clipboard";import { timeAgo } from "@/lib/format";@@ -194,11 +195,55 @@ function Tokens({ status, onChange }: { status: AuthStatus; onChange: () => void);}+interface PublicSignupStatus {+ setting: boolean;+ fromEnv: boolean | null;+ active: boolean;+}++/** Public sign-up: guests browse read-only, and anyone can make an account (that runs on its own GPU). */+function PublicSignup() {+ const qc = useQueryClient();+ const id = useId();+ const q = useQuery({ queryKey: ["auth", "public"], queryFn: () => call<PublicSignupStatus>("/api/auth/public", "GET") });+ const [busy, setBusy] = useState(false);+ if (!q.data) return null;+ const p = q.data;+ const set = async (on: boolean) => {+ setBusy(true);+ try {+ qc.setQueryData(["auth", "public"], await call<PublicSignupStatus>("/api/auth/public", "PUT", { on }));+ void qc.invalidateQueries({ queryKey: ["viewer"] });+ } catch (e) {+ toast.error((e as Error).message);+ } finally {+ setBusy(false);+ }+ };+ return (+ <div className="space-y-1.5 sm:w-[36rem] sm:max-w-full">+ <div className="flex items-center gap-3">+ <Label htmlFor={`${id}-public`} className="flex-1 text-[13px] font-medium">+ Public sign-up+ </Label>+ <Switch id={`${id}-public`} checked={p.fromEnv ?? p.setting} disabled={busy || p.fromEnv !== null} onCheckedChange={(on) => void set(on)} />+ </div>+ <p className="text-[12px] text-muted-foreground">+ Guests can browse every page read-only (not your library), and anyone can sign up with an email and a password. Accounts never use your cloud keys or GPU, and+ can't change settings, keys or tokens.+ {p.fromEnv !== null && " Set by FUOBE_PUBLIC_SIGNUP on the server."}+ {p.active && !(p.fromEnv ?? p.setting) && " On for this address (fuobe.com)."}+ </p>+ </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.isError) return <p className="text-[13px] text-muted-foreground">{status.error.message} Only the studio's owner sees these settings.</p>;if (!status.data) return <Loader2 className="size-5 animate-spin text-muted-foreground" />;const s = status.data;return (@@ -226,6 +271,7 @@ export function SecuritySettings() {</div>)}{!s.fromEnv && <PasswordForm status={s} onDone={refresh} />}+ {s.enabled && <PublicSignup />}<Tokens status={s} onChange={refresh} /></div>);diff --git a/src/lib/api.ts b/src/lib/api.tsindex d78a1a01..854a9e0d 100644--- a/src/lib/api.ts+++ b/src/lib/api.ts@@ -1047,3 +1047,63 @@ export function useAssistActions() {},};}++// ---------------------------------------------------------------------------+// Who is looking (public sign-up: GET /api/auth/me)++export interface ViewerInfo {+ signedIn: boolean;+ /** The install password's session or an API token (also everyone while no password is set). */+ owner: boolean;+ /** Guests may browse and anyone may sign up. */+ publicSignup: boolean;+ account?: { email: string };+}++export function useViewer() {+ return useQuery({+ queryKey: ["viewer"],+ queryFn: async () => json<ViewerInfo>(await fetch("/api/auth/me")),+ staleTime: 60_000,+ });+}++/** A guest browsing a public studio: signed out while sign-up is open. */+export function useIsGuest(): boolean {+ const v = useViewer().data;+ return !!v && v.publicSignup && !v.signedIn;+}++/** "Sign up" / "Log in" with a way back here. */+export function signInHref(mode: "signup" | "login", next?: string): string {+ const p = new URLSearchParams();+ if (mode === "signup") p.set("signup", "1");+ if (next && next !== "/") p.set("next", next);+ const q = p.toString();+ return q ? `/login?${q}` : "/login";+}++export const GUEST_PROMPT_EVENT = "fuobe:guest-prompt";+export const CONNECT_GPU_EVENT = "fuobe:connect-gpu";++/**+ * A guest tried to change something (the proxy answers a guest's change with a 401 marked+ * x-fuobe-guest): open "Create a free account" (GuestPrompt). An account tried to run something+ * (a 403 marked x-fuobe-connect-gpu): open "Connect your GPU". Watches every fetch, so the studio's+ * own helpers (json() here, and the components' own) all get it. Installed once.+ */+export function watchGuestRefusals(): void {+ const w = window as typeof window & { __fuobeGuestFetch?: boolean };+ if (w.__fuobeGuestFetch) return;+ w.__fuobeGuestFetch = true;+ const original = window.fetch.bind(window);+ window.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {+ const res = await original(input, init);+ if (res.status === 401 && res.headers.get("x-fuobe-guest") === "1") {+ const method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();+ if (method !== "GET" && method !== "HEAD") window.dispatchEvent(new Event(GUEST_PROMPT_EVENT));+ }+ if (res.status === 403 && res.headers.get("x-fuobe-connect-gpu") === "1") window.dispatchEvent(new Event(CONNECT_GPU_EVENT));+ return res;+ };+}diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.tsnew file mode 100644index 00000000..b97ea935--- /dev/null+++ b/src/lib/guest-access.ts@@ -0,0 +1,153 @@+/**+ * What guests (signed-out visitors) and accounts (people who signed up) may do while public sign-up+ * is on (src/server/auth.ts publicSignup). Path rules only: src/proxy.ts applies them.+ *+ * - A guest opens every page and the catalog and status reads the pages need. The owner's library+ * comes back empty (or 401 "Sign up to see your library"), and every change is a 401 that the+ * client turns into "Create a free account" (src/components/guest-prompt.tsx).+ * - An account browses the whole studio and keeps its own library and projects (ACCOUNT_CHANGES),+ * but never runs on the owner's cloud keys or GPU ("Connect your GPU"), and never changes+ * install-wide settings, keys or tokens (owner only).+ */++/** Set by the proxy on a guest's request to a route that answers guests itself (GUEST_FILTERED), and on its 401s. */+export const GUEST_HEADER = "x-fuobe-guest";++/** A guest's request, as the proxy marks it for GUEST_FILTERED routes (a client that sends the header itself only gets less). */+export const isGuest = (request: Request) => request.headers.get(GUEST_HEADER) === "1";++export const GUEST_LIBRARY_MESSAGE = "Sign up to see your library.";+export const GUEST_RUN_MESSAGE = "Create a free account to run this.";++/** Catalog and status reads that hold nothing of the owner's library: a guest gets the real answer. */+const GUEST_READS = new Set(["/api/status", "/api/models", "/api/search-index", "/api/comfyui", "/api/settings/models"]);++/** Catalogs mixed with the owner's own items: the route leaves the owner's part out for a guest (GUEST_HEADER). */+const GUEST_FILTERED = new Set(["/api/moodboards", "/api/palettes", "/api/assist/skills"]);++/** The owner's lists ({ items }): a guest gets them empty. */+const EMPTY_LISTS = [+ "/api/generations",+ "/api/generations/trash",+ "/api/assets",+ "/api/folders",+ "/api/elements",+ "/api/canvases",+ "/api/cinema/projects",+ "/api/layers",+ "/api/content-factory/series",+ "/api/dub",+ "/api/explainer",+ "/api/faceless/channels",+ "/api/faceless/episodes",+ "/api/katana",+ "/api/marketing/runs",+ "/api/products",+ "/api/brands",+ "/api/shorts/sessions",+ "/api/shorts/presets",+ "/api/swap-studio/projects",+ "/api/ads/creatives",+ "/api/assist/projects",+ "/api/assist/schedules",+];++const EMPTY: Record<string, unknown> = {+ ...Object.fromEntries(EMPTY_LISTS.map((p) => [p, { items: [] }])),+ "/api/shares": { items: [], signIn: true },+ "/api/photodump": { packs: [] },+ "/api/photodump/packs": { packs: [] },+ "/api/generations/facets": { models: [], kinds: {}, total: 0, favorites: 0, failed: 0, trash: 0, pinned: 0, steps: 0, reviews: {} },+};++export type GuestRead =+ /** A page, or a catalog read: let it through. */+ | { kind: "pass" }+ /** Let it through with GUEST_HEADER: the route answers without the owner's items. */+ | { kind: "filtered" }+ /** Answer this body (the owner's list, empty). */+ | { kind: "empty"; body: unknown }+ /** No such endpoint for a guest (404: the live-updates stream, so the client looks again much later). */+ | { kind: "none" }+ /** The owner's data: 401. */+ | { kind: "closed" };++/** What a guest's GET or HEAD gets. Anything not named here under /api stays closed. */+export function guestRead(pathname: string): GuestRead {+ if (pathname !== "/api" && !pathname.startsWith("/api/")) return { kind: "pass" };+ if (GUEST_READS.has(pathname)) return { kind: "pass" };+ if (GUEST_FILTERED.has(pathname)) return { kind: "filtered" };+ if (Object.hasOwn(EMPTY, pathname)) return { kind: "empty", body: EMPTY[pathname] };+ if (pathname === "/api/generations/stream") return { kind: "none" };+ return { kind: "closed" };+}++/** The run routes whose `?preview=1` only plans and prices (any other route would ignore the flag and run). */+const PREVIEWS = [/^\/api\/(generations|audio-tools|dub|katana)$/, /^\/api\/dub\/[^/]+\/voice$/];++/** The estimate routes (named: a dynamic segment called "estimate" on another route must not pass for one). */+const ESTIMATES =+ /^\/api\/(ads|ads\/multiplier|assist\/skills\/[^/]+|content-factory|evolution|faceless|genjutsu|influencer|marketing|marketing\/click-to-ad|mixed-media|remove-object|shorts|storyboards)\/estimate$/;++/** A POST that only plans and prices a run (an estimate route, or ?preview=1 where PREVIEWS honours it): free, and open to guests. */+export function isPriceCheck(method: string, pathname: string, search: string): boolean {+ if (method !== "POST") return false;+ if (ESTIMATES.test(pathname)) return true;+ return new URLSearchParams(search).get("preview") === "1" && PREVIEWS.some((r) => r.test(pathname));+}++/**+ * Changes an account may make: its own library and projects (create, rename, move, share, delete,+ * upload), never anything that reaches a model. Everything else an account sends (a run, an AI+ * helper, a connector, the MCP endpoint…) is refused with "Connect your GPU": an account never+ * spends the owner's cloud keys or GPU.+ */+const ACCOUNT_CHANGES: [methods: string, path: RegExp][] = [+ ["POST", /^\/api\/auth\/logout$/],+ ["POST", /^\/api\/uploads$/],+ ["POST", /^\/api\/media\/probe$/],+ ["POST", /^\/api\/folders$/],+ ["PATCH DELETE", /^\/api\/folders\/[^/]+$/],+ ["PATCH DELETE", /^\/api\/generations\/[^/]+$/],+ ["POST", /^\/api\/generations\/(bulk|local)$/],+ ["POST", /^\/api\/generations\/[^/]+\/(cancel|finish)$/],+ ["DELETE", /^\/api\/generations\/trash$/],+ ["DELETE", /^\/api\/assets\/[^/]+$/],+ ["POST", /^\/api\/shares$/],+ ["PATCH DELETE", /^\/api\/shares\/[^/]+$/],+ ["POST", /^\/api\/(canvases|cinema\/projects|layers|elements|palettes|products|brands|swap-studio\/projects|shorts\/presets|photodump\/packs|assist\/projects|assist\/memory)$/],+ [+ "PATCH DELETE",+ /^\/api\/(canvases|cinema\/projects|layers|elements|palettes|products|brands|moodboards|swap-studio\/projects|content-factory\/series|faceless\/channels|faceless\/episodes|dub|shorts\/presets|shorts\/sessions|assist|assist\/projects|assist\/memory|assist\/schedules|assist\/skills|ads\/creatives)\/[^/]+$/,+ ],+ ["DELETE", /^\/api\/(katana|marketing\/runs|photodump\/packs)\/[^/]+$/],+ ["POST", /^\/api\/canvases\/[^/]+\/duplicate$/],+ ["POST", /^\/api\/assist\/skills\/[^/]+\/duplicate$/],+ ["POST", /^\/api\/ads\/creatives\/[^/]+\/save$/],+ ["POST", /^\/api\/cinema\/projects\/[^/]+\/folders$/],+ ["PATCH DELETE", /^\/api\/cinema\/projects\/[^/]+\/(items|folders\/[^/]+)$/],+ ["PUT", /^\/api\/cinema\/projects\/[^/]+\/items\/[^/]+\/tiles$/],+ ["POST", /^\/api\/layers\/[^/]+\/versions$/],+ ["PATCH DELETE", /^\/api\/layers\/[^/]+\/jobs\/[^/]+$/],+ ["DELETE", /^\/api\/assist\/projects\/[^/]+\/sources\/[^/]+$/],+];++/** May an account make this change itself? (Reads are always fine; price checks are free.) */+export function accountMayChange(method: string, pathname: string, search: string): boolean {+ if (method === "GET" || method === "HEAD" || isPriceCheck(method, pathname, search)) return true;+ return ACCOUNT_CHANGES.some(([methods, path]) => methods.split(" ").includes(method) && path.test(pathname));+}++/** Set on an account's refused run: the client shows "Connect your GPU to run this". */+export const CONNECT_GPU_HEADER = "x-fuobe-connect-gpu";+export const CONNECT_GPU_MESSAGE = "Connect your GPU to run this. Free accounts run on their own ComfyUI.";++/** 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$/];++export function ownerOnly(method: string, pathname: string): boolean {+ if (OWNER_ALL.some((r) => r.test(pathname))) return true;+ return method !== "GET" && method !== "HEAD" && OWNER_WRITES.has(pathname);+}diff --git a/src/proxy.ts b/src/proxy.tsindex 84b777be..5115a47f 100644--- a/src/proxy.ts+++ b/src/proxy.ts@@ -2,12 +2,26 @@ import { NextResponse, type NextRequest } from "next/server";import { APPS } from "@/lib/catalog/apps";import { recordForPath, unknownHubMode } from "@/lib/record-pages";import { countsAsView, SHARE_VIEW_HEADER, shareRoute } from "@/lib/share";-import { authEnabled, crossSite, hostAllowed, LoginGuard, SESSION_COOKIE, validSession, validToken } from "@/server/auth";+import {+ accountMayChange,+ CONNECT_GPU_HEADER,+ CONNECT_GPU_MESSAGE,+ GUEST_HEADER,+ GUEST_LIBRARY_MESSAGE,+ GUEST_RUN_MESSAGE,+ guestRead,+ isPriceCheck,+ ownerOnly,+} from "@/lib/guest-access";+import { authEnabled, crossSite, hostAllowed, LoginGuard, publicSignup, SESSION_COOKIE, sessionViewer, validSession, validToken, type Viewer } from "@/server/auth";import { recordExists } from "@/server/records";import { findShare, shareGuard, shareTargetExists } from "@/server/share-access";-/** Paths that work signed out: the login page and its API (and share links: openShare). */-const OPEN = new Set(["/login", "/api/auth/login"]);+/**+ * Paths that work signed out: the login page and its API (and share links: openShare). Sign-up and+ * "who am I" answer for themselves whether public sign-up is on.+ */+const OPEN = new Set(["/login", "/api/auth/login", "/api/auth/signup", "/api/auth/me"]);const APP_IDS = new Set(APPS.map((a) => a.id));@@ -32,8 +46,56 @@ const notFound = (request: NextRequest) => NextResponse.rewrite(new URL("/_fuobe/** Share pages and their files: never indexed, and the token never leaks to another site in a Referer. */const SHARE_HEADERS = { "X-Robots-Tag": "noindex, nofollow, noarchive", "Referrer-Policy": "no-referrer" };+/** The owner: the install password's session, or an API token. */const signedIn = (request: NextRequest) => validSession(request.cookies.get(SESSION_COOKIE)?.value) || validToken(request.headers.get("authorization"));+/** The owner, an account (only while public sign-up is on), or null (a guest). */+function viewerOf(request: NextRequest, open: boolean): Viewer | null {+ const session = sessionViewer(request.cookies.get(SESSION_COOKIE)?.value);+ if (session?.kind === "owner" || validToken(request.headers.get("authorization"))) return { kind: "owner" };+ return open && session?.kind === "account" ? session : null;+}++const guestHeaders = { [GUEST_HEADER]: "1", "Cache-Control": "no-store" };++/**+ * A guest (public sign-up on, signed out): every page and the catalog reads, the owner's lists+ * empty, the rest of the library 401, and every change 401 (the client offers to sign up).+ */+function guest(request: NextRequest): NextResponse {+ const { pathname, search } = request.nextUrl;+ if (request.method === "GET" || request.method === "HEAD") {+ const read = guestRead(pathname);+ if (read.kind === "pass") return pass(request);+ if (read.kind === "filtered") {+ const headers = new Headers(request.headers);+ headers.set(GUEST_HEADER, "1");+ return NextResponse.next({ request: { headers } });+ }+ if (read.kind === "empty") return NextResponse.json(read.body, { headers: guestHeaders });+ if (read.kind === "none") return NextResponse.json({ error: "Not for guests" }, { status: 404, headers: guestHeaders });+ return NextResponse.json({ error: GUEST_LIBRARY_MESSAGE }, { status: 401, headers: guestHeaders });+ }+ if (isPriceCheck(request.method, pathname, search)) return pass(request);+ return NextResponse.json({ error: GUEST_RUN_MESSAGE }, { status: 401, headers: guestHeaders });+}++/**+ * An account: browses the whole studio and keeps its own library and projects, but install-wide+ * settings, keys and tokens are the owner's, and anything that would reach a model is refused+ * ("Connect your GPU"): an account never runs on the owner's cloud keys or GPU.+ */+function account(request: NextRequest): NextResponse {+ const { pathname, search } = request.nextUrl;+ if (ownerOnly(request.method, pathname)) {+ return NextResponse.json({ error: "Only the studio's owner can change settings, keys and tokens." }, { status: 403 });+ }+ if (!accountMayChange(request.method, pathname, search)) {+ return NextResponse.json({ error: CONNECT_GPU_MESSAGE, code: "connect-gpu" }, { status: 403, headers: { [CONNECT_GPU_HEADER]: "1" } });+ }+ return pass(request);+}+const tooMany = (seconds: number) =>new NextResponse("Too many wrong links. Try again in a minute.", { status: 429, headers: { ...SHARE_HEADERS, "Retry-After": String(seconds) } });@@ -102,7 +164,11 @@ export function proxy(request: NextRequest) {if (share) return openShare(request, share.token, !!share.file);if (!authEnabled()) return pass(request);if (OPEN.has(pathname)) return NextResponse.next();- if (signedIn(request)) return pass(request);+ const open = publicSignup(request.headers.get("host") ?? request.nextUrl.host);+ const viewer = viewerOf(request, open);+ if (viewer?.kind === "owner") return pass(request);+ if (viewer?.kind === "account") return account(request);+ if (open) return guest(request);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"' } });}diff --git a/src/server/auth.ts b/src/server/auth.tsindex 7909fda6..a5ed45b9 100644--- a/src/server/auth.ts+++ b/src/server/auth.ts@@ -3,6 +3,12 @@* Then every page and API call needs a session cookie (from /login) or an API token* (`Authorization: Bearer fuobe_…`).*+ * Public sign-up (publicSignup: FUOBE_PUBLIC_SIGNUP=1, Settings → Security, or fuobe.com itself)+ * opens a password-protected studio a little: guests may browse it read-only, and anyone may make+ * an account (email + password, no verification) whose session works across the app. An account+ * never runs on the owner's cloud keys or GPU, and install-wide settings, keys and tokens stay the+ * owner's (the install password's session, or an API token): src/proxy.ts, src/lib/guest-access.ts.+ ** Kept in a small JSON file next to the database, not in SQLite, so the proxy's sign-in check* needs nothing but `fs` and `crypto`. (The proxy does open SQLite, for one primary-key lookup on* record pages only, so an unknown id gets a real 404: src/server/records.ts.)@@ -29,12 +35,25 @@ export interface ApiToken {lastUsedAt?: number;}+/** A signed-up visitor (public sign-up). */+export interface Account {+ id: string;+ /** Lower-cased. */+ email: string;+ /** scrypt hash of the password ("salt:hash", hex), as the install password's. */+ hash: string;+ createdAt: 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[];+ accounts?: Account[];+ /** Settings → Security: guests may browse and anyone may sign up (FUOBE_PUBLIC_SIGNUP overrides it). */+ publicSignup?: boolean;}let cache: { mtime: number; data: AuthFile } | null = null;@@ -84,13 +103,18 @@ function hashPassword(pw: string): string {const same = (a: Buffer, b: Buffer) => a.length === b.length && crypto.timingSafeEqual(a, b);+function verifyHash(pw: string, stored: string): boolean {+ const [salt, hash] = stored.split(":");+ if (!salt || !hash) return false;+ return same(crypto.scryptSync(pw, Buffer.from(salt, "hex"), 32), Buffer.from(hash, "hex"));+}+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"));+ return verifyHash(pw, stored);}/** Set, change or (with null) remove the UI password. Signs every browser out. */@@ -106,22 +130,114 @@ export function setPassword(pw: string | null): void {const sign = (secret: string, payload: string) => crypto.createHmac("sha256", secret).update(payload).digest("base64url");-export function createSession(): { value: string; maxAge: number } {+/**+ * 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.+ */+export function createSession(accountId?: string): { 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 };+ const payload = accountId ? `${exp}.${accountId}` : String(exp);+ return { value: `${payload}.${sign(d.secret, payload)}`, maxAge: SESSION_DAYS * 86_400 };}+/** Who a session cookie belongs to: the owner, an account that still exists, or nobody. */+export type Viewer = { kind: "owner" } | { kind: "account"; account: Account };++export function sessionViewer(value: string | undefined): Viewer | null {+ if (!value) return null;+ const parts = value.split(".");+ if (parts.length !== 2 && parts.length !== 3) return 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 (!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;+}++/** The owner's session (the install password's): what Settings → Security and the tokens need. */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)));+ return sessionViewer(value)?.kind === "owner";+}++// ---------------------------------------------------------------------------+// Public sign-up: accounts++export class AccountError extends Error {+ constructor(+ message: string,+ readonly status: number,+ ) {+ super(message);+ }+}++/** Lower-cased, or null when it doesn't look like an email address. */+export function normalizeEmail(email: string): string | null {+ const e = email.trim().toLowerCase();+ return e.length <= 254 && /^[^\s@]+@[^\s@.]+(\.[^\s@.]+)+$/.test(e) ? e : null;+}++export function createAccount(email: string, password: string): Account {+ const e = normalizeEmail(email);+ if (!e) throw new AccountError("Enter a valid email address", 400);+ 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() };+ write({ ...d, accounts: [...(d.accounts ?? []), account] });+ return account;+}++let dummy: string | undefined;++/** The account for this email and password, or null. An unknown email costs the same scrypt as a known one. */+export function checkAccount(email: string, password: string): Account | null {+ const e = normalizeEmail(email);+ const account = e ? read().accounts?.find((a) => a.email === e) : undefined;+ const ok = verifyHash(password, account?.hash ?? (dummy ??= hashPassword(crypto.randomBytes(12).toString("hex"))));+ return account && ok ? account : null;+}++// ---------------------------------------------------------------------------+// Public sign-up: the switch++const FUOBE_COM = new Set(["fuobe.com", "www.fuobe.com"]);++/** FUOBE_PUBLIC_SIGNUP: "1" on, "0" off (Settings can't change either), else null. */+export function publicSignupFromEnv(): boolean | null {+ const v = process.env.FUOBE_PUBLIC_SIGNUP?.trim();+ return v === "1" ? true : v === "0" ? false : null;+}++/** The Settings → Security switch (ignored while FUOBE_PUBLIC_SIGNUP is set). */+export const publicSignupSetting = () => !!read().publicSignup;++export function setPublicSignup(on: boolean): void {+ if (publicSignupFromEnv() !== null) throw new Error("Public sign-up is set by FUOBE_PUBLIC_SIGNUP on the server");+ write({ ...withSecret(read()), publicSignup: on });+}++/**+ * Are guests and sign-ups let in for a request to this host? Only on a studio with a password+ * (without one everyone is the owner already). FUOBE_PUBLIC_SIGNUP=1 or 0 decides; unset, the+ * Settings switch, or the public demo at fuobe.com. The Host header is the client's word, so a+ * self-hosted studio reached by its IP can't be opened with "Host: fuobe.com": the name counts+ * only on an install that lists it in FUOBE_ALLOWED_ORIGINS, as fuobe.com's own server does.+ */+export function publicSignup(host: string | null | undefined): boolean {+ if (!authEnabled()) return false;+ const env = publicSignupFromEnv();+ if (env !== null) return env;+ if (publicSignupSetting()) return true;+ return !!host && FUOBE_COM.has(hostName(host)) && allowedHosts().some((a) => FUOBE_COM.has(hostName(a)));}// ---------------------------------------------------------------------------diff --git a/tests/public-signup.test.ts b/tests/public-signup.test.tsnew file mode 100644index 00000000..7ea03c58--- /dev/null+++ b/tests/public-signup.test.ts@@ -0,0 +1,267 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";+import { NextRequest } from "next/server";++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-signup-"));+process.env.FUOBE_DATA_DIR = dir;+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_PUBLIC_SIGNUP;+delete process.env.FUOBE_ALLOWED_ORIGINS;+const auth = await import("@/server/auth");+const { proxy } = await import("@/proxy");+const access = await import("@/lib/guest-access");+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";+const toLogin = (r: Response) => r.status === 307 && new URL(r.headers.get("location") ?? "", "http://x").pathname === "/login";++function req(url: string, init: { method?: string; cookie?: string; headers?: Record<string, string> } = {}) {+ const method = init.method ?? "GET";+ const headers: Record<string, string> = { ...init.headers };+ if (init.cookie) headers.cookie = `${auth.SESSION_COOKIE}=${init.cookie}`;+ return new NextRequest(`http://localhost:3000${url}`, { method, headers, ...(method !== "GET" && method !== "HEAD" && { body: "{}" }) });+}++beforeAll(() => auth.setPassword("install password"));+afterEach(() => {+ delete process.env.FUOBE_PUBLIC_SIGNUP;+ delete process.env.FUOBE_ALLOWED_ORIGINS;+});++describe("accounts", () => {+ it("signs up with a lower-cased email and a salted scrypt hash, never the password", () => {+ const a = auth.createAccount(" [email protected] ", "long enough");+ expect(a.email).toBe("[email protected]");+ expect(a.hash).toMatch(/^[0-9a-f]{32}:[0-9a-f]{64}$/);+ expect(a.createdAt).toBeGreaterThan(0);+ const file = fs.readFileSync(path.join(dir, "auth.json"), "utf8");+ expect(file).not.toContain("long enough");+ expect(JSON.parse(file).accounts[0].email).toBe("[email protected]");+ });++ it("logs in with the right password only", () => {+ expect(auth.checkAccount("[email protected]", "long enough")?.email).toBe("[email protected]");+ expect(auth.checkAccount("[email protected]", "wrong password")).toBeNull();+ expect(auth.checkAccount("[email protected]", "long enough")).toBeNull();+ expect(auth.checkAccount("not an email", "long enough")).toBeNull();+ });++ it("refuses a duplicate email, a bad email and a short password", () => {+ expect(() => auth.createAccount("[email protected]", "another one")).toThrow(/already exists/);+ expect(() => auth.createAccount("[email protected]", "another one")).toThrow(expect.objectContaining({ status: 409 }));+ expect(() => auth.createAccount("no-at-sign", "long enough")).toThrow(/valid email/);+ expect(() => auth.createAccount("[email protected]", "short")).toThrow(/8 characters/);+ });++ it("keeps the install password working, and an account session is never the owner's", () => {+ expect(auth.checkPassword("install password")).toBe(true);+ const a = auth.checkAccount("[email protected]", "long enough")!;+ const s = auth.createSession(a.id);+ expect(auth.sessionViewer(s.value)).toMatchObject({ kind: "account", account: { id: a.id } });+ expect(auth.validSession(s.value)).toBe(false);+ // Dropping the account id doesn't make an owner session.+ const [exp, , mac] = s.value.split(".");+ expect(auth.sessionViewer(`${exp}.${mac}`)).toBeNull();+ expect(auth.sessionViewer(s.value.replace(a.id, "0".repeat(a.id.length)))).toBeNull();+ expect(auth.validSession(auth.createSession().value)).toBe(true);+ });+});++describe("the switch", () => {+ it("is off by default, on with FUOBE_PUBLIC_SIGNUP=1 or the Settings switch, and FUOBE_PUBLIC_SIGNUP=0 wins", () => {+ expect(auth.publicSignup("localhost:3000")).toBe(false);+ process.env.FUOBE_PUBLIC_SIGNUP = "1";+ expect(auth.publicSignup("localhost:3000")).toBe(true);+ process.env.FUOBE_PUBLIC_SIGNUP = "0";+ expect(() => auth.setPublicSignup(true)).toThrow(/FUOBE_PUBLIC_SIGNUP/);+ delete process.env.FUOBE_PUBLIC_SIGNUP;+ auth.setPublicSignup(true);+ expect(auth.publicSignup("localhost:3000")).toBe(true);+ process.env.FUOBE_PUBLIC_SIGNUP = "0";+ expect(auth.publicSignup("localhost:3000")).toBe(false);+ delete process.env.FUOBE_PUBLIC_SIGNUP;+ auth.setPublicSignup(false);+ expect(auth.publicSignup("localhost:3000")).toBe(false);+ });++ it("is on at fuobe.com, but only on the install that names fuobe.com as its address", () => {+ // A self-hosted studio reached by IP: a forged Host header doesn't open it.+ expect(auth.publicSignup("fuobe.com")).toBe(false);+ process.env.FUOBE_ALLOWED_ORIGINS = "fuobe.com";+ expect(auth.publicSignup("fuobe.com")).toBe(true);+ expect(auth.publicSignup("www.fuobe.com")).toBe(true);+ expect(auth.publicSignup("evil.example")).toBe(false);+ process.env.FUOBE_PUBLIC_SIGNUP = "0";+ expect(auth.publicSignup("fuobe.com")).toBe(false);+ });+});++describe("proxy with public sign-up on", () => {+ let account = "";+ beforeAll(() => {+ account = auth.createSession(auth.createAccount("[email protected]", "long enough").id).value;+ });++ it("lets a guest open pages and the catalog reads", () => {+ process.env.FUOBE_PUBLIC_SIGNUP = "1";+ for (const p of ["/", "/motions", "/layers", "/cinema", "/image-to-3d", "/settings"]) expect(passed(proxy(req(p))), p).toBe(true);+ for (const p of ["/api/status", "/api/models", "/api/search-index"]) expect(passed(proxy(req(p))), p).toBe(true);+ expect(passed(proxy(req("/motions", { method: "HEAD" })))).toBe(true);+ });++ it("never shows a guest the owner's library", async () => {+ process.env.FUOBE_PUBLIC_SIGNUP = "1";+ const list = proxy(req("/api/generations?limit=40"));+ expect(list.status).toBe(200);+ expect(await list.json()).toEqual({ items: [] });+ for (const p of ["/api/files/outputs/a.png", "/api/settings", "/api/auth/tokens", "/api/generations/abc", "/api/layers/abc", "/api/uploads", "/api/assist"]) {+ const r = proxy(req(p));+ expect(r.status, p).toBe(401);+ expect(r.headers.get(access.GUEST_HEADER), p).toBe("1");+ }+ // Catalogs mixed with the owner's items: the route is told it's a guest.+ const moodboards = proxy(req("/api/moodboards"));+ expect(passed(moodboards)).toBe(true);+ expect(moodboards.headers.get(`x-middleware-request-${access.GUEST_HEADER}`)).toBe("1");+ });++ it("refuses a guest's every change with a 401 the client turns into the sign-up prompt", async () => {+ process.env.FUOBE_PUBLIC_SIGNUP = "1";+ for (const [method, p] of [+ ["POST", "/api/generations"],+ ["POST", "/api/uploads"],+ ["PUT", "/api/settings"],+ ["POST", "/api/layers"],+ ["DELETE", "/api/generations/abc"],+ ["PATCH", "/api/cinema/projects/abc"],+ ]) {+ const r = proxy(req(p, { method }));+ expect(r.status, `${method} ${p}`).toBe(401);+ expect(r.headers.get(access.GUEST_HEADER)).toBe("1");+ expect((await r.json()).error).toMatch(/free account/);+ }+ // Price checks only plan a run.+ expect(passed(proxy(req("/api/generations?preview=1", { method: "POST" })))).toBe(true);+ expect(passed(proxy(req("/api/shorts/estimate", { method: "POST" })))).toBe(true);+ });++ it("lets an account use the studio, but not settings, keys or tokens", async () => {+ process.env.FUOBE_PUBLIC_SIGNUP = "1";+ expect(passed(proxy(req("/api/generations", { cookie: account })))).toBe(true);+ expect(passed(proxy(req("/api/files/outputs/a.png", { cookie: account })))).toBe(true);+ expect(passed(proxy(req("/api/uploads", { method: "POST", cookie: account })))).toBe(true);+ expect(passed(proxy(req("/api/layers", { method: "POST", cookie: account })))).toBe(true);+ for (const [method, p] of [+ ["PUT", "/api/settings"],+ ["PUT", "/api/settings/models"],+ ["POST", "/api/auth/password"],+ ["GET", "/api/auth/tokens"],+ ["POST", "/api/auth/tokens"],+ ["PUT", "/api/auth/public"],+ ["POST", "/api/loras"],+ ["POST", "/api/assist/connectors"],+ ]) {+ const r = proxy(req(p, { method, cookie: account }));+ expect(r.status, `${method} ${p}`).toBe(403);+ expect((await r.json()).error).toMatch(/owner/);+ }+ });++ it("keeps the install password and API tokens working, with everything open", () => {+ process.env.FUOBE_PUBLIC_SIGNUP = "1";+ const owner = auth.createSession().value;+ expect(passed(proxy(req("/api/settings", { method: "PUT", cookie: owner })))).toBe(true);+ expect(passed(proxy(req("/api/auth/tokens", { cookie: owner })))).toBe(true);+ const { token } = auth.createToken("CI");+ expect(passed(proxy(req("/api/settings", { method: "PUT", headers: { authorization: `Bearer ${token}` } })))).toBe(true);+ });++ it("opens sign-up, log-in and who-am-I to everyone", () => {+ for (const p of ["/login", "/api/auth/login", "/api/auth/signup", "/api/auth/me"]) {+ expect(passed(proxy(req(p, { method: p === "/login" || p === "/api/auth/me" ? "GET" : "POST" }))), p).toBe(true);+ }+ });+});++describe("proxy with public sign-up off (today's behaviour)", () => {+ it("sends guests to sign in and refuses accounts; the owner still gets in", async () => {+ const account = auth.createSession(auth.createAccount("[email protected]", "long enough").id).value;+ expect(toLogin(proxy(req("/motions")))).toBe(true);+ expect(toLogin(proxy(req("/")))).toBe(true);+ expect(proxy(req("/api/status")).status).toBe(401);+ const list = proxy(req("/api/generations"));+ expect(list.status).toBe(401);+ expect(list.headers.get(access.GUEST_HEADER)).toBeNull();+ expect(proxy(req("/api/generations", { method: "POST" })).status).toBe(401);+ expect(toLogin(proxy(req("/motions", { cookie: account })))).toBe(true);+ expect(proxy(req("/api/generations", { cookie: account })).status).toBe(401);+ const owner = auth.createSession().value;+ expect(passed(proxy(req("/motions", { cookie: owner })))).toBe(true);+ expect(passed(proxy(req("/api/generations", { method: "POST", cookie: owner })))).toBe(true);+ });+});++describe("accounts never run on the owner's keys or GPU", () => {+ it("refuses an account's runs and AI helpers with Connect your GPU", async () => {+ process.env.FUOBE_PUBLIC_SIGNUP = "1";+ const cookie = auth.createSession(auth.createAccount("[email protected]", "long enough").id).value;+ for (const p of [+ "/api/generations",+ "/api/canvases/c1/run",+ "/api/cinema/projects/p1/generate",+ "/api/layers/l1/jobs",+ "/api/katana/k1/retry",+ "/api/enhance",+ "/api/brands/b1/chat",+ "/api/assist",+ "/api/assist/t1/messages",+ "/api/assist/t1/approval",+ "/api/faceless/episodes/e1/render",+ "/api/content-factory/claude",+ // A run route that ignores ?preview=1 isn't a price check.+ "/api/cinema/projects/p1/generate?preview=1",+ "/api/faceless/episodes/e1/estimate",+ ]) {+ const r = proxy(req(p, { method: "POST", cookie }));+ expect(r.status, p).toBe(403);+ expect(r.headers.get(access.CONNECT_GPU_HEADER), p).toBe("1");+ expect((await r.json()).code).toBe("connect-gpu");+ }+ // Owner-only routes say so (not "connect your GPU").+ expect(proxy(req("/api/mcp", { method: "POST", cookie })).headers.get(access.CONNECT_GPU_HEADER)).toBeNull();+ // Its own library, price checks and reads are fine.+ for (const [method, p] of [+ ["POST", "/api/generations?preview=1"],+ ["POST", "/api/ads/estimate"],+ ["POST", "/api/assist/skills/s1/estimate"],+ ["POST", "/api/folders"],+ ["PATCH", "/api/folders/f1"],+ ["POST", "/api/generations/bulk"],+ ["DELETE", "/api/generations/g1"],+ ["POST", "/api/shares"],+ ["POST", "/api/cinema/projects"],+ ["PATCH", "/api/layers/l1"],+ ["POST", "/api/auth/logout"],+ ["GET", "/api/generations"],+ ]) {+ expect(passed(proxy(req(p, { method, cookie }))), `${method} ${p}`).toBe(true);+ }+ });++ it("keeps the owner's runs unchanged", () => {+ process.env.FUOBE_PUBLIC_SIGNUP = "1";+ const owner = auth.createSession().value;+ for (const p of ["/api/generations", "/api/enhance", "/api/canvases/c1/run"]) expect(passed(proxy(req(p, { method: "POST", cookie: owner }))), p).toBe(true);+ });++ it("knows a price check from a run", () => {+ expect(access.isPriceCheck("POST", "/api/generations", "?preview=1")).toBe(true);+ expect(access.isPriceCheck("POST", "/api/dub/d1/voice", "?preview=1")).toBe(true);+ expect(access.isPriceCheck("POST", "/api/generations", "")).toBe(false);+ expect(access.isPriceCheck("POST", "/api/canvases/c1/run", "?preview=1")).toBe(false);+ expect(access.isPriceCheck("POST", "/api/shorts/sessions/s1/segments/estimate", "")).toBe(false);+ expect(access.isPriceCheck("GET", "/api/shorts/estimate", "")).toBe(false);+ });+});