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
Real 404s: unknown project, canvas, channel… ids and hub modes answer 404, not a not-found state with 200
Claude334d6d8d1bfe
diff --git a/src/app/(studio)/ads/[brandId]/page.tsx b/src/app/(studio)/ads/[brandId]/page.tsxindex db7f8769..746058db 100644--- a/src/app/(studio)/ads/[brandId]/page.tsx+++ b/src/app/(studio)/ads/[brandId]/page.tsx@@ -1,11 +1,14 @@import type { Metadata } from "next";+import { notFound } from "next/navigation";import { Suspense } from "react";import { BrandWorkspace } from "@/components/ads/brand-workspace";+import { recordExists } from "@/server/records";export const metadata: Metadata = { title: "Ads Studio" };async function Workspace({ params }: { params: PageProps<"/ads/[brandId]">["params"] }) {const { brandId } = await params;+ if (!recordExists({ kind: "brand", ids: [brandId] })) notFound();return <BrandWorkspace brandId={brandId} />;}diff --git a/src/app/(studio)/assist/projects/[id]/page.tsx b/src/app/(studio)/assist/projects/[id]/page.tsxindex cf6e69a3..64082a93 100644--- a/src/app/(studio)/assist/projects/[id]/page.tsx+++ b/src/app/(studio)/assist/projects/[id]/page.tsx@@ -1,11 +1,14 @@import type { Metadata } from "next";+import { notFound } from "next/navigation";import { Suspense } from "react";import { ProjectView } from "@/components/assist/project-view";+import { recordExists } from "@/server/records";export const metadata: Metadata = { title: "Project" };async function Project({ params }: { params: PageProps<"/assist/projects/[id]">["params"] }) {const { id } = await params;+ if (!recordExists({ kind: "assist-project", ids: [id] })) notFound();return <ProjectView id={id} />;}diff --git a/src/app/(studio)/canvas/[id]/page.tsx b/src/app/(studio)/canvas/[id]/page.tsxindex 926462ca..0f6b075b 100644--- a/src/app/(studio)/canvas/[id]/page.tsx+++ b/src/app/(studio)/canvas/[id]/page.tsx@@ -1,11 +1,14 @@import type { Metadata } from "next";+import { notFound } from "next/navigation";import { Suspense } from "react";import { CanvasEditor } from "@/components/canvas/canvas-editor";+import { recordExists } from "@/server/records";export const metadata: Metadata = { title: "Canvas" };async function Editor({ params }: { params: PageProps<"/canvas/[id]">["params"] }) {const { id } = await params;+ if (!recordExists({ kind: "canvas", ids: [id] })) notFound();return <CanvasEditor id={id} />;}diff --git a/src/app/(studio)/cinema/[id]/page.tsx b/src/app/(studio)/cinema/[id]/page.tsxindex 0f0ee7f3..e47ff32c 100644--- a/src/app/(studio)/cinema/[id]/page.tsx+++ b/src/app/(studio)/cinema/[id]/page.tsx@@ -1,11 +1,14 @@import type { Metadata } from "next";+import { notFound } from "next/navigation";import { Suspense } from "react";import { CinemaWorkspace } from "@/components/cinema/workspace";+import { recordExists } from "@/server/records";export const metadata: Metadata = { title: "Cinema Studio" };async function Workspace({ params }: { params: PageProps<"/cinema/[id]">["params"] }) {const { id } = await params;+ if (!recordExists({ kind: "cinema", ids: [id] })) notFound();return <CinemaWorkspace id={id} />;}diff --git a/src/app/(studio)/elements/[id]/page.tsx b/src/app/(studio)/elements/[id]/page.tsxindex 6624ab21..6030dbec 100644--- a/src/app/(studio)/elements/[id]/page.tsx+++ b/src/app/(studio)/elements/[id]/page.tsx@@ -1,12 +1,15 @@import type { Metadata } from "next";+import { notFound } from "next/navigation";import { Suspense } from "react";import { ElementStudio } from "@/components/element-studio";import { StudioSkeleton } from "@/components/skeletons";+import { recordExists } from "@/server/records";export const metadata: Metadata = { title: "Element" };async function Studio({ params }: { params: PageProps<"/elements/[id]">["params"] }) {const { id } = await params;+ if (!recordExists({ kind: "element", ids: [id] })) notFound();return <ElementStudio id={id} />;}diff --git a/src/app/(studio)/explainer/[id]/page.tsx b/src/app/(studio)/explainer/[id]/page.tsxindex f579f91a..1a0b8ffe 100644--- a/src/app/(studio)/explainer/[id]/page.tsx+++ b/src/app/(studio)/explainer/[id]/page.tsx@@ -1,11 +1,14 @@import type { Metadata } from "next";+import { notFound } from "next/navigation";import { Suspense } from "react";import { EpisodeView } from "@/components/faceless/episode-view";+import { recordExists } from "@/server/records";export const metadata: Metadata = { title: "Explainer" };async function Explainer({ params }: { params: PageProps<"/explainer/[id]">["params"] }) {const { id } = await params;+ if (!recordExists({ kind: "explainer", ids: [id] })) notFound();return <EpisodeView id={id} backHref="/explainer" backLabel="Explainer" />;}diff --git a/src/app/(studio)/faceless/[id]/[episode]/page.tsx b/src/app/(studio)/faceless/[id]/[episode]/page.tsxindex f6277745..1e20d6dd 100644--- a/src/app/(studio)/faceless/[id]/[episode]/page.tsx+++ b/src/app/(studio)/faceless/[id]/[episode]/page.tsx@@ -1,11 +1,14 @@import type { Metadata } from "next";+import { notFound } from "next/navigation";import { Suspense } from "react";import { EpisodeView } from "@/components/faceless/episode-view";+import { recordExists } from "@/server/records";export const metadata: Metadata = { title: "Episode" };async function Episode({ params }: { params: PageProps<"/faceless/[id]/[episode]">["params"] }) {const { id, episode } = await params;+ if (!recordExists({ kind: "episode", ids: [id, episode] })) notFound();return <EpisodeView id={episode} backHref={`/faceless/${id}`} backLabel="Channel" />;}diff --git a/src/app/(studio)/faceless/[id]/new/page.tsx b/src/app/(studio)/faceless/[id]/new/page.tsxindex b7e0ac34..cf0470a9 100644--- a/src/app/(studio)/faceless/[id]/new/page.tsx+++ b/src/app/(studio)/faceless/[id]/new/page.tsx@@ -1,13 +1,16 @@import type { Metadata } from "next";+import { notFound } from "next/navigation";import { Suspense } from "react";import { EpisodeWizard } from "@/components/faceless/episode-wizard";import { getModel } from "@/lib/catalog";import { pickerData } from "@/lib/catalog/faceless";+import { recordExists } from "@/server/records";export const metadata: Metadata = { title: "New episode" };async function Wizard({ params }: { params: PageProps<"/faceless/[id]/new">["params"] }) {const { id } = await params;+ if (!recordExists({ kind: "channel", ids: [id] })) notFound();return <EpisodeWizard channelId={id} picker={pickerData(getModel)} />;}diff --git a/src/app/(studio)/faceless/[id]/page.tsx b/src/app/(studio)/faceless/[id]/page.tsxindex fb6f8293..4ddde4a9 100644--- a/src/app/(studio)/faceless/[id]/page.tsx+++ b/src/app/(studio)/faceless/[id]/page.tsx@@ -1,13 +1,16 @@import type { Metadata } from "next";+import { notFound } from "next/navigation";import { Suspense } from "react";import { ChannelView } from "@/components/faceless/channel-view";import { getModel } from "@/lib/catalog";import { pickerData } from "@/lib/catalog/faceless";+import { recordExists } from "@/server/records";export const metadata: Metadata = { title: "Faceless channel" };async function Channel({ params }: { params: PageProps<"/faceless/[id]">["params"] }) {const { id } = await params;+ if (!recordExists({ kind: "channel", ids: [id] })) notFound();return <ChannelView id={id} picker={pickerData(getModel)} />;}diff --git a/src/app/(studio)/layers/[id]/page.tsx b/src/app/(studio)/layers/[id]/page.tsxindex c573d687..98051b3e 100644--- a/src/app/(studio)/layers/[id]/page.tsx+++ b/src/app/(studio)/layers/[id]/page.tsx@@ -1,8 +1,10 @@import type { Metadata } from "next";+import { notFound } from "next/navigation";import { Suspense } from "react";import { LayersEditor } from "@/components/layers/layers-editor";import { getModel } from "@/lib/catalog";import { CUTOUT_MODELS, TOOL_MODELS, type LayerModelInfo } from "@/lib/layers";+import { recordExists } from "@/server/records";export const metadata: Metadata = { title: "Layers" };@@ -27,6 +29,7 @@ function toolModels(): Record<string, LayerModelInfo> {async function Editor({ params }: { params: PageProps<"/layers/[id]">["params"] }) {const { id } = await params;+ if (!recordExists({ kind: "layers", ids: [id] })) notFound();return <LayersEditor id={id} models={toolModels()} />;}diff --git a/src/app/(studio)/shorts/[id]/page.tsx b/src/app/(studio)/shorts/[id]/page.tsxindex 6bb39d42..30c9263f 100644--- a/src/app/(studio)/shorts/[id]/page.tsx+++ b/src/app/(studio)/shorts/[id]/page.tsx@@ -1,11 +1,14 @@import type { Metadata } from "next";+import { notFound } from "next/navigation";import { Suspense } from "react";import { ShortsSessionView } from "@/components/shorts/session-view";+import { recordExists } from "@/server/records";export const metadata: Metadata = { title: "Your short" };async function Session({ params }: { params: PageProps<"/shorts/[id]">["params"] }) {const { id } = await params;+ if (!recordExists({ kind: "shorts", ids: [id] })) notFound();return <ShortsSessionView id={id} />;}diff --git a/src/lib/record-pages.ts b/src/lib/record-pages.tsnew file mode 100644index 00000000..155916fb--- /dev/null+++ b/src/lib/record-pages.ts@@ -0,0 +1,64 @@+/**+ * Pages whose URL names a stored record (/cinema/<id>, /faceless/<channel>/<episode>…), so an+ * unknown id can get a real 404. The page's own notFound() can't send one: the studio's loading+ * skeleton (and with Cache Components, the prerendered shell) has already streamed with a 200 by+ * the time the page looks the id up. The proxy checks first (src/proxy.ts → recordExists in+ * src/server/records.ts) and rewrites unknown ids to the not-found page with a 404.+ * Pure, so the route table is tested without a server.+ */+import { HUB_MODES, type HubKind } from "./hubs";++export type RecordKind = "cinema" | "canvas" | "assist-project" | "layers" | "shorts" | "brand" | "element" | "channel" | "episode" | "explainer";++/** A record a page needs, with its ids in the order the lookup takes them. */+export interface RecordRef {+ kind: RecordKind;+ ids: string[];+}++const SEG = "([^/]+)";++/** Path patterns → the record they name. Fixed sub-pages (/faceless/<id>/new) come before the catch-alls. */+const PAGES: [RegExp, (m: string[]) => RecordRef][] = [+ [new RegExp(`^/cinema/${SEG}$`), ([id]) => ({ kind: "cinema", ids: [id] })],+ [new RegExp(`^/canvas/${SEG}$`), ([id]) => ({ kind: "canvas", ids: [id] })],+ [new RegExp(`^/assist/projects/${SEG}$`), ([id]) => ({ kind: "assist-project", ids: [id] })],+ [new RegExp(`^/layers/${SEG}$`), ([id]) => ({ kind: "layers", ids: [id] })],+ [new RegExp(`^/shorts/${SEG}$`), ([id]) => ({ kind: "shorts", ids: [id] })],+ [new RegExp(`^/ads/${SEG}$`), ([id]) => ({ kind: "brand", ids: [id] })],+ [new RegExp(`^/elements/${SEG}$`), ([id]) => ({ kind: "element", ids: [id] })],+ [new RegExp(`^/faceless/${SEG}/new$`), ([id]) => ({ kind: "channel", ids: [id] })],+ [new RegExp(`^/faceless/${SEG}/${SEG}$`), ([id, episode]) => ({ kind: "episode", ids: [id, episode] })],+ [new RegExp(`^/faceless/${SEG}$`), ([id]) => ({ kind: "channel", ids: [id] })],+ [new RegExp(`^/explainer/${SEG}$`), ([id]) => ({ kind: "explainer", ids: [id] })],+];++/** Static pages that a record pattern would also match (/ads/multiplier is not a brand). */+const FIXED = new Set(["/ads/multiplier"]);++function decode(s: string): string {+ try {+ return decodeURIComponent(s);+ } catch {+ return s;+ }+}++/** The record a page path names (null for every other page). A trailing slash is ignored. */+export function recordForPath(pathname: string): RecordRef | null {+ const path = pathname.length > 1 ? pathname.replace(/\/+$/, "") : pathname;+ if (FIXED.has(path)) return null;+ for (const [re, ref] of PAGES) {+ const m = re.exec(path);+ if (m) return ref(m.slice(1).map(decode));+ }+ return null;+}++/** /audio/<mode>, /video-tools/<mode> and /upscale/<mode> with a mode the hub doesn't have. */+export function unknownHubMode(pathname: string): boolean {+ const m = /^\/(audio|video-tools|upscale)\/([^/]+)\/?$/.exec(pathname);+ if (!m) return false;+ const mode = decode(m[2]);+ return !HUB_MODES[m[1] as HubKind].some((x) => x.id === mode);+}diff --git a/src/proxy.ts b/src/proxy.tsindex 06159936..8b7c9d23 100644--- a/src/proxy.ts+++ b/src/proxy.ts@@ -1,6 +1,8 @@import { NextResponse, type NextRequest } from "next/server";import { APPS } from "@/lib/catalog/apps";+import { recordForPath, unknownHubMode } from "@/lib/record-pages";import { authEnabled, crossSite, hostAllowed, SESSION_COOKIE, validSession, validToken } from "@/server/auth";+import { recordExists } from "@/server/records";/** Paths that work signed out: the login page and its API. */const OPEN = new Set(["/login", "/api/auth/login"]);@@ -8,16 +10,25 @@ const OPEN = new Set(["/login", "/api/auth/login"]);const APP_IDS = new Set(APPS.map((a) => a.id));/**- * Let the request through — except /apps/<id> for an app that doesn't exist, which gets a real 404.- * The page can't send one itself: the studio's loading.tsx streams the shell (with a 200) before- * the page knows the id is unknown.+ * Let the request through — except a page for something that doesn't exist (an unknown app or hub+ * mode, a project / canvas / channel… id that isn't stored), which gets a real 404. The page can't+ * send one itself: the studio's loading.tsx streams the shell (with a 200) before the page knows+ * the id is unknown. Records are checked on document loads only: a client-side navigation (an RSC+ * request) gets the page's own notFound() in place, without a reload.*/function pass(request: NextRequest): NextResponse {- const app = /^\/apps\/([^/]+)\/?$/.exec(request.nextUrl.pathname)?.[1];- if (app && !APP_IDS.has(safeDecode(app))) return NextResponse.rewrite(new URL("/_fuobe-not-found", request.url), { status: 404 });+ const { pathname } = request.nextUrl;+ const app = /^\/apps\/([^/]+)\/?$/.exec(pathname)?.[1];+ if ((app && !APP_IDS.has(safeDecode(app))) || unknownHubMode(pathname)) return notFound(request);+ if (!request.headers.has("rsc")) {+ const record = recordForPath(pathname);+ if (record && !recordExists(record)) return notFound(request);+ }return NextResponse.next();}+const notFound = (request: NextRequest) => NextResponse.rewrite(new URL("/_fuobe-not-found", request.url), { status: 404 });+function safeDecode(s: string): string {try {return decodeURIComponent(s);diff --git a/src/server/records.ts b/src/server/records.tsnew file mode 100644index 00000000..187ee8e2--- /dev/null+++ b/src/server/records.ts@@ -0,0 +1,31 @@+import "server-only";+import type { RecordRef } from "@/lib/record-pages";+import { db } from "./db";++/** The table and id columns behind each kind of record page (the ids are the page's segments, in order). */+const LOOKUPS: Record<RecordRef["kind"], string> = {+ cinema: "SELECT 1 FROM cinema_projects WHERE id = ?",+ canvas: "SELECT 1 FROM canvases WHERE id = ?",+ "assist-project": "SELECT 1 FROM assist_projects WHERE id = ?",+ layers: "SELECT 1 FROM layer_projects WHERE id = ?",+ shorts: "SELECT 1 FROM shorts_sessions WHERE id = ?",+ brand: "SELECT 1 FROM brand_kits WHERE id = ?",+ element: "SELECT 1 FROM characters WHERE id = ?",+ channel: "SELECT 1 FROM faceless_channels WHERE id = ?",+ episode: "SELECT 1 FROM faceless_episodes WHERE channel_id = ? AND id = ?",+ explainer: "SELECT 1 FROM faceless_episodes WHERE id = ?",+};++/**+ * Whether the record a page names is stored (a primary-key lookup). Used by the proxy, so an+ * unknown id gets a real 404 before the page's shell streams, and by the pages themselves+ * (notFound() for client-side navigations). A database that can't be read counts as "exists": the+ * page then shows its own state rather than a wrong 404.+ */+export function recordExists(ref: RecordRef): boolean {+ try {+ return !!db().prepare(LOOKUPS[ref.kind]).get(...ref.ids);+ } catch {+ return true;+ }+}diff --git a/tests/record-pages.test.ts b/tests/record-pages.test.tsnew file mode 100644index 00000000..c454a798--- /dev/null+++ b/tests/record-pages.test.ts@@ -0,0 +1,83 @@+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";+import { recordForPath, unknownHubMode } from "@/lib/record-pages";++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-records-"));+process.env.FUOBE_DATA_DIR = dir;+delete process.env.FUOBE_PASSWORD;+const { db } = await import("@/server/db");+const { recordExists } = await import("@/server/records");+const { proxy } = await import("@/proxy");+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++/** Where the proxy sent a page request: its own path, or the not-found page (with the status). */+function routed(pathname: string): { status: number; to: string | null } {+ const res = proxy(new NextRequest(`http://localhost:3000${pathname}`, { headers: { host: "localhost:3000" } }));+ return { status: res.status, to: res.headers.get("x-middleware-rewrite") };+}++describe("record pages (real 404s)", () => {+ it("names the record behind every id page", () => {+ expect(recordForPath("/cinema/abc")).toEqual({ kind: "cinema", ids: ["abc"] });+ expect(recordForPath("/canvas/abc/")).toEqual({ kind: "canvas", ids: ["abc"] });+ expect(recordForPath("/assist/projects/p1")).toEqual({ kind: "assist-project", ids: ["p1"] });+ expect(recordForPath("/layers/l1")).toEqual({ kind: "layers", ids: ["l1"] });+ expect(recordForPath("/shorts/s1")).toEqual({ kind: "shorts", ids: ["s1"] });+ expect(recordForPath("/ads/b1")).toEqual({ kind: "brand", ids: ["b1"] });+ expect(recordForPath("/elements/e%201")).toEqual({ kind: "element", ids: ["e 1"] });+ expect(recordForPath("/faceless/c1")).toEqual({ kind: "channel", ids: ["c1"] });+ expect(recordForPath("/faceless/c1/new")).toEqual({ kind: "channel", ids: ["c1"] });+ expect(recordForPath("/faceless/c1/ep1")).toEqual({ kind: "episode", ids: ["c1", "ep1"] });+ expect(recordForPath("/explainer/x1")).toEqual({ kind: "explainer", ids: ["x1"] });+ });++ it("leaves list pages and fixed sub-pages alone", () => {+ for (const p of ["/", "/cinema", "/canvas/", "/ads", "/ads/multiplier", "/assist/projects", "/assist/skills", "/faceless", "/explainer", "/library", "/apps/app-face-swap", "/cinema/a/b"]) {+ expect(recordForPath(p), p).toBeNull();+ }+ });++ it("knows each hub's modes", () => {+ expect(unknownHubMode("/audio/music")).toBe(false);+ expect(unknownHubMode("/video-tools/trim/")).toBe(false);+ expect(unknownHubMode("/upscale/video")).toBe(false);+ expect(unknownHubMode("/audio/nope")).toBe(true);+ expect(unknownHubMode("/video-tools/captions%20x")).toBe(true);+ // The hub's own page and other paths aren't hub modes.+ expect(unknownHubMode("/audio")).toBe(false);+ expect(unknownHubMode("/apps/nope")).toBe(false);+ });++ it("looks the record up in its table", () => {+ const now = Date.now();+ db().prepare("INSERT INTO canvases (id, name, created_at, updated_at) VALUES (?, ?, ?, ?)").run("cv1", "Board", now, now);+ db()+ .prepare("INSERT INTO faceless_channels (id, name, idea, genre, settings_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)")+ .run("ch1", "Channel", "idea", "history", "{}", now, now);+ db()+ .prepare("INSERT INTO faceless_episodes (id, channel_id, kind, title, topic, status, settings_json, script_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")+ .run("ep1", "ch1", "faceless", "Episode", "topic", "draft", "{}", "[]", now, now);+ expect(recordExists({ kind: "canvas", ids: ["cv1"] })).toBe(true);+ expect(recordExists({ kind: "canvas", ids: ["nope"] })).toBe(false);+ expect(recordExists({ kind: "cinema", ids: ["cv1"] })).toBe(false);+ expect(recordExists({ kind: "channel", ids: ["ch1"] })).toBe(true);+ expect(recordExists({ kind: "episode", ids: ["ch1", "ep1"] })).toBe(true);+ // An episode of another channel is not this channel's episode.+ expect(recordExists({ kind: "episode", ids: ["other", "ep1"] })).toBe(false);+ expect(recordExists({ kind: "explainer", ids: ["ep1"] })).toBe(true);+ });++ it("answers unknown ids with a 404 before the page streams", () => {+ expect(routed("/canvas/nope")).toEqual({ status: 404, to: "http://localhost:3000/_fuobe-not-found" });+ expect(routed("/faceless/ch1/nope").status).toBe(404);+ expect(routed("/audio/nope").status).toBe(404);+ expect(routed("/apps/nope").status).toBe(404);+ // Stored records, real modes and other pages go through.+ for (const p of ["/canvas/cv1", "/faceless/ch1", "/faceless/ch1/new", "/faceless/ch1/ep1", "/audio/music", "/ads/multiplier", "/library"]) {+ expect(routed(p), p).toEqual({ status: 200, to: null });+ }+ });+});