Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Security: the proxy and every route read the sign-in cookie the same way

Adarsh43ebef85eeb3
diff --git a/src/app/api/admin/accounts/[id]/route.ts b/src/app/api/admin/accounts/[id]/route.ts
index 136786b2..0ad86128 100644
--- a/src/app/api/admin/accounts/[id]/route.ts
+++ b/src/app/api/admin/accounts/[id]/route.ts
@@ -1,10 +1,9 @@
-import { cookies } from "next/headers";
import { z } from "zod";
-import { AccountError, deleteAccount, isOwnerRequest, listAccounts, SESSION_COOKIE, setAccountDisabled } from "@/server/auth";
+import { AccountError, deleteAccount, isOwnerRequest, listAccounts, sessionCookieOf, setAccountDisabled } from "@/server/auth";
import { purgeAccount } from "@/server/account-sweep";
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 });
+ return isOwnerRequest(request, sessionCookieOf(request)) ? null : Response.json({ error: "Only the studio's owner manages accounts" }, { status: 403 });
}
const failed = (e: unknown) => {
diff --git a/src/app/api/admin/accounts/route.ts b/src/app/api/admin/accounts/route.ts
index 57bcb08b..82c866ed 100644
--- a/src/app/api/admin/accounts/route.ts
+++ b/src/app/api/admin/accounts/route.ts
@@ -1,11 +1,10 @@
-import { cookies } from "next/headers";
import { connection } from "next/server";
-import { accountsCsv, isOwnerRequest, listAccounts, SESSION_COOKIE } from "@/server/auth";
+import { accountsCsv, isOwnerRequest, listAccounts, sessionCookieOf } 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 });
+ if (!isOwnerRequest(request, sessionCookieOf(request))) 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);
diff --git a/src/app/api/auth/me/route.ts b/src/app/api/auth/me/route.ts
index 4d202c31..cec4125b 100644
--- a/src/app/api/auth/me/route.ts
+++ b/src/app/api/auth/me/route.ts
@@ -1,14 +1,14 @@
import { cookies } from "next/headers";
import { connection } from "next/server";
import { z } from "zod";
-import { authEnabled, checkAccount, deleteAccount, publicSignup, SESSION_COOKIE, sessionViewer, validToken } from "@/server/auth";
+import { authEnabled, checkAccount, deleteAccount, publicSignup, SESSION_COOKIE, sessionCookieOf, sessionViewer, validToken } from "@/server/auth";
import { purgeAccount } from "@/server/account-sweep";
/** 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 session = sessionViewer(sessionCookieOf(request));
const owner = !authEnabled() || session?.kind === "owner" || validToken(request.headers.get("authorization"));
const account = !owner && open && session?.kind === "account" ? session.account : null;
return Response.json(
@@ -25,7 +25,7 @@ export async function GET(request: Request) {
/** 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);
+ const session = sessionViewer(sessionCookieOf(request));
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 });
diff --git a/src/app/api/auth/password/route.ts b/src/app/api/auth/password/route.ts
index 98f33be8..ee94741e 100644
--- a/src/app/api/auth/password/route.ts
+++ b/src/app/api/auth/password/route.ts
@@ -1,7 +1,7 @@
import { cookies } from "next/headers";
import { connection } from "next/server";
import { z } from "zod";
-import { authEnabled, authStatus, checkPassword, createSession, SESSION_COOKIE, setPassword, validSession } from "@/server/auth";
+import { authEnabled, authStatus, checkPassword, createSession, SESSION_COOKIE, sessionCookieOf, setPassword, validSession } from "@/server/auth";
const Body = z.object({ current: z.string().max(500).optional(), password: z.string().max(500).nullable() });
@@ -16,7 +16,7 @@ export async function POST(request: Request) {
if (!parsed.success) return Response.json({ error: "Invalid request" }, { status: 400 });
const { current, password } = parsed.data;
const jar = await cookies();
- if (authEnabled() && !validSession(jar.get(SESSION_COOKIE)?.value)) return Response.json({ error: "Change the password from a signed-in browser" }, { status: 403 });
+ if (authEnabled() && !validSession(sessionCookieOf(request))) return Response.json({ error: "Change the password from a signed-in browser" }, { status: 403 });
if (authEnabled() && !checkPassword(current ?? "")) return Response.json({ error: "The current password is wrong" }, { status: 403 });
try {
setPassword(password);
diff --git a/src/app/api/auth/public/route.ts b/src/app/api/auth/public/route.ts
index 4ebf01b8..2acce224 100644
--- a/src/app/api/auth/public/route.ts
+++ b/src/app/api/auth/public/route.ts
@@ -1,7 +1,6 @@
-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";
+import { authEnabled, publicSignup, publicSignupFromEnv, publicSignupSetting, sessionCookieOf, setPublicSignup, validSession } from "@/server/auth";
const status = (request: Request) => ({
/** The Settings switch. */
@@ -21,7 +20,7 @@ export async function GET(request: 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 });
+ if (!validSession(sessionCookieOf(request))) 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 {
diff --git a/src/app/api/auth/tokens/route.ts b/src/app/api/auth/tokens/route.ts
index f7916d18..a00d5119 100644
--- a/src/app/api/auth/tokens/route.ts
+++ b/src/app/api/auth/tokens/route.ts
@@ -1,11 +1,11 @@
-import { cookies } from "next/headers";
+import { headers } from "next/headers";
import { connection } from "next/server";
import { z } from "zod";
-import { authEnabled, authStatus, createToken, revokeToken, SESSION_COOKIE, validSession } from "@/server/auth";
+import { authEnabled, authStatus, createToken, revokeToken, sessionCookieFrom, validSession } from "@/server/auth";
/** Tokens are managed from a signed-in browser only: a token can't mint or revoke tokens. */
async function browserOnly(): Promise<Response | null> {
- if (!authEnabled() || validSession((await cookies()).get(SESSION_COOKIE)?.value)) return null;
+ if (!authEnabled() || validSession(sessionCookieFrom((await headers()).get("cookie")))) return null;
return Response.json({ error: "Manage API tokens from a signed-in browser" }, { status: 403 });
}
diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.ts
index 619b2151..0f60ef9b 100644
--- a/src/app/api/generations/route.ts
+++ b/src/app/api/generations/route.ts
@@ -1,7 +1,7 @@
import { connection } from "next/server";
-import { CONNECT_GPU_HEADER, OWN_GPU_TOOL_MESSAGE } from "@/lib/guest-access";
+import { CONNECT_GPU_HEADER, GUEST_RUN_MESSAGE, OWN_GPU_TOOL_MESSAGE } from "@/lib/guest-access";
import { missingFilesMessage } from "@/lib/missing-files";
-import { accountGpu, requestAccount, requestViewer } from "@/server/auth";
+import { accountGpu, requestViewer } from "@/server/auth";
import { OPERATION_LABELS } from "@/lib/catalog/types";
import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountUsage, diskHasRoom } from "@/server/account-files";
import { accountInputProblem } from "@/server/account-inputs";
@@ -22,9 +22,10 @@ import { gpuTargetFor } from "@/server/gpu/target";
export async function GET(request: Request) {
await connection();
ensureTrashPurge();
- // An account (public sign-up) lists only its own runs; the owner only theirs.
- const account = requestAccount(request);
- return Response.json({ items: listGenerations({ ...listOptionsFrom(new URL(request.url).searchParams), account: account?.id }) });
+ // An account (public sign-up) lists only its own runs; the owner only theirs; anyone else nothing.
+ const viewer = requestViewer(request);
+ if (viewer.kind === "guest") return Response.json({ items: [] });
+ return Response.json({ items: listGenerations({ ...listOptionsFrom(new URL(request.url).searchParams), account: viewer.kind === "account" ? viewer.account.id : undefined }) });
}
/** An account's runs going now (queued or running), counted as runs: a run's jobs and chain steps share a batch. */
@@ -45,6 +46,8 @@ export async function POST(request: Request) {
const viewer = requestViewer(request);
const account = viewer.kind === "account" ? viewer.account : null;
const preview = new URL(request.url).searchParams.get("preview") === "1";
+ // Without a viewer only a price check: a run is the owner's or an account's, never "nobody, so the owner".
+ if (viewer.kind === "guest" && !preview) return refuse(401, GUEST_RUN_MESSAGE);
// An account's run request is words and file paths (files are uploaded first): small.
const limitBody = !!account && !preview;
if (limitBody && Number(request.headers.get("content-length") ?? 0) > ACCOUNT_LIMITS.runBodyBytes) return refuse(413, ACCOUNT_MESSAGES.bodyTooBig);
diff --git a/src/app/api/media/probe/route.ts b/src/app/api/media/probe/route.ts
index b4cecb78..e9169699 100644
--- a/src/app/api/media/probe/route.ts
+++ b/src/app/api/media/probe/route.ts
@@ -1,6 +1,7 @@
import { z } from "zod";
import { ACCOUNT_MESSAGES } from "@/server/account-files";
-import { requestAccount } from "@/server/auth";
+import { GUEST_RUN_MESSAGE } from "@/lib/guest-access";
+import { requestViewer } from "@/server/auth";
import { enter, hit } from "@/server/rate";
import { probeSource } from "@/server/shorts";
import { body, handle } from "@/server/shorts-schemas";
@@ -15,8 +16,10 @@ import { runAsTenant } from "@/server/tenant";
export async function POST(request: Request) {
return handle(async () => {
const { url } = await body(request, z.object({ url: z.string().startsWith("/api/files/").max(500) }), "Upload the clip first");
- const account = requestAccount(request);
- if (!account) return Response.json(await probeSource(url));
+ const viewer = requestViewer(request);
+ if (viewer.kind === "owner") return Response.json(await probeSource(url));
+ if (viewer.kind !== "account") return Response.json({ error: GUEST_RUN_MESSAGE }, { status: 401, headers: { "Cache-Control": "no-store" } });
+ const { account } = viewer;
const busy = () => Response.json({ error: ACCOUNT_MESSAGES.probeRate }, { status: 429, headers: { "Retry-After": "10", "Cache-Control": "no-store" } });
if (!hit(`probe:${account.id}`, 60, 60_000).ok) return busy();
const release = enter(`probe:${account.id}`, 2);
diff --git a/src/proxy.ts b/src/proxy.ts
index 04fc22c3..fd064cd4 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -20,7 +20,7 @@ import {
ownerOnly,
ownGpuRun,
} from "@/lib/guest-access";
-import { authEnabled, crossSite, hostAllowed, LoginGuard, publicSignup, SESSION_COOKIE, sessionViewer, validSession, validToken, type Account, type Viewer } from "@/server/auth";
+import { authEnabled, crossSite, hostAllowed, LoginGuard, publicSignup, sessionCookieOf, sessionViewer, validSession, validToken, type Account, type Viewer } from "@/server/auth";
import { fileAccount, generationAccount } from "@/server/account-library";
import { recordExists } from "@/server/records";
import { findShare, shareGuard, shareTargetExists } from "@/server/share-access";
@@ -55,11 +55,11 @@ const notFound = (request: NextRequest) => NextResponse.rewrite(new URL("/_fuobe
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"));
+const signedIn = (request: NextRequest) => validSession(sessionCookieOf(request)) || 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);
+ const session = sessionViewer(sessionCookieOf(request));
if (session?.kind === "owner" || validToken(request.headers.get("authorization"))) return { kind: "owner" };
return open && session?.kind === "account" ? session : null;
}
diff --git a/src/server/auth.ts b/src/server/auth.ts
index d3a30649..c57e09e6 100644
--- a/src/server/auth.ts
+++ b/src/server/auth.ts
@@ -306,13 +306,26 @@ export function setAccountGpu(id: string, gpu: AccountGpu | null): void {
/** Who is asking: the owner (also everyone while no password is set), an account (public sign-up on), or a guest. */
export type RequestViewer = { kind: "owner" } | { kind: "account"; account: Account } | { kind: "guest" };
-/** The session cookie a request carries (read from its Cookie header: works outside Next's request scope too). */
-export function sessionCookieOf(request: Request): string | undefined {
- for (const part of (request.headers.get("cookie") ?? "").split(";")) {
+/**
+ * The session cookie in a Cookie header: the one reading the proxy and every route use, so they always agree on who is
+ * asking. Exactly one fuobe_session pair whose value is a plain token (letters, digits, "_", "-", "."). Two pairs, or an
+ * encoded value, mean no session: parsers that pick a different pair (Next keeps the last and decodes it) would
+ * otherwise let the proxy check one viewer while a route acts for another.
+ */
+export function sessionCookieFrom(header: string | null | undefined): string | undefined {
+ let found: string | undefined;
+ for (const part of (header ?? "").split(";")) {
const eq = part.indexOf("=");
- if (eq > 0 && part.slice(0, eq).trim() === SESSION_COOKIE) return part.slice(eq + 1).trim();
+ if (eq <= 0 || part.slice(0, eq).trim() !== SESSION_COOKIE) continue;
+ if (found !== undefined) return undefined;
+ found = part.slice(eq + 1).trim();
}
- return undefined;
+ return found && /^[\w.-]+$/.test(found) ? found : undefined;
+}
+
+/** The session cookie a request carries (read from its Cookie header: works outside Next's request scope too). */
+export function sessionCookieOf(request: Request): string | undefined {
+ return sessionCookieFrom(request.headers.get("cookie"));
}
export function requestViewer(request: Request, cookie = sessionCookieOf(request)): RequestViewer {
diff --git a/tests/public-signup.test.ts b/tests/public-signup.test.ts
index dfcde2f2..6b80f8fc 100644
--- a/tests/public-signup.test.ts
+++ b/tests/public-signup.test.ts
@@ -1,8 +1,10 @@
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 { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { 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 () => {} }));
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-signup-"));
process.env.FUOBE_DATA_DIR = dir;
@@ -336,3 +338,48 @@ describe("accounts with their own GPU", () => {
expect(proxy(req("/api/account/gpu")).status).toBe(401);
});
});
+
+describe("one reading of the session cookie (audit: proxy and routes must agree on who is asking)", () => {
+ let account = "";
+ beforeAll(() => {
+ account = auth.createSession(auth.createAccount("[email protected]", "long enough").id).value;
+ });
+ const raw = (url: string, cookie: string, method = "GET") =>
+ new NextRequest(`http://localhost:3000${url}`, { method, headers: { cookie }, ...(method !== "GET" && { body: "{}" }) });
+ const doubled = () => `${auth.SESSION_COOKIE}=x; ${auth.SESSION_COOKIE}=${account}`;
+ const encoded = () => `${auth.SESSION_COOKIE}=${account.replaceAll(".", "%2E")}`;
+
+ it("reads exactly one plain session pair, and nothing else", () => {
+ expect(auth.sessionCookieFrom(`${auth.SESSION_COOKIE}=${account}`)).toBe(account);
+ expect(auth.sessionCookieFrom(`a=1; ${auth.SESSION_COOKIE}=${account}; b=2`)).toBe(account);
+ expect(auth.sessionCookieFrom(doubled())).toBeUndefined();
+ expect(auth.sessionCookieFrom(`${auth.SESSION_COOKIE}=${account}; ${auth.SESSION_COOKIE}=${account}`)).toBeUndefined();
+ expect(auth.sessionCookieFrom(encoded())).toBeUndefined();
+ expect(auth.sessionCookieFrom(`${auth.SESSION_COOKIE}="${account}"`)).toBeUndefined();
+ expect(auth.sessionCookieFrom(null)).toBeUndefined();
+ });
+
+ it("treats a doubled or encoded cookie as a guest in the proxy AND in the routes", () => {
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ for (const cookie of [doubled(), encoded()]) {
+ // The proxy: an account may list its own runs and start one; a guest may not start one.
+ expect(proxy(raw("/api/generations", cookie, "POST")).status, cookie).toBe(401);
+ expect(proxy(raw("/api/account/gpu", cookie)).status, cookie).toBe(401);
+ // The routes see the same guest, never "no account, so the owner".
+ expect(auth.requestViewer(raw("/api/generations", cookie)).kind, cookie).toBe("guest");
+ expect(auth.requestAccount(raw("/api/generations", cookie)), cookie).toBeNull();
+ }
+ // The plain cookie is still the account, in both.
+ expect(auth.requestViewer(raw("/api/generations", `${auth.SESSION_COOKIE}=${account}`)).kind).toBe("account");
+ expect(passed(proxy(raw("/api/account/gpu", `${auth.SESSION_COOKIE}=${account}`)))).toBe(true);
+ });
+
+ it("the run and list routes answer a guest as a guest, never as the owner", async () => {
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ const { GET, POST } = await import("@/app/api/generations/route");
+ const list = await GET(raw("/api/generations", doubled()));
+ expect(await list.json()).toEqual({ items: [] });
+ const run = await POST(raw("/api/generations", doubled(), "POST"));
+ expect(run.status).toBe(401);
+ });
+});