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
Runtime security: cross-site requests, remote inputs, sign-in lockout, redirects
Claude88cad73de4c9
diff --git a/next.config.ts b/next.config.tsindex 8f1d6d73..995ff054 100644--- a/next.config.ts+++ b/next.config.ts@@ -4,6 +4,10 @@ const nextConfig: NextConfig = {/* config options here */cacheComponents: true,partialPrefetching: true,+ experimental: {+ // The sign-in proxy buffers request bodies (10 MB by default): uploads take up to 200 MB plus the form overhead.+ proxyClientMaxBodySize: "210mb",+ },async redirects() {return [{ source: "/characters", destination: "/elements", permanent: true },diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.tsindex fd7ca6dd..d297f443 100644--- a/src/app/api/auth/login/route.ts+++ b/src/app/api/auth/login/route.ts@@ -1,22 +1,27 @@import { cookies } from "next/headers";import { z } from "zod";-import { authEnabled, checkPassword, createSession, SESSION_COOKIE } from "@/server/auth";+import { authEnabled, checkPassword, createSession, LoginGuard, SESSION_COOKIE } from "@/server/auth";const Body = z.object({ password: z.string().min(1).max(500) });-const failures = new Map<string, { n: number; until: number }>();++declare global {+ var __fuobeLoginGuard: LoginGuard | undefined;+}+const guard = (globalThis.__fuobeLoginGuard ??= new LoginGuard());export async function POST(request: Request) {if (!authEnabled()) return Response.json({ ok: true });- const ip = request.headers.get("x-forwarded-for")?.split(",")[0].trim() || "local";- const f = failures.get(ip);- if (f && f.until > Date.now()) return Response.json({ error: "Too many attempts. Wait a minute and try again." }, { status: 429 });+ const key = LoginGuard.clientKey(request.headers);+ const wait = guard.blockedFor(key);+ if (wait > 0) {+ return Response.json({ error: "Too many attempts. Wait a minute and try again." }, { status: 429, headers: { "Retry-After": String(Math.ceil(wait / 1000)) } });+ }const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success || !checkPassword(parsed.data.password)) {- const n = (f?.n ?? 0) + 1;- failures.set(ip, { n, until: n >= 5 ? Date.now() + 60_000 : 0 });+ guard.fail(key);return Response.json({ error: "Wrong password" }, { status: 401 });}- failures.delete(ip);+ guard.succeed(key);const s = createSession();(await cookies()).set(SESSION_COOKIE, s.value, {httpOnly: true,diff --git a/src/components/login-form.tsx b/src/components/login-form.tsxindex 433a1fc8..a93b01b8 100644--- a/src/components/login-form.tsx+++ b/src/components/login-form.tsx@@ -5,17 +5,13 @@ import { useSearchParams } from "next/navigation";import { useState } from "react";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";+import { safeNext } from "@/lib/safe-redirect";export function LoginForm() {const params = useSearchParams();const [password, setPassword] = useState("");const [error, setError] = useState<string | null>(null);const [busy, setBusy] = useState(false);- // Only same-site paths: never bounce to another origin after signing in.- const next = (() => {- const n = params.get("next") ?? "/";- return n.startsWith("/") && !n.startsWith("//") ? n : "/";- })();const submit = async (e: React.FormEvent) => {e.preventDefault();@@ -23,7 +19,8 @@ export function LoginForm() {setError(null);const res = await fetch("/api/auth/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ password }) });if (res.ok) {- window.location.assign(next);+ // Only a page on this site: never bounce to another origin after signing in.+ window.location.assign(safeNext(params.get("next"), window.location.origin));return;}setError(((await res.json().catch(() => ({}))) as { error?: string }).error ?? "Couldn't sign in");diff --git a/src/lib/safe-redirect.ts b/src/lib/safe-redirect.tsnew file mode 100644index 00000000..99ab374a--- /dev/null+++ b/src/lib/safe-redirect.ts@@ -0,0 +1,14 @@+/**+ * Where to go after signing in: only a path on this site. "/\evil.example" or "/\t/evil.example"+ * look like paths but the URL parser reads them as another host, so the check resolves the URL+ * and compares origins instead of looking at the first characters.+ */+export function safeNext(next: string | null | undefined, origin: string): string {+ if (!next) return "/";+ try {+ const u = new URL(next, origin);+ return u.origin === new URL(origin).origin ? `${u.pathname}${u.search}${u.hash}` : "/";+ } catch {+ return "/";+ }+}diff --git a/src/proxy.ts b/src/proxy.tsindex 6d6ddc85..db0b6339 100644--- a/src/proxy.ts+++ b/src/proxy.ts@@ -1,10 +1,14 @@import { NextResponse, type NextRequest } from "next/server";-import { authEnabled, SESSION_COOKIE, validSession, validToken } from "@/server/auth";+import { authEnabled, crossSite, SESSION_COOKIE, validSession, validToken } from "@/server/auth";/** Paths that work signed out: the login page and its API. */const OPEN = new Set(["/login", "/api/auth/login"]);export function proxy(request: NextRequest) {+ // Before the sign-in check: a password-less install needs this most.+ if (crossSite(request, request.nextUrl.host)) {+ return NextResponse.json({ error: "Blocked a request from another website. Use Fuobe from its own address (or add it to FUOBE_ALLOWED_ORIGINS)." }, { status: 403 });+ }if (!authEnabled()) return NextResponse.next();const { pathname, search } = request.nextUrl;if (OPEN.has(pathname)) return NextResponse.next();@@ -18,6 +22,7 @@ export function proxy(request: NextRequest) {}export const config = {- // Everything except build assets and the public folder's files.- matcher: ["/((?!_next/static|_next/image|favicon.ico|samples/|.*\\.svg$).*)"],+ // Everything except build assets and the public folder's own files: the favicon, the demo+ // samples and the SVGs at the root. Generated SVGs under /api/files stay behind sign-in.+ matcher: ["/((?!_next/static|_next/image|favicon\\.ico$|samples/|[^/]+\\.svg$).*)"],};diff --git a/src/server/auth.ts b/src/server/auth.tsindex fe82f2ef..5fb7d04e 100644--- a/src/server/auth.ts+++ b/src/server/auth.ts@@ -121,6 +121,104 @@ export function validSession(value: string | undefined): boolean {return same(Buffer.from(mac), Buffer.from(sign(secret, exp)));}+// ---------------------------------------------------------------------------+// Cross-site requests++const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);++/** Extra addresses this studio is reached at (FUOBE_ALLOWED_ORIGINS="https://fuobe.example.com,studio.lan:3000"). */+function allowedHosts(): string[] {+ return (process.env.FUOBE_ALLOWED_ORIGINS ?? "")+ .split(",")+ .map((s) => s.trim())+ .filter(Boolean)+ .map((s) => {+ try {+ return s.includes("://") ? new URL(s).host : s;+ } catch {+ return s;+ }+ });+}++/**+ * Changes must come from Fuobe's own pages, or from a client that isn't a browser (those send no+ * Origin). Without this check any web page could post to a password-less local install — set its+ * password, start paid generations — with a "simple" text/plain request that needs no preflight.+ */+export function crossSite(request: Request, ownHost: string): boolean {+ if (SAFE_METHODS.has(request.method)) return false;+ if (request.headers.get("sec-fetch-site") === "cross-site") return true;+ const origin = request.headers.get("origin");+ if (!origin) return false;+ let host: string;+ try {+ host = new URL(origin).host;+ } catch {+ return true; // "null" (sandboxed frames, file://) or garbage+ }+ if (!host) return true;+ const own = [request.headers.get("host"), request.headers.get("x-forwarded-host")?.split(",")[0].trim(), ownHost, ...allowedHosts()];+ return !own.includes(host);+}++// ---------------------------------------------------------------------------+// Sign-in attempts++/**+ * Wrong-password lockout. Route handlers can't see the socket address, and Next keeps any+ * X-Forwarded-For a client sends, so that header only identifies a client behind a reverse proxy+ * you trust (FUOBE_TRUST_PROXY=1; the proxy's own entry is the last one). Otherwise every client+ * shares one budget. A global budget caps guesses even when the per-client key is spoofed.+ */+export class LoginGuard {+ private failures = new Map<string, { n: number; first: number; until: number }>();+ private recent: number[] = [];++ constructor(+ private readonly o = { perClient: 5, global: 20, windowMs: 60_000, lockMs: 60_000, maxClients: 5000 },+ ) {}++ /** Who is signing in: the last X-Forwarded-For hop when a trusted proxy sets it, else one shared key. */+ static clientKey(headers: Headers, trustProxy = process.env.FUOBE_TRUST_PROXY === "1"): string {+ if (!trustProxy) return "direct";+ const hops = (headers.get("x-forwarded-for") ?? "").split(",").map((s) => s.trim()).filter(Boolean);+ return hops.at(-1) ?? "direct";+ }++ /** Milliseconds until this client may try again (0 = now). */+ blockedFor(key: string, now = Date.now()): number {+ this.recent = this.recent.filter((t) => now - t < this.o.windowMs);+ const f = this.failures.get(key);+ const own = f && f.until > now ? f.until - now : 0;+ const global = this.recent.length >= this.o.global ? this.o.windowMs - (now - this.recent[0]) : 0;+ return Math.max(own, global);+ }++ fail(key: string, now = Date.now()): void {+ this.recent.push(now);+ const f = this.failures.get(key);+ const fresh = !f || now - f.first > this.o.windowMs;+ const n = fresh ? 1 : f.n + 1;+ this.failures.delete(key);+ this.failures.set(key, { n, first: fresh ? now : f.first, until: n >= this.o.perClient ? now + this.o.lockMs : 0 });+ // Forget old entries; never let the map grow without bound.+ for (const [k, v] of this.failures) {+ if (this.failures.size <= this.o.maxClients && now - v.first < this.o.windowMs * 10) break;+ if (v.until < now) this.failures.delete(k);+ else if (this.failures.size > this.o.maxClients) this.failures.delete(k);+ }+ }++ succeed(key: string): void {+ this.failures.delete(key);+ }++ get size() {+ return this.failures.size;+ }+}+// ---------------------------------------------------------------------------// API tokensdiff --git a/src/server/remote-fetch.ts b/src/server/remote-fetch.tsnew file mode 100644index 00000000..cbd2602f--- /dev/null+++ b/src/server/remote-fetch.ts@@ -0,0 +1,177 @@+import "server-only";+import dns from "node:dns/promises";+import http from "node:http";+import https from "node:https";+import net from "node:net";++/**+ * Fetch a file from a URL someone handed us (API callers, MCP clients, the Assist LLM) without+ * letting it reach this machine's own network: loopback, private, link-local (cloud metadata),+ * CGNAT and multicast addresses are refused. The check runs on the address the socket actually+ * connects to (so DNS can't swap it after the check), and again on every redirect.+ * Set FUOBE_ALLOW_PRIVATE_URLS=1 to allow private addresses (a LAN-only install that wants them).+ */++export const MAX_REMOTE_BYTES = 200 * 1024 * 1024;++export class RemoteFetchError extends Error {}++const v4 = (ip: string): number[] => ip.split(".").map(Number);++function blockedV4(ip: string): boolean {+ const [a, b, c] = v4(ip);+ return (+ a === 0 || // "this" network+ a === 10 ||+ a === 127 ||+ (a === 100 && b >= 64 && b <= 127) || // CGNAT (and Alibaba's metadata service)+ (a === 169 && b === 254) || // link-local: cloud metadata endpoints+ (a === 172 && b >= 16 && b <= 31) ||+ (a === 192 && b === 168) ||+ (a === 192 && b === 0 && (c === 0 || c === 2)) ||+ (a === 198 && (b === 18 || b === 19)) || // benchmarking+ (a === 198 && b === 51 && c === 100) ||+ (a === 203 && b === 0 && c === 113) ||+ a >= 224 // multicast, reserved, broadcast+ );+}++/** Expand an IPv6 address to its 8 hextets (handles "::" and an embedded IPv4 tail). */+function hextets(ip: string): number[] | null {+ let s = ip.toLowerCase().split("%")[0];+ const tail = /(\d+\.\d+\.\d+\.\d+)$/.exec(s);+ if (tail) {+ const [a, b, c, d] = v4(tail[1]);+ s = s.slice(0, -tail[1].length) + `${((a << 8) | b).toString(16)}:${((c << 8) | d).toString(16)}`;+ }+ const [head, rest] = s.split("::");+ const h = head ? head.split(":") : [];+ const r = rest !== undefined ? (rest ? rest.split(":") : []) : [];+ const fill = rest !== undefined ? 8 - h.length - r.length : 0;+ const all = [...h, ...Array(Math.max(0, fill)).fill("0"), ...r].map((x) => parseInt(x || "0", 16));+ return all.length === 8 && all.every((n) => Number.isFinite(n)) ? all : null;+}++function blockedV6(ip: string): boolean {+ const h = hextets(ip);+ if (!h) return true;+ const embedded = (hi: number, lo: number) => `${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`;+ if (h.slice(0, 7).every((x) => x === 0)) return true; // :: and ::1+ if (h.slice(0, 5).every((x) => x === 0) && h[5] === 0xffff) return blockedV4(embedded(h[6], h[7])); // ::ffff:a.b.c.d+ if (h[0] === 0x64 && h[1] === 0xff9b) return blockedV4(embedded(h[6], h[7])); // NAT64+ if (h[0] === 0x2002) return blockedV4(embedded(h[1], h[2])); // 6to4+ return (h[0] & 0xfe00) === 0xfc00 || (h[0] & 0xffc0) === 0xfe80 || (h[0] & 0xffc0) === 0xfec0 || (h[0] & 0xff00) === 0xff00;+}++/** True for addresses on this machine or its private networks (never fetched for a caller). */+export function isPrivateAddress(ip: string): boolean {+ if (net.isIPv4(ip)) return blockedV4(ip);+ if (net.isIPv6(ip)) return blockedV6(ip);+ return true;+}++export interface RemoteFetchOptions {+ maxBytes?: number;+ timeoutMs?: number;+ maxRedirects?: number;+ /** Tests: resolve host names without DNS. */+ resolve?: (host: string) => Promise<string[]>;+ /** Tests: which addresses to refuse (default: {@link isPrivateAddress}). */+ blocked?: (ip: string) => boolean;+}++const allowPrivate = () => process.env.FUOBE_ALLOW_PRIVATE_URLS === "1";++function refuse(host: string): RemoteFetchError {+ return new RemoteFetchError(`Fuobe won't fetch ${host}: it points to this machine or a private network. Upload the file instead.`);+}++/** GET a public http(s) URL into memory, with a timeout, a size cap and checked redirects. */+export async function fetchRemote(url: string, o: RemoteFetchOptions = {}): Promise<{ data: Buffer; contentType: string | null; url: string }> {+ const maxBytes = o.maxBytes ?? MAX_REMOTE_BYTES;+ const blocked = o.blocked ?? ((ip: string) => !allowPrivate() && isPrivateAddress(ip));+ const resolve = o.resolve ?? (async (host: string) => (await dns.lookup(host, { all: true, verbatim: true })).map((a) => a.address));+ const deadline = Date.now() + (o.timeoutMs ?? 60_000);+ let current = new URL(url);+ for (let hop = 0; hop <= (o.maxRedirects ?? 5); hop++) {+ if (current.protocol !== "http:" && current.protocol !== "https:") throw new RemoteFetchError(`Only http(s) links can be fetched, not ${current.protocol}`);+ if (current.username || current.password) throw new RemoteFetchError("Links with a user name or password aren't fetched");+ const host = current.hostname.replace(/^\[|\]$/g, "");+ if (net.isIP(host) && blocked(host)) throw refuse(current.host);+ const res = await get(current, { host, maxBytes, deadline, resolve, blocked });+ if (res.location) {+ current = new URL(res.location, current);+ continue;+ }+ return { data: res.data!, contentType: res.contentType, url: current.toString() };+ }+ throw new RemoteFetchError(`Too many redirects fetching ${url}`);+}++function get(+ url: URL,+ o: { host: string; maxBytes: number; deadline: number; resolve: (host: string) => Promise<string[]>; blocked: (ip: string) => boolean },+): Promise<{ location?: string; data?: Buffer; contentType: string | null }> {+ // Checked at connect time, on the address actually used.+ const lookup: net.LookupFunction = (hostname, options, cb) => {+ o.resolve(hostname).then(+ (addrs) => {+ if (!addrs.length) return cb(new RemoteFetchError(`Couldn't resolve ${hostname}`), "", 4);+ if (addrs.some(o.blocked)) return cb(refuse(hostname), "", 4);+ if (options.all) return (cb as unknown as (e: null, a: { address: string; family: number }[]) => void)(null, addrs.map((a) => ({ address: a, family: net.isIPv6(a) ? 6 : 4 })));+ cb(null, addrs[0], net.isIPv6(addrs[0]) ? 6 : 4);+ },+ (e: Error) => cb(e, "", 4),+ );+ };+ const left = o.deadline - Date.now();+ if (left <= 0) return Promise.reject(new RemoteFetchError(`Timed out fetching ${url.host}`));+ return new Promise((resolveOuter, rejectOuter) => {+ // A hard deadline for the whole download, not just an idle timeout.+ const timer = setTimeout(() => {+ req.destroy();+ reject(new RemoteFetchError(`Timed out fetching ${url.host}`));+ }, left);+ const resolvePromise = (v: { location?: string; data?: Buffer; contentType: string | null }) => {+ clearTimeout(timer);+ resolveOuter(v);+ };+ const reject = (e: Error) => {+ clearTimeout(timer);+ rejectOuter(e);+ };+ const req = (url.protocol === "https:" ? https : http).request(url, { method: "GET", lookup, headers: { "User-Agent": "Fuobe", Accept: "*/*" }, timeout: left }, (res) => {+ const status = res.statusCode ?? 0;+ if (status >= 300 && status < 400 && res.headers.location) {+ res.resume();+ return resolvePromise({ location: res.headers.location, contentType: null });+ }+ if (status < 200 || status >= 300) {+ res.resume();+ return reject(new RemoteFetchError(`Could not fetch ${url.toString()}: ${status}`));+ }+ const declared = Number(res.headers["content-length"] ?? 0);+ if (declared > o.maxBytes) {+ res.destroy();+ return reject(new RemoteFetchError(`That file is over ${Math.round(o.maxBytes / 1024 / 1024)} MB`));+ }+ const chunks: Buffer[] = [];+ let size = 0;+ res.on("data", (c: Buffer) => {+ size += c.length;+ if (size > o.maxBytes) {+ res.destroy();+ req.destroy();+ reject(new RemoteFetchError(`That file is over ${Math.round(o.maxBytes / 1024 / 1024)} MB`));+ return;+ }+ chunks.push(c);+ });+ res.on("end", () => resolvePromise({ data: Buffer.concat(chunks), contentType: res.headers["content-type"]?.split(";")[0].trim() || null }));+ res.on("error", reject);+ });+ req.on("timeout", () => req.destroy(new RemoteFetchError(`Timed out fetching ${url.host}`)));+ req.on("error", (e) => reject(e instanceof RemoteFetchError ? e : new RemoteFetchError(`Could not fetch ${url.toString()}: ${e.message}`)));+ req.end();+ });+}diff --git a/src/server/storage.ts b/src/server/storage.tsindex d612aa11..e0b5017b 100644--- a/src/server/storage.ts+++ b/src/server/storage.ts@@ -4,6 +4,7 @@ import path from "node:path";import { nanoid } from "nanoid";import { DATA_DIR, db } from "./db";import type { MediaKind } from "@/lib/catalog/types";+import { fetchRemote } from "./remote-fetch";export const FILES_DIR = path.join(DATA_DIR, "files");@@ -22,6 +23,13 @@ const EXT_BY_TYPE: Record<string, string> = {"audio/ogg": "ogg","audio/flac": "flac","audio/mp4": "m4a",+ // Text outputs (transcripts, translations, scripts) and 3D models.+ "text/plain": "txt",+ "application/x-subrip": "srt",+ "text/vtt": "vtt",+ "application/json": "json",+ "model/gltf-binary": "glb",+ "model/gltf+json": "gltf",};const TYPE_BY_EXT: Record<string, string> = {@@ -39,6 +47,12 @@ const TYPE_BY_EXT: Record<string, string> = {ogg: "audio/ogg",flac: "audio/flac",m4a: "audio/mp4",+ txt: "text/plain",+ srt: "application/x-subrip",+ vtt: "text/vtt",+ json: "application/json",+ glb: "model/gltf-binary",+ gltf: "model/gltf+json",};export function contentTypeFor(fileName: string, fallback = "application/octet-stream"): string {@@ -47,8 +61,12 @@ export function contentTypeFor(fileName: string, fallback = "application/octet-s}export function kindFor(contentType: string): MediaKind {- if (contentType.startsWith("video/")) return "video";- if (contentType.startsWith("audio/")) return "audio";+ const type = contentType.split(";")[0].trim().toLowerCase();+ if (type.startsWith("video/")) return "video";+ if (type.startsWith("audio/")) return "audio";+ // Transcripts, translations and scripts: plain text, subtitles or JSON cue lists.+ if (type.startsWith("text/") || type === "application/json" || type === "application/x-subrip") return "text";+ if (type.startsWith("model/")) return "model3d";return "image";}@@ -104,7 +122,7 @@ export function saveFile(opts: {generationId?: string;}): Asset {const id = nanoid(12);- const ext = EXT_BY_TYPE[opts.contentType] ?? opts.name?.split(".").pop()?.toLowerCase() ?? "bin";+ const ext = EXT_BY_TYPE[opts.contentType.split(";")[0].trim()] ?? opts.name?.split(".").pop()?.toLowerCase() ?? "bin";const day = new Date().toISOString().slice(0, 10);const relPath = path.join(/*turbopackIgnore: true*/ opts.source === "upload" ? "uploads" : "outputs", day, `${id}.${ext}`);const abs = path.join(FILES_DIR, relPath);@@ -182,10 +200,11 @@ export async function readRef(ref: string): Promise<{ data: Buffer; contentType:return { data: fs.readFileSync(abs), contentType: contentTypeFor(abs), name: path.basename(abs) };}if (/^https?:\/\//.test(ref)) {- const res = await fetch(ref);- if (!res.ok) throw new Error(`Could not fetch ${ref}: ${res.status}`);- const contentType = res.headers.get("content-type")?.split(";")[0] ?? contentTypeFor(ref);- return { data: Buffer.from(await res.arrayBuffer()), contentType, name: ref.split("/").pop() ?? "input" };+ // Public links only: never this machine or its private network (see remote-fetch.ts).+ const res = await fetchRemote(ref);+ const path0 = new URL(res.url).pathname;+ const header = res.contentType && res.contentType !== "application/octet-stream" ? res.contentType : null;+ return { data: res.data, contentType: header ?? contentTypeFor(path0), name: path0.split("/").pop() || "input" };}const asset = getAsset(ref);if (!asset) throw new Error(`Unknown asset ${ref}`);diff --git a/tests/remote-fetch.test.ts b/tests/remote-fetch.test.tsnew file mode 100644index 00000000..230a9a0b--- /dev/null+++ b/tests/remote-fetch.test.ts@@ -0,0 +1,94 @@+import fs from "node:fs";+import http from "node:http";+import os from "node:os";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-ssrf-"));+process.env.FUOBE_DATA_DIR = dir;+const { fetchRemote, isPrivateAddress } = await import("@/server/remote-fetch");+const { readRef } = await import("@/server/storage");++let server: http.Server;+let port = 0;++beforeAll(async () => {+ server = http.createServer((req, res) => {+ if (req.url === "/fox.png") {+ res.setHeader("content-type", "image/png");+ return res.end(Buffer.from("89504e470d0a1a0a", "hex"));+ }+ if (req.url === "/to-metadata") {+ res.writeHead(302, { location: "http://169.254.169.254/latest/meta-data/" });+ return res.end();+ }+ if (req.url === "/to-internal") {+ res.writeHead(301, { location: "http://internal.test/admin" });+ return res.end();+ }+ if (req.url === "/to-fox") {+ res.writeHead(307, { location: "/fox.png" });+ return res.end();+ }+ if (req.url === "/big") {+ res.setHeader("content-length", String(10_000));+ return res.end(Buffer.alloc(10_000));+ }+ if (req.url === "/slow") return void setTimeout(() => res.end("late"), 2000);+ res.statusCode = 404;+ res.end();+ });+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));+ port = (server.address() as { port: number }).port;+});+afterAll(() => {+ server.close();+ fs.rmSync(dir, { recursive: true, force: true });+});++// The test server is on loopback: pretend "public.test" is a public host that resolves to it.+const resolve = async (host: string) => (host === "public.test" ? ["127.0.0.1"] : host === "internal.test" ? ["10.0.0.7"] : ["93.184.216.34"]);+const blocked = (ip: string) => ip !== "127.0.0.1" && isPrivateAddress(ip);++describe("remote inputs (S14)", () => {+ it("knows which addresses are private", () => {+ for (const ip of ["127.0.0.1", "10.1.2.3", "172.16.0.1", "192.168.1.10", "169.254.169.254", "100.100.100.200", "0.0.0.0", "::1", "::", "fe80::1", "fd00:ec2::254", "::ffff:127.0.0.1", "::ffff:7f00:1", "64:ff9b::a9fe:a9fe", "2002:7f00:1::"]) {+ expect(isPrivateAddress(ip), ip).toBe(true);+ }+ for (const ip of ["93.184.216.34", "8.8.8.8", "2606:4700:4700::1111", "172.32.0.1"]) expect(isPrivateAddress(ip), ip).toBe(false);+ });++ it("refuses loopback, private and metadata addresses, by IP or by name", async () => {+ await expect(readRef("http://127.0.0.1:1/x.png")).rejects.toThrow(/won't fetch/);+ await expect(readRef("http://169.254.169.254/latest/meta-data/iam/security-credentials/role")).rejects.toThrow(/won't fetch/);+ await expect(readRef("http://[::1]/x.png")).rejects.toThrow(/won't fetch/);+ await expect(readRef("http://localhost:1/x.png")).rejects.toThrow(/won't fetch/);+ await expect(readRef("file:///etc/passwd")).rejects.toThrow();+ await expect(fetchRemote("http://internal.test/x", { resolve })).rejects.toThrow(/won't fetch internal\.test/);+ });++ it("fetches public links, following redirects and checking each hop", async () => {+ const ok = await fetchRemote(`http://public.test:${port}/to-fox`, { resolve, blocked });+ expect(ok.contentType).toBe("image/png");+ expect(ok.data.subarray(0, 4).toString("hex")).toBe("89504e47");+ await expect(fetchRemote(`http://public.test:${port}/to-metadata`, { resolve, blocked })).rejects.toThrow(/won't fetch 169\.254\.169\.254/);+ await expect(fetchRemote(`http://public.test:${port}/to-internal`, { resolve, blocked })).rejects.toThrow(/won't fetch internal\.test/);+ });++ it("caps size and time", async () => {+ await expect(fetchRemote(`http://public.test:${port}/big`, { resolve, blocked, maxBytes: 1000 })).rejects.toThrow(/over/);+ await expect(fetchRemote(`http://public.test:${port}/slow`, { resolve, blocked, timeoutMs: 300 })).rejects.toThrow(/Timed out/);+ await expect(fetchRemote(`http://public.test:${port}/missing`, { resolve, blocked })).rejects.toThrow(/404/);+ });++ it("allows private addresses only when the install opts in", async () => {+ process.env.FUOBE_ALLOW_PRIVATE_URLS = "1";+ try {+ const f = await readRef(`http://127.0.0.1:${port}/fox.png`);+ expect(f.contentType).toBe("image/png");+ expect(f.name).toBe("fox.png");+ } finally {+ delete process.env.FUOBE_ALLOW_PRIVATE_URLS;+ }+ });+});diff --git a/tests/runtime-auth.test.ts b/tests/runtime-auth.test.tsnew file mode 100644index 00000000..cf88dc84--- /dev/null+++ b/tests/runtime-auth.test.ts@@ -0,0 +1,96 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, describe, expect, it } from "vitest";+import { NextRequest } from "next/server";++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-auth-rt-"));+process.env.FUOBE_DATA_DIR = dir;+delete process.env.FUOBE_PASSWORD;+const auth = await import("@/server/auth");+const { proxy, config } = await import("@/proxy");+const { safeNext } = await import("@/lib/safe-redirect");+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++const post = (url: string, headers: Record<string, string> = {}) => new NextRequest(url, { method: "POST", headers, body: "{}" });++describe("cross-site requests (S8)", () => {+ it("blocks state changes from other websites, password or not", async () => {+ expect(auth.authEnabled()).toBe(false);+ const evil = proxy(post("http://localhost:3000/api/auth/password", { origin: "http://evil.example", "content-type": "text/plain" }));+ expect(evil.status).toBe(403);+ expect((await evil.json()).error).toMatch(/another website/);+ expect(proxy(post("http://localhost:3000/api/generations", { origin: "null" })).status).toBe(403);+ expect(proxy(post("http://localhost:3000/api/generations", { "sec-fetch-site": "cross-site" })).status).toBe(403);+ // Another port on localhost is another origin.+ expect(proxy(post("http://localhost:3000/api/generations", { origin: "http://localhost:5173" })).status).toBe(403);+ });++ it("lets the studio's own pages, non-browser clients and reads through", () => {+ const ok = (r: Response) => r.headers.get("x-middleware-next") === "1";+ expect(ok(proxy(post("http://localhost:3000/api/generations", { origin: "http://localhost:3000" })))).toBe(true);+ expect(ok(proxy(post("http://localhost:3000/api/mcp")))).toBe(true);+ expect(ok(proxy(new NextRequest("http://localhost:3000/api/generations", { headers: { origin: "http://evil.example" } })))).toBe(true);+ // Behind a reverse proxy that forwards the public host.+ expect(ok(proxy(post("http://127.0.0.1:3000/api/generations", { origin: "https://fuobe.example.com", "x-forwarded-host": "fuobe.example.com" })))).toBe(true);+ process.env.FUOBE_ALLOWED_ORIGINS = "https://studio.example.org";+ try {+ expect(ok(proxy(post("http://127.0.0.1:3000/api/generations", { origin: "https://studio.example.org" })))).toBe(true);+ } finally {+ delete process.env.FUOBE_ALLOWED_ORIGINS;+ }+ });+});++describe("sign-in lockout (S10)", () => {+ it("ignores spoofed X-Forwarded-For unless a trusted proxy sets it", () => {+ const h = (xff: string) => new Headers({ "x-forwarded-for": xff });+ expect(auth.LoginGuard.clientKey(h("1.2.3.4"), false)).toBe("direct");+ expect(auth.LoginGuard.clientKey(h("6.6.6.6, 1.2.3.4"), true)).toBe("1.2.3.4");+ });++ it("locks a client after 5 misses, and everyone after too many misses overall", () => {+ const g = new auth.LoginGuard({ perClient: 5, global: 20, windowMs: 60_000, lockMs: 60_000, maxClients: 5000 });+ const t = 1_000_000;+ for (let i = 0; i < 4; i++) g.fail("a", t + i);+ expect(g.blockedFor("a", t + 5)).toBe(0);+ g.fail("a", t + 5);+ expect(g.blockedFor("a", t + 6)).toBeGreaterThan(50_000);+ expect(g.blockedFor("b", t + 6)).toBe(0);+ // Rotating the key doesn't help: the global budget runs out.+ for (let i = 0; i < 15; i++) g.fail(`spoof-${i}`, t + 10 + i);+ expect(g.blockedFor("fresh", t + 30)).toBeGreaterThan(0);+ expect(g.blockedFor("fresh", t + 120_000)).toBe(0);+ });++ it("keeps its memory bounded", () => {+ const g = new auth.LoginGuard({ perClient: 5, global: 1e9, windowMs: 60_000, lockMs: 60_000, maxClients: 100 });+ for (let i = 0; i < 5000; i++) g.fail(`k${i}`, 1_000_000 + i);+ expect(g.size).toBeLessThanOrEqual(101);+ });+});++describe("after sign-in (C5)", () => {+ const origin = "http://localhost:3000";+ it("only goes to pages on this site", () => {+ expect(safeNext("/video?model=kling-3#x", origin)).toBe("/video?model=kling-3#x");+ expect(safeNext(null, origin)).toBe("/");+ for (const bad of ["//evil.example", "/\\evil.example", "/\t/evil.example", "https://evil.example/", "javascript:alert(1)", "\\\\evil.example"]) {+ expect(safeNext(bad, origin), bad).toBe("/");+ }+ });+});++describe("proxy matcher (C13)", () => {+ // path-to-regexp turns "/(…)" into this group.+ const matches = (p: string) => new RegExp(`^${config.matcher[0]}$`).test(p);+ it("gates generated SVGs but not the public folder's files", () => {+ expect(matches("/api/files/outputs/2026-10-17/abc.svg")).toBe(true);+ expect(matches("/api/generations")).toBe(true);+ expect(matches("/library")).toBe(true);+ expect(matches("/next.svg")).toBe(false);+ expect(matches("/samples/demo-model.glb")).toBe(false);+ expect(matches("/favicon.ico")).toBe(false);+ expect(matches("/_next/static/chunks/a.js")).toBe(false);+ });+});