The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Accounts 2: every route goes through handler()
Claude556a29a7f12c
diff --git a/src/app/api/ads/batches/route.ts b/src/app/api/ads/batches/route.tsindex 66cc78ae..eb813721 100644--- a/src/app/api/ads/batches/route.ts+++ b/src/app/api/ads/batches/route.ts@@ -1,9 +1,10 @@import { after } from "next/server";import { BatchBody, createBatch } from "@/server/ads";import { failure, readBody } from "@/server/marketing";+import { handler } from "@/server/access/route";/** "Create N ads": creatives land in the grid at once; copy and pictures follow in the background. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const body = await readBody(request, BatchBody, "Pick products and how many ads to make");if (body instanceof Response) return body;try {@@ -13,4 +14,4 @@ export async function POST(request: Request) {} catch (e) {return failure(e);}-}+});diff --git a/src/app/api/ads/creatives/[id]/retry/route.ts b/src/app/api/ads/creatives/[id]/retry/route.tsindex a130ce06..b52875b0 100644--- a/src/app/api/ads/creatives/[id]/retry/route.ts+++ b/src/app/api/ads/creatives/[id]/retry/route.ts@@ -1,12 +1,13 @@import { retryCreative } from "@/server/ads";import { failure } from "@/server/marketing";+import { handler } from "@/server/access/route";/** Make a failed ad again (this spends credits again). */-export async function POST(_req: Request, ctx: RouteContext<"/api/ads/creatives/[id]/retry">) {+export const POST = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/ads/creatives/[id]/retry">) => {const { id } = await ctx.params;try {return Response.json(await retryCreative(id), { status: 201 });} catch (e) {return (e as Error).message === "Not found" ? Response.json({ error: "Not found" }, { status: 404 }) : failure(e);}-}+});diff --git a/src/app/api/ads/creatives/[id]/route.ts b/src/app/api/ads/creatives/[id]/route.tsindex d2baef11..edbafe7d 100644--- a/src/app/api/ads/creatives/[id]/route.ts+++ b/src/app/api/ads/creatives/[id]/route.ts@@ -1,17 +1,18 @@import { CreativePatch, deleteCreative, updateCreative } from "@/server/ads";import { readBody } from "@/server/marketing";+import { handler } from "@/server/access/route";/** Edit an ad's words or layout (the picture stays). */-export async function PATCH(request: Request, ctx: RouteContext<"/api/ads/creatives/[id]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/ads/creatives/[id]">) => {const { id } = await ctx.params;const body = await readBody(request, CreativePatch, "Check the ad's text");if (body instanceof Response) return body;const c = updateCreative(id, body);return c ? Response.json(c) : Response.json({ error: "Not found" }, { status: 404 });-}+});/** Remove an ad from the grid (its picture stays in the Library). */-export async function DELETE(_req: Request, ctx: RouteContext<"/api/ads/creatives/[id]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/ads/creatives/[id]">) => {const { id } = await ctx.params;return deleteCreative(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });-}+});diff --git a/src/app/api/ads/creatives/[id]/save/route.ts b/src/app/api/ads/creatives/[id]/save/route.tsindex 11de5945..02edb761 100644--- a/src/app/api/ads/creatives/[id]/save/route.ts+++ b/src/app/api/ads/creatives/[id]/save/route.ts@@ -1,11 +1,12 @@import { z } from "zod";import { saveComposite } from "@/server/ads";import { failure, readBody } from "@/server/marketing";+import { handler } from "@/server/access/route";const Body = z.object({ url: z.string().startsWith("/api/files/"), ratio: z.enum(["1:1", "4:5", "9:16"]) });/** Record a creative composited in the browser (an uploaded PNG) in the Library. */-export async function POST(request: Request, ctx: RouteContext<"/api/ads/creatives/[id]/save">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/ads/creatives/[id]/save">) => {const { id } = await ctx.params;const body = await readBody(request, Body, "Upload the image first");if (body instanceof Response) return body;@@ -14,4 +15,4 @@ export async function POST(request: Request, ctx: RouteContext<"/api/ads/creativ} catch (e) {return (e as Error).message === "Not found" ? Response.json({ error: "Not found" }, { status: 404 }) : failure(e);}-}+});diff --git a/src/app/api/ads/creatives/route.ts b/src/app/api/ads/creatives/route.tsindex 684aca37..c9e31826 100644--- a/src/app/api/ads/creatives/route.ts+++ b/src/app/api/ads/creatives/route.ts@@ -1,11 +1,12 @@import { connection } from "next/server";import { listCreatives } from "@/server/ads";+import { handler } from "@/server/access/route";/** A brand's ads (`?brand=<id>`, optionally `&batch=` or `&product=`), newest run first. */-export async function GET(request: Request) {+export const GET = handler({ access: "signed-in" }, async (request: Request) => {await connection();const q = new URL(request.url).searchParams;const brandId = q.get("brand");if (!brandId) return Response.json({ error: "Pick a brand" }, { status: 400 });return Response.json({ items: listCreatives({ brandId, batchId: q.get("batch") ?? undefined, productId: q.get("product") ?? undefined }) });-}+});diff --git a/src/app/api/ads/estimate/route.ts b/src/app/api/ads/estimate/route.tsindex ae2d9285..28c66577 100644--- a/src/app/api/ads/estimate/route.ts+++ b/src/app/api/ads/estimate/route.ts@@ -1,8 +1,9 @@import { BatchBody, estimateBatch } from "@/server/ads";import { readBody } from "@/server/marketing";+import { handler } from "@/server/access/route";/** The total before the run: ads × price per ad (+ the copy), and which model renders them. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const body = await readBody(request, BatchBody, "Pick products and how many ads to make");if (body instanceof Response) return body;try {@@ -10,4 +11,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ costUsd: null, total: 0, perAd: null, demo: false, blocker: (e as Error).message });}-}+});diff --git a/src/app/api/ads/multiplier/estimate/route.ts b/src/app/api/ads/multiplier/estimate/route.tsindex a8d6f938..dc1586c6 100644--- a/src/app/api/ads/multiplier/estimate/route.ts+++ b/src/app/api/ads/multiplier/estimate/route.ts@@ -1,6 +1,7 @@import { estimateMultiplier, MultiplierBody, readBody } from "@/server/marketing";+import { handler } from "@/server/access/route";-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const body = await readBody(request, MultiplierBody, "Add a reference video to recreate");if (body instanceof Response) return body;try {@@ -8,4 +9,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ costUsd: null, demo: false, steps: [], notes: [], runs: 0, blocker: (e as Error).message });}-}+});diff --git a/src/app/api/ads/multiplier/route.ts b/src/app/api/ads/multiplier/route.tsindex f6125701..7bf897de 100644--- a/src/app/api/ads/multiplier/route.ts+++ b/src/app/api/ads/multiplier/route.ts@@ -1,7 +1,8 @@import { failure, MultiplierBody, readBody, runMultiplier } from "@/server/marketing";+import { handler } from "@/server/access/route";/** Ad Multiplier: new versions of a reference ad (the whole ad from a prompt, or a new hook / CTA around it). */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const body = await readBody(request, MultiplierBody, "Add a reference video to recreate");if (body instanceof Response) return body;try {@@ -9,4 +10,4 @@ export async function POST(request: Request) {} catch (e) {return failure(e);}-}+});diff --git a/src/app/api/assets/[id]/route.ts b/src/app/api/assets/[id]/route.tsindex 0c142bd9..0c75cefe 100644--- a/src/app/api/assets/[id]/route.ts+++ b/src/app/api/assets/[id]/route.ts@@ -3,19 +3,20 @@ import { assetUses } from "@/server/generations";import { deleteUnusedAsset } from "@/server/library";import { getAsset } from "@/server/storage";import { describeUses } from "@/lib/library";+import { handler } from "@/server/access/route";/** A stored file and where it's used (`uses`, and `usedBy`: the same in one line, empty when nothing uses it). */-export async function GET(_req: Request, ctx: RouteContext<"/api/assets/[id]">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assets/[id]">) => {await connection();const { id } = await ctx.params;const asset = getAsset(id);if (!asset) return Response.json({ error: "Not found" }, { status: 404 });const uses = assetUses(id);return Response.json({ ...asset, uses, usedBy: describeUses(uses) });-}+});/** Delete the file for good, only when nothing uses it (409 with `uses` and `usedBy` otherwise). */-export async function DELETE(_req: Request, ctx: RouteContext<"/api/assets/[id]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assets/[id]">) => {const { id } = await ctx.params;const r = deleteUnusedAsset(id);if (!r) return Response.json({ error: "That file is already gone" }, { status: 404 });@@ -24,4 +25,4 @@ export async function DELETE(_req: Request, ctx: RouteContext<"/api/assets/[id]"return Response.json({ error: `It's still used by ${usedBy}.`, uses: r.uses, usedBy }, { status: 409 });}return new Response(null, { status: 204 });-}+});diff --git a/src/app/api/assets/route.ts b/src/app/api/assets/route.tsindex 88181793..df2d4899 100644--- a/src/app/api/assets/route.ts+++ b/src/app/api/assets/route.ts@@ -2,9 +2,10 @@ import { connection } from "next/server";import { listAssets } from "@/server/storage";import { cursorFrom } from "@/server/library";import type { MediaKind } from "@/lib/catalog/types";+import { handler } from "@/server/access/route";/** Stored files, newest first: source / kind filters, limit, and paging with before=<createdAt>:<id> of the last one. */-export async function GET(request: Request) {+export const GET = handler({ access: "signed-in" }, async (request: Request) => {await connection();const u = new URL(request.url);return Response.json({@@ -15,4 +16,4 @@ export async function GET(request: Request) {...cursorFrom(u.searchParams.get("before")),}),});-}+});diff --git a/src/app/api/assist/[id]/approval/route.ts b/src/app/api/assist/[id]/approval/route.tsindex 2d548cc6..0311922d 100644--- a/src/app/api/assist/[id]/approval/route.ts+++ b/src/app/api/assist/[id]/approval/route.ts@@ -1,11 +1,12 @@import { after } from "next/server";import { z } from "zod";import { answerApproval, AssistBusyError, run } from "@/server/assist/agent";+import { handler } from "@/server/access/route";const Body = z.object({ approve: z.boolean() });/** Approve (run) or decline the plan on the thread's approval card; the agent then carries on. */-export async function POST(request: Request, ctx: RouteContext<"/api/assist/[id]/approval">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/assist/[id]/approval">) => {const { id } = await ctx.params;const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Say approve true or false" }, { status: 400 });@@ -17,4 +18,4 @@ export async function POST(request: Request, ctx: RouteContext<"/api/assist/[id]} catch (e) {return Response.json({ error: (e as Error).message }, { status: e instanceof AssistBusyError ? 409 : 404 });}-}+});diff --git a/src/app/api/assist/[id]/messages/route.ts b/src/app/api/assist/[id]/messages/route.tsindex 227b0934..d445a545 100644--- a/src/app/api/assist/[id]/messages/route.ts+++ b/src/app/api/assist/[id]/messages/route.ts@@ -1,8 +1,9 @@import { after } from "next/server";import { addMessage, AssistBusyError, run } from "@/server/assist/agent";import { AssistMessage } from "@/server/assist/schemas";+import { handler } from "@/server/access/route";-export async function POST(request: Request, ctx: RouteContext<"/api/assist/[id]/messages">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/assist/[id]/messages">) => {const { id } = await ctx.params;const parsed = AssistMessage.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Write a message" }, { status: 400 });@@ -14,4 +15,4 @@ export async function POST(request: Request, ctx: RouteContext<"/api/assist/[id]} catch (e) {return Response.json({ error: (e as Error).message }, { status: e instanceof AssistBusyError ? 409 : 404 });}-}+});diff --git a/src/app/api/assist/[id]/route.ts b/src/app/api/assist/[id]/route.tsindex 72490fca..e306caba 100644--- a/src/app/api/assist/[id]/route.ts+++ b/src/app/api/assist/[id]/route.ts@@ -2,6 +2,7 @@ import { connection } from "next/server";import { z } from "zod";import { AssistBusyError, deleteThread, getThread, updateThread } from "@/server/assist/agent";import { ModeChoice } from "@/server/assist/schemas";+import { handler } from "@/server/access/route";const Patch = z.object({autoApprove: z.boolean().optional(),@@ -10,14 +11,14 @@ const Patch = z.object({mode: ModeChoice.optional(),});-export async function GET(_req: Request, ctx: RouteContext<"/api/assist/[id]">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/[id]">) => {await connection();const view = getThread((await ctx.params).id);return view ? Response.json(view) : Response.json({ error: "Not found" }, { status: 404 });-}+});/** Ask-first, rename, move into or out of a project, or switch the mode (Free / Smart / Manual). */-export async function PATCH(request: Request, ctx: RouteContext<"/api/assist/[id]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/assist/[id]">) => {const parsed = Patch.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Invalid change" }, { status: 400 });try {@@ -26,9 +27,9 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/assist/[id} catch (e) {return Response.json({ error: (e as Error).message }, { status: e instanceof AssistBusyError ? 409 : 400 });}-}+});-export async function DELETE(_req: Request, ctx: RouteContext<"/api/assist/[id]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/[id]">) => {deleteThread((await ctx.params).id);return new Response(null, { status: 204 });-}+});diff --git a/src/app/api/assist/connectors/[connectorId]/route.ts b/src/app/api/assist/connectors/[connectorId]/route.tsindex b6677c2d..7189d784 100644--- a/src/app/api/assist/connectors/[connectorId]/route.ts+++ b/src/app/api/assist/connectors/[connectorId]/route.ts@@ -1,8 +1,9 @@import { ConnectorError, deleteConnector, updateConnector } from "@/server/assist/connectors";import { ConnectorBody } from "@/server/assist/schemas";+import { handler } from "@/server/access/route";/** Rename, change the URL, replace the token ("" removes it; leave it out to keep it), switch on or off. */-export async function PATCH(request: Request, ctx: RouteContext<"/api/assist/connectors/[connectorId]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/assist/connectors/[connectorId]">) => {const parsed = ConnectorBody.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Invalid change" }, { status: 400 });try {@@ -11,8 +12,8 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/assist/con} catch (e) {return Response.json({ error: (e as Error).message }, { status: e instanceof ConnectorError ? e.status : 500 });}-}+});-export async function DELETE(_req: Request, ctx: RouteContext<"/api/assist/connectors/[connectorId]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/connectors/[connectorId]">) => {return deleteConnector((await ctx.params).connectorId) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });-}+});diff --git a/src/app/api/assist/connectors/route.ts b/src/app/api/assist/connectors/route.tsindex 8295fc7f..af3715b5 100644--- a/src/app/api/assist/connectors/route.ts+++ b/src/app/api/assist/connectors/route.ts@@ -1,14 +1,15 @@import { connection } from "next/server";import { ConnectorError, createConnector, listConnectors } from "@/server/assist/connectors";import { ConnectorBody } from "@/server/assist/schemas";+import { handler } from "@/server/access/route";/** Custom MCP connectors, tokens masked. */-export async function GET() {+export const GET = handler({ access: "signed-in" }, async () => {await connection();return Response.json({ items: listConnectors() });-}+});-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = ConnectorBody.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Check the connector's name, URL and token" }, { status: 400 });try {@@ -16,4 +17,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: e instanceof ConnectorError ? e.status : 500 });}-}+});diff --git a/src/app/api/assist/memory/[memoryId]/route.ts b/src/app/api/assist/memory/[memoryId]/route.tsindex 502a138e..73426a7d 100644--- a/src/app/api/assist/memory/[memoryId]/route.ts+++ b/src/app/api/assist/memory/[memoryId]/route.ts@@ -1,10 +1,11 @@import { z } from "zod";import { deleteMemory, MemoryError, updateMemory } from "@/server/assist/memory";import { MemoryCategorySchema } from "@/server/assist/schemas";+import { handler } from "@/server/access/route";const Patch = z.object({ text: z.string().trim().min(1).max(500).optional(), category: MemoryCategorySchema.optional() });-export async function PATCH(request: Request, ctx: RouteContext<"/api/assist/memory/[memoryId]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/assist/memory/[memoryId]">) => {const parsed = Patch.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Invalid change" }, { status: 400 });try {@@ -12,8 +13,8 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/assist/mem} catch (e) {return Response.json({ error: (e as Error).message }, { status: e instanceof MemoryError ? e.status : 500 });}-}+});-export async function DELETE(_req: Request, ctx: RouteContext<"/api/assist/memory/[memoryId]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/memory/[memoryId]">) => {return deleteMemory((await ctx.params).memoryId) ? new Response(null, { status: 204 }) : Response.json({ error: "That memory doesn't exist anymore" }, { status: 404 });-}+});diff --git a/src/app/api/assist/memory/import/route.ts b/src/app/api/assist/memory/import/route.tsindex 078e209a..e019a601 100644--- a/src/app/api/assist/memory/import/route.ts+++ b/src/app/api/assist/memory/import/route.ts@@ -2,6 +2,7 @@ import { z } from "zod";import { parseMemoryImport } from "@/lib/assist";import { importMemories, MemoryError } from "@/server/assist/memory";import { MemoryCategorySchema } from "@/server/assist/schemas";+import { handler } from "@/server/access/route";const Body = z.object({/** Pasted text (parsed here) … */@@ -13,7 +14,7 @@ const Body = z.object({});/** Import memories pasted from another assistant (Claude, ChatGPT, Codex…). */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success || (!parsed.data.text && !parsed.data.items)) return Response.json({ error: "Paste the memories to import" }, { status: 400 });const items = parsed.data.items ?? parseMemoryImport(parsed.data.text ?? "");@@ -23,4 +24,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: e instanceof MemoryError ? e.status : 500 });}-}+});diff --git a/src/app/api/assist/memory/route.ts b/src/app/api/assist/memory/route.tsindex 3055b204..78544f4a 100644--- a/src/app/api/assist/memory/route.ts+++ b/src/app/api/assist/memory/route.ts@@ -2,6 +2,7 @@ import { connection } from "next/server";import { z } from "zod";import { addMemory, listMemories, MemoryError } from "@/server/assist/memory";import { MemoryCategorySchema } from "@/server/assist/schemas";+import { handler } from "@/server/access/route";const Add = z.object({text: z.string().trim().min(1).max(500),@@ -11,17 +12,17 @@ const Add = z.object({});/** Memories: `?scope=personal|project|all` and `?project=<id>`. */-export async function GET(request: Request) {+export const GET = handler({ access: "signed-in" }, async (request: Request) => {await connection();const sp = new URL(request.url).searchParams;const scope = sp.get("scope");return Response.json({items: listMemories({ scope: scope === "personal" || scope === "project" ? scope : "all", projectId: sp.get("project") }),});-}+});/** "Remember that: …" */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = Add.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Write what to remember and pick a category" }, { status: 400 });try {@@ -29,4 +30,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: e instanceof MemoryError ? e.status : 500 });}-}+});diff --git a/src/app/api/assist/projects/[projectId]/assets/route.ts b/src/app/api/assist/projects/[projectId]/assets/route.tsindex 35efacf7..69e495c4 100644--- a/src/app/api/assist/projects/[projectId]/assets/route.ts+++ b/src/app/api/assist/projects/[projectId]/assets/route.ts@@ -1,11 +1,12 @@import { connection } from "next/server";import { projectAssets } from "@/server/assist/agent";import { getProject } from "@/server/assist/projects";+import { handler } from "@/server/access/route";/** The project's assets: what its chats made (finished generations, newest first). */-export async function GET(_req: Request, ctx: RouteContext<"/api/assist/projects/[projectId]/assets">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/projects/[projectId]/assets">) => {await connection();const { projectId } = await ctx.params;if (!getProject(projectId)) return Response.json({ error: "Not found" }, { status: 404 });return Response.json({ items: projectAssets(projectId) });-}+});diff --git a/src/app/api/assist/projects/[projectId]/route.ts b/src/app/api/assist/projects/[projectId]/route.tsindex 85f73681..b4c63974 100644--- a/src/app/api/assist/projects/[projectId]/route.ts+++ b/src/app/api/assist/projects/[projectId]/route.ts@@ -1,14 +1,15 @@import { connection } from "next/server";import { deleteProject, getProject, ProjectError, updateProject } from "@/server/assist/projects";import { ProjectBody } from "@/server/assist/schemas";+import { handler } from "@/server/access/route";-export async function GET(_req: Request, ctx: RouteContext<"/api/assist/projects/[projectId]">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/projects/[projectId]">) => {await connection();const p = getProject((await ctx.params).projectId);return p ? Response.json(p) : Response.json({ error: "Not found" }, { status: 404 });-}+});-export async function PATCH(request: Request, ctx: RouteContext<"/api/assist/projects/[projectId]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/assist/projects/[projectId]">) => {const parsed = ProjectBody.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Invalid change" }, { status: 400 });try {@@ -16,9 +17,9 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/assist/pro} catch (e) {return Response.json({ error: (e as Error).message }, { status: e instanceof ProjectError ? e.status : 500 });}-}+});/** Delete the project, its sources and project memories; its chats move to your chats. */-export async function DELETE(_req: Request, ctx: RouteContext<"/api/assist/projects/[projectId]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/projects/[projectId]">) => {return deleteProject((await ctx.params).projectId) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });-}+});diff --git a/src/app/api/assist/projects/[projectId]/sources/[sourceId]/refresh/route.ts b/src/app/api/assist/projects/[projectId]/sources/[sourceId]/refresh/route.tsindex defccef0..f9331bfa 100644--- a/src/app/api/assist/projects/[projectId]/sources/[sourceId]/refresh/route.ts+++ b/src/app/api/assist/projects/[projectId]/sources/[sourceId]/refresh/route.ts@@ -1,11 +1,12 @@import { ProjectError, refreshSource } from "@/server/assist/projects";+import { handler } from "@/server/access/route";/** Fetch a link source again. */-export async function POST(_req: Request, ctx: RouteContext<"/api/assist/projects/[projectId]/sources/[sourceId]/refresh">) {+export const POST = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/projects/[projectId]/sources/[sourceId]/refresh">) => {const { projectId, sourceId } = await ctx.params;try {return Response.json(await refreshSource(projectId, sourceId));} catch (e) {return Response.json({ error: (e as Error).message }, { status: e instanceof ProjectError ? e.status : 500 });}-}+});diff --git a/src/app/api/assist/projects/[projectId]/sources/[sourceId]/route.ts b/src/app/api/assist/projects/[projectId]/sources/[sourceId]/route.tsindex 52e7aca2..b2c5fc81 100644--- a/src/app/api/assist/projects/[projectId]/sources/[sourceId]/route.ts+++ b/src/app/api/assist/projects/[projectId]/sources/[sourceId]/route.ts@@ -1,6 +1,7 @@import { deleteSource } from "@/server/assist/projects";+import { handler } from "@/server/access/route";-export async function DELETE(_req: Request, ctx: RouteContext<"/api/assist/projects/[projectId]/sources/[sourceId]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/projects/[projectId]/sources/[sourceId]">) => {const { projectId, sourceId } = await ctx.params;return deleteSource(projectId, sourceId) ? new Response(null, { status: 204 }) : Response.json({ error: "That source isn't in this project" }, { status: 404 });-}+});diff --git a/src/app/api/assist/projects/[projectId]/sources/route.ts b/src/app/api/assist/projects/[projectId]/sources/route.tsindex 1b3580b9..f3d4a2a7 100644--- a/src/app/api/assist/projects/[projectId]/sources/route.ts+++ b/src/app/api/assist/projects/[projectId]/sources/route.ts@@ -1,6 +1,7 @@import { z } from "zod";import { addSource, ProjectError } from "@/server/assist/projects";import { contentTypeFor, deleteAsset, saveFile } from "@/server/storage";+import { handler } from "@/server/access/route";const MAX_BYTES = 25 * 1024 * 1024;/** Documents Assist can read (text, Markdown, PDF), plus media it can pass on as inputs. */@@ -18,7 +19,7 @@ const Json = z.discriminatedUnion("kind", [* Add a source: JSON (a link, an uploaded file URL, an element, a note) or multipart "file"* (documents and media are stored like uploads). Links are fetched through the guarded fetcher.*/-export async function POST(request: Request, ctx: RouteContext<"/api/assist/projects/[projectId]/sources">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/assist/projects/[projectId]/sources">) => {const { projectId } = await ctx.params;try {if ((request.headers.get("content-type") ?? "").startsWith("multipart/form-data")) {@@ -47,4 +48,4 @@ export async function POST(request: Request, ctx: RouteContext<"/api/assist/proj} catch (e) {return Response.json({ error: (e as Error).message }, { status: e instanceof ProjectError ? e.status : 500 });}-}+});diff --git a/src/app/api/assist/projects/route.ts b/src/app/api/assist/projects/route.tsindex 5c863ad3..b1086b02 100644--- a/src/app/api/assist/projects/route.ts+++ b/src/app/api/assist/projects/route.ts@@ -1,13 +1,14 @@import { connection } from "next/server";import { createProject, listProjects, ProjectError } from "@/server/assist/projects";import { ProjectBody } from "@/server/assist/schemas";+import { handler } from "@/server/access/route";-export async function GET() {+export const GET = handler({ access: "signed-in" }, async () => {await connection();return Response.json({ items: listProjects() });-}+});-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = ProjectBody.safeParse(await request.json().catch(() => null));if (!parsed.success || !parsed.data.name) return Response.json({ error: "Give the project a name" }, { status: 400 });try {@@ -15,4 +16,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: e instanceof ProjectError ? e.status : 500 });}-}+});diff --git a/src/app/api/assist/route.ts b/src/app/api/assist/route.tsindex d06ca60b..ed9494fb 100644--- a/src/app/api/assist/route.ts+++ b/src/app/api/assist/route.ts@@ -2,6 +2,7 @@ import { after, connection } from "next/server";import { z } from "zod";import { addMessage, availability, createThread, listThreads, resolveAgent, resolveMode, run } from "@/server/assist/agent";import { AssistMessage, ModeChoice } from "@/server/assist/schemas";+import { handler } from "@/server/access/route";const Create = AssistMessage.extend({engine: z.enum(["cloud", "open"]),@@ -11,17 +12,17 @@ const Create = AssistMessage.extend({});/** Chats (all, `?project=<id>`, or `?project=none` for chats outside projects; `?q=` searches), with what can run. */-export async function GET(request: Request) {+export const GET = handler({ access: "signed-in" }, async (request: Request) => {await connection();const sp = new URL(request.url).searchParams;const project = sp.get("project");const threads = listThreads({ project: project === "none" ? null : (project ?? undefined), q: sp.get("q") ?? undefined });const [agent, can] = await Promise.all([resolveAgent(), availability()]);return Response.json({ threads, agent, availability: can });-}+});/** Start a chat with its first message; the agent replies in the background (poll the thread). */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = Create.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Write a message" }, { status: 400 });const { text, attachments, engine, autoApprove, projectId, mode } = parsed.data;@@ -37,4 +38,4 @@ export async function POST(request: Request) {const reply = run(thread.id);after(() => reply);return Response.json({ ...updated, ...(r.note && { note: r.note }) }, { status: 201 });-}+});diff --git a/src/app/api/assist/schedules/[scheduleId]/route.ts b/src/app/api/assist/schedules/[scheduleId]/route.tsindex b5857eeb..fbcabb7a 100644--- a/src/app/api/assist/schedules/[scheduleId]/route.ts+++ b/src/app/api/assist/schedules/[scheduleId]/route.ts@@ -1,17 +1,18 @@import { connection } from "next/server";import { deleteSchedule, getSchedule, ScheduleError, updateSchedule } from "@/server/assist/schedules";import { ScheduleBody } from "@/server/assist/schemas";+import { handler } from "@/server/access/route";const Patch = ScheduleBody.partial();-export async function GET(_req: Request, ctx: RouteContext<"/api/assist/schedules/[scheduleId]">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/schedules/[scheduleId]">) => {await connection();const s = getSchedule((await ctx.params).scheduleId);return s ? Response.json(s) : Response.json({ error: "Not found" }, { status: 404 });-}+});/** Edit, pause (`{paused: true}`) or resume a task. */-export async function PATCH(request: Request, ctx: RouteContext<"/api/assist/schedules/[scheduleId]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/assist/schedules/[scheduleId]">) => {const parsed = Patch.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: parsed.error.issues[0]?.message ?? "Invalid change" }, { status: 400 });try {@@ -20,9 +21,9 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/assist/sch} catch (e) {return Response.json({ error: (e as Error).message }, { status: e instanceof ScheduleError ? e.status : 500 });}-}+});/** Delete the task; the chats its runs made stay. */-export async function DELETE(_req: Request, ctx: RouteContext<"/api/assist/schedules/[scheduleId]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/schedules/[scheduleId]">) => {return deleteSchedule((await ctx.params).scheduleId) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });-}+});diff --git a/src/app/api/assist/schedules/[scheduleId]/run/route.ts b/src/app/api/assist/schedules/[scheduleId]/run/route.tsindex 208ac82e..31dd18ce 100644--- a/src/app/api/assist/schedules/[scheduleId]/run/route.ts+++ b/src/app/api/assist/schedules/[scheduleId]/run/route.ts@@ -1,12 +1,13 @@import { after } from "next/server";import { ScheduleError, startSchedule } from "@/server/assist/schedules";+import { handler } from "@/server/access/route";/*** Run a task now, off schedule: a new chat starts and the agent works in the background (202). No new* chat: 409 while the last run is still going; 422 with the reason when the run couldn't start (its* project is gone, so the task paused, or the chat failed to start).*/-export async function POST(_req: Request, ctx: RouteContext<"/api/assist/schedules/[scheduleId]/run">) {+export const POST = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/schedules/[scheduleId]/run">) => {try {const started = await startSchedule((await ctx.params).scheduleId, { manual: true });if (started.threadId === null) return Response.json({ threadId: null, reason: started.reason, error: started.message }, { status: started.reason === "busy" ? 409 : 422 });@@ -15,4 +16,4 @@ export async function POST(_req: Request, ctx: RouteContext<"/api/assist/schedul} catch (e) {return Response.json({ error: (e as Error).message }, { status: e instanceof ScheduleError ? e.status : 500 });}-}+});diff --git a/src/app/api/assist/schedules/route.ts b/src/app/api/assist/schedules/route.tsindex 26c0fc07..b3bb5ac9 100644--- a/src/app/api/assist/schedules/route.ts+++ b/src/app/api/assist/schedules/route.ts@@ -1,17 +1,18 @@import { connection } from "next/server";import { createSchedule, listSchedules, ScheduleError } from "@/server/assist/schedules";import { ScheduleBody } from "@/server/assist/schemas";+import { handler } from "@/server/access/route";const issue = (e: { issues: { message: string }[] }) => e.issues[0]?.message ?? "Check the schedule";/** Scheduled tasks (all, `?project=<id>`, or `?project=none` for those outside projects). */-export async function GET(request: Request) {+export const GET = handler({ access: "signed-in" }, async (request: Request) => {await connection();const project = new URL(request.url).searchParams.get("project");return Response.json({ items: listSchedules({ project: project === "none" ? null : (project ?? undefined) }) });-}+});-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = ScheduleBody.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: issue(parsed.error) }, { status: 400 });try {@@ -19,4 +20,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: e instanceof ScheduleError ? e.status : 500 });}-}+});diff --git a/src/app/api/assist/skills/[name]/download/route.ts b/src/app/api/assist/skills/[name]/download/route.tsindex 0a803b35..fda36832 100644--- a/src/app/api/assist/skills/[name]/download/route.ts+++ b/src/app/api/assist/skills/[name]/download/route.ts@@ -1,11 +1,12 @@import { connection } from "next/server";import { skillArchive, skillMarkdown } from "@/server/skills";+import { handler } from "@/server/access/route";/*** The skill to keep or share: SKILL.md (upload it on another Fuobe, or use it with Claude), or with `?format=zip` the* skill with every bundled file, as Upload reads it. A recipe's examples and source stay out unless `&examples=1`.*/-export async function GET(req: Request, ctx: RouteContext<"/api/assist/skills/[name]/download">) {+export const GET = handler({ access: "signed-in" }, async (req: Request, ctx: RouteContext<"/api/assist/skills/[name]/download">) => {await connection();const { name } = await ctx.params;const sp = new URL(req.url).searchParams;@@ -29,4 +30,4 @@ export async function GET(req: Request, ctx: RouteContext<"/api/assist/skills/[n"X-Content-Type-Options": "nosniff",},});-}+});diff --git a/src/app/api/assist/skills/[name]/duplicate/route.ts b/src/app/api/assist/skills/[name]/duplicate/route.tsindex 8fe5116b..f3bbad3a 100644--- a/src/app/api/assist/skills/[name]/duplicate/route.ts+++ b/src/app/api/assist/skills/[name]/duplicate/route.ts@@ -1,10 +1,11 @@import { duplicateSkill, SkillError } from "@/server/skills";+import { handler } from "@/server/access/route";/** Copy a skill into My skills (the way to change a built-in). */-export async function POST(_req: Request, ctx: RouteContext<"/api/assist/skills/[name]/duplicate">) {+export const POST = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/skills/[name]/duplicate">) => {try {return Response.json(duplicateSkill((await ctx.params).name), { status: 201 });} catch (e) {return Response.json({ error: (e as Error).message }, { status: e instanceof SkillError ? e.status : 500 });}-}+});diff --git a/src/app/api/assist/skills/[name]/estimate/route.ts b/src/app/api/assist/skills/[name]/estimate/route.tsindex b9a851f9..017c38c4 100644--- a/src/app/api/assist/skills/[name]/estimate/route.ts+++ b/src/app/api/assist/skills/[name]/estimate/route.ts@@ -1,8 +1,9 @@import { badBody, recipeFailure, RunBody } from "@/server/recipe-routes";import { estimateRecipe } from "@/server/recipes";+import { handler } from "@/server/access/route";/** Price a run of a skill's recipe, or many (`rows` or `csv`, priced together with a total). Starts nothing. */-export async function POST(request: Request, ctx: RouteContext<"/api/assist/skills/[name]/estimate">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/assist/skills/[name]/estimate">) => {const parsed = RunBody.safeParse(await request.json().catch(() => ({})));if (!parsed.success) return badBody(parsed.error.issues);try {@@ -11,4 +12,4 @@ export async function POST(request: Request, ctx: RouteContext<"/api/assist/skil} catch (e) {return recipeFailure(e);}-}+});diff --git a/src/app/api/assist/skills/[name]/recipe/route.ts b/src/app/api/assist/skills/[name]/recipe/route.tsindex 1dff251a..048ae00d 100644--- a/src/app/api/assist/skills/[name]/recipe/route.ts+++ b/src/app/api/assist/skills/[name]/recipe/route.ts@@ -1,19 +1,20 @@import { connection } from "next/server";import { recipeFailure } from "@/server/recipe-routes";import { recipeView, saveRecipe } from "@/server/recipes";+import { handler } from "@/server/access/route";/** A skill's recipe with where it runs and what was checked (engines, ready, needs a re-check). */-export async function GET(_req: Request, ctx: RouteContext<"/api/assist/skills/[name]/recipe">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/skills/[name]/recipe">) => {await connection();try {return Response.json(recipeView((await ctx.params).name));} catch (e) {return recipeFailure(e);}-}+});/** Save a user skill's recipe.json (it starts unchecked); every problem is named. */-export async function PUT(request: Request, ctx: RouteContext<"/api/assist/skills/[name]/recipe">) {+export const PUT = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/assist/skills/[name]/recipe">) => {const body = await request.json().catch(() => null);if (!body || typeof body !== "object") return Response.json({ error: "Send the recipe as JSON" }, { status: 400 });try {@@ -23,4 +24,4 @@ export async function PUT(request: Request, ctx: RouteContext<"/api/assist/skill} catch (e) {return recipeFailure(e);}-}+});diff --git a/src/app/api/assist/skills/[name]/route.ts b/src/app/api/assist/skills/[name]/route.tsindex 252200dc..a6ebffad 100644--- a/src/app/api/assist/skills/[name]/route.ts+++ b/src/app/api/assist/skills/[name]/route.ts@@ -1,6 +1,7 @@import { connection } from "next/server";import { z } from "zod";import { deleteSkill, getSkill, setSkillEnabled, SkillError, updateSkill } from "@/server/skills";+import { handler } from "@/server/access/route";const Patch = z.object({enabled: z.boolean().optional(),@@ -14,14 +15,14 @@ const Patch = z.object({const fail = (e: unknown) => Response.json({ error: (e as Error).message }, { status: e instanceof SkillError ? e.status : 500 });-export async function GET(_req: Request, ctx: RouteContext<"/api/assist/skills/[name]">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/skills/[name]">) => {await connection();const s = getSkill((await ctx.params).name);return s ? Response.json(s) : Response.json({ error: "No such skill" }, { status: 404 });-}+});/** Switch a skill on or off, or edit one of your own. */-export async function PATCH(request: Request, ctx: RouteContext<"/api/assist/skills/[name]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/assist/skills/[name]">) => {const parsed = Patch.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Invalid change" }, { status: 400 });const { name } = await ctx.params;@@ -34,13 +35,13 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/assist/ski} catch (e) {return fail(e);}-}+});-export async function DELETE(_req: Request, ctx: RouteContext<"/api/assist/skills/[name]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/skills/[name]">) => {try {deleteSkill((await ctx.params).name);return new Response(null, { status: 204 });} catch (e) {return fail(e);}-}+});diff --git a/src/app/api/assist/skills/[name]/run/route.ts b/src/app/api/assist/skills/[name]/run/route.tsindex 23447463..5ac46bb1 100644--- a/src/app/api/assist/skills/[name]/run/route.ts+++ b/src/app/api/assist/skills/[name]/run/route.ts@@ -1,8 +1,9 @@import { badBody, recipeFailure, RunBody } from "@/server/recipe-routes";import { runRecipe } from "@/server/recipes";+import { handler } from "@/server/access/route";/** Run a skill's recipe with new inputs, once or once per row, with no LLM. Every row is checked before any starts. */-export async function POST(request: Request, ctx: RouteContext<"/api/assist/skills/[name]/run">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/assist/skills/[name]/run">) => {const parsed = RunBody.safeParse(await request.json().catch(() => ({})));if (!parsed.success) return badBody(parsed.error.issues);try {@@ -11,4 +12,4 @@ export async function POST(request: Request, ctx: RouteContext<"/api/assist/skil} catch (e) {return recipeFailure(e);}-}+});diff --git a/src/app/api/assist/skills/[name]/verify/route.ts b/src/app/api/assist/skills/[name]/verify/route.tsindex cecb4fa8..f334ba77 100644--- a/src/app/api/assist/skills/[name]/verify/route.ts+++ b/src/app/api/assist/skills/[name]/verify/route.ts@@ -1,6 +1,7 @@import { z } from "zod";import { badBody, recipeFailure } from "@/server/recipe-routes";import { verifyRecipe } from "@/server/recipes";+import { handler } from "@/server/access/route";const Body = z.object({level: z.enum(["plan", "demo", "real"]).default("demo"),@@ -10,7 +11,7 @@ const Body = z.object({});/** Check a skill's recipe (plan, a free dry run, or a real test) and record what passed in its `verified`. */-export async function POST(request: Request, ctx: RouteContext<"/api/assist/skills/[name]/verify">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/assist/skills/[name]/verify">) => {const parsed = Body.safeParse(await request.json().catch(() => ({})));if (!parsed.success) return badBody(parsed.error.issues);try {@@ -19,4 +20,4 @@ export async function POST(request: Request, ctx: RouteContext<"/api/assist/skil} catch (e) {return recipeFailure(e);}-}+});diff --git a/src/app/api/assist/skills/draft/check/route.ts b/src/app/api/assist/skills/draft/check/route.tsindex 1389f737..c14d94de 100644--- a/src/app/api/assist/skills/draft/check/route.ts+++ b/src/app/api/assist/skills/draft/check/route.ts@@ -1,6 +1,7 @@import { z } from "zod";import { badBody, recipeFailure } from "@/server/recipe-routes";import { checkDraft } from "@/server/recipes";+import { handler } from "@/server/access/route";const Body = z.object({recipe: z.unknown(),@@ -10,7 +11,7 @@ const Body = z.object({});/** Check a drafted skill's recipe before it is saved: free, with or without keys. What passed is kept for its save. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = Body.safeParse(await request.json().catch(() => ({})));if (!parsed.success) return badBody(parsed.error.issues);try {@@ -18,4 +19,4 @@ export async function POST(request: Request) {} catch (e) {return recipeFailure(e);}-}+});diff --git a/src/app/api/assist/skills/draft/name/route.ts b/src/app/api/assist/skills/draft/name/route.tsindex 3881b2ab..c4ecb8d2 100644--- a/src/app/api/assist/skills/draft/name/route.ts+++ b/src/app/api/assist/skills/draft/name/route.ts@@ -1,6 +1,7 @@import { z } from "zod";import { badBody, recipeFailure } from "@/server/recipe-routes";import { draftFromGenerations, nameDraft } from "@/server/recipe-builder";+import { handler } from "@/server/access/route";const Body = z.object({ generations: z.array(z.string().min(1).max(40)).min(1).max(200) });@@ -8,7 +9,7 @@ const Body = z.object({ generations: z.array(z.string().min(1).max(40)).min(1).m* The optional naming pass for a draft (Claude or Ollama, whichever this install allows): names for its inputs, slots in* its prompts, a title, a description and a SKILL.md body. `naming` is null when there's no LLM or its answer was malformed.*/-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = Body.safeParse(await request.json().catch(() => ({})));if (!parsed.success) return badBody(parsed.error.issues);try {@@ -17,4 +18,4 @@ export async function POST(request: Request) {} catch (e) {return recipeFailure(e);}-}+});diff --git a/src/app/api/assist/skills/draft/route.ts b/src/app/api/assist/skills/draft/route.tsindex 85db57d6..60089f34 100644--- a/src/app/api/assist/skills/draft/route.ts+++ b/src/app/api/assist/skills/draft/route.ts@@ -1,6 +1,7 @@import { z } from "zod";import { badBody, recipeFailure } from "@/server/recipe-routes";import { draftFromGenerations } from "@/server/recipe-builder";+import { handler } from "@/server/access/route";const Body = z.object({ generations: z.array(z.string().min(1).max(40)).min(1).max(200) });@@ -8,7 +9,7 @@ const Body = z.object({ generations: z.array(z.string().min(1).max(40)).min(1).m* A skill drafted from results in the Library (W2): the steps behind them rebuilt from their requests, every input* Fixed, with the inputs that could vary and proposed checks; `refusals` say which picks couldn't be used and why.*/-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = Body.safeParse(await request.json().catch(() => ({})));if (!parsed.success) return badBody(parsed.error.issues);try {@@ -16,4 +17,4 @@ export async function POST(request: Request) {} catch (e) {return recipeFailure(e);}-}+});diff --git a/src/app/api/assist/skills/draft/save/route.ts b/src/app/api/assist/skills/draft/save/route.tsindex d2835d89..122bc154 100644--- a/src/app/api/assist/skills/draft/save/route.ts+++ b/src/app/api/assist/skills/draft/save/route.ts@@ -2,11 +2,12 @@ import { z } from "zod";import { SkillBody } from "@/server/assist/schemas";import { badBody, recipeFailure } from "@/server/recipe-routes";import { saveDraft } from "@/server/recipes";+import { handler } from "@/server/access/route";const Body = SkillBody.extend({ recipe: z.unknown() });/** Save a drafted skill: its SKILL.md and recipe.json, once its plan passes on an engine (checked again here, free). */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = Body.safeParse(await request.json().catch(() => ({})));if (!parsed.success) return badBody(parsed.error.issues);try {@@ -14,4 +15,4 @@ export async function POST(request: Request) {} catch (e) {return recipeFailure(e);}-}+});diff --git a/src/app/api/assist/skills/route.ts b/src/app/api/assist/skills/route.tsindex 48e34368..2f12b3cd 100644--- a/src/app/api/assist/skills/route.ts+++ b/src/app/api/assist/skills/route.ts@@ -1,15 +1,16 @@import { connection } from "next/server";import { SkillBody } from "@/server/assist/schemas";import { createSkill, listSkills, SkillError } from "@/server/skills";+import { handler } from "@/server/access/route";/** Every skill: built-in (from skills/) and the user's own. */-export async function GET() {+export const GET = handler({ access: "signed-in" }, async () => {await connection();return Response.json({ items: listSkills() });-}+});/** Create a skill from the form (name, title, description, when to use, instructions). */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = SkillBody.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Give the skill a name, a description and instructions" }, { status: 400 });try {@@ -17,4 +18,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: e instanceof SkillError ? e.status : 500 });}-}+});diff --git a/src/app/api/assist/skills/upload/route.ts b/src/app/api/assist/skills/upload/route.tsindex 796ce3e4..0c5b82d8 100644--- a/src/app/api/assist/skills/upload/route.ts+++ b/src/app/api/assist/skills/upload/route.ts@@ -1,9 +1,10 @@import { importSkill, SkillError } from "@/server/skills";+import { handler } from "@/server/access/route";const MAX_BYTES = 5 * 1024 * 1024;/** Add a skill from a .zip / .skill archive or a SKILL.md (multipart "file"; `?replace=1` overwrites your skill of the same name). */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const form = await request.formData().catch(() => null);const file = form?.get("file");if (!(file instanceof File)) return Response.json({ error: "Choose a .zip, .skill or SKILL.md file" }, { status: 400 });@@ -15,4 +16,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: e instanceof SkillError ? e.status : 500 });}-}+});diff --git a/src/app/api/audio-tools/export/route.ts b/src/app/api/audio-tools/export/route.tsindex 6ea5a9b3..dad4544d 100644--- a/src/app/api/audio-tools/export/route.ts+++ b/src/app/api/audio-tools/export/route.ts@@ -1,10 +1,11 @@import { MixExportError, PART_MAX, receiveMixPart } from "@/server/mix-export";+import { handler } from "@/server/access/route";/*** Split soundtrack's Export mix, in parts: POST the WAV's bytes as the body, `?offset=` where they start, `&id=` from* the first part's answer, `&last=1&name=` on the last part, which answers with the Library asset (201).*/-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const q = new URL(request.url).searchParams;const offset = Number(q.get("offset") ?? "0");if (!Number.isSafeInteger(offset) || offset < 0) return Response.json({ error: "Say where the part starts (offset)" }, { status: 400 });@@ -18,4 +19,4 @@ export async function POST(request: Request) {console.error("[audio-tools/export]", e);return Response.json({ error: (e as Error).message || "Couldn't save the mix" }, { status: 500 });}-}+});diff --git a/src/app/api/audio-tools/route.ts b/src/app/api/audio-tools/route.tsindex 37eb1a09..5d0ccca9 100644--- a/src/app/api/audio-tools/route.ts+++ b/src/app/api/audio-tools/route.ts@@ -1,4 +1,5 @@import { AudioToolBody, AudioToolError, previewAudioTool, runAudioTool } from "@/server/audio-tools";+import { handler } from "@/server/access/route";/** What a field that doesn't check out means, in words the page shows. */const MESSAGES: Record<string, string> = {@@ -10,7 +11,7 @@ const MESSAGES: Record<string, string> = {};/** Audio → Loop / extend, Join and Split soundtrack (and a split's mix put back on its video): start a run; `?preview=1` only plans and prices it. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const raw: unknown = await request.json().catch(() => null);const parsed = AudioToolBody.safeParse(raw);if (!parsed.success) {@@ -27,4 +28,4 @@ export async function POST(request: Request) {console.error("[audio-tools]", e);return Response.json({ error: (e as Error).message || "Something went wrong" }, { status: 500 });}-}+});diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.tsindex 03bc2ace..b07f2609 100644--- a/src/app/api/auth/login/route.ts+++ b/src/app/api/auth/login/route.ts@@ -5,6 +5,7 @@ import { signInOwner, type SignInResult } from "@/server/identity/owner";import { PASSWORD_SIGN_IN_MAX } from "@/server/identity/password";import { refusal } from "@/server/identity/refusals";import { signInRequired } from "@/server/mode";+import { handler } from "@/server/access/route";/*** Personal sign-in (docs/research/accounts-8.md §8): one password field, no email. Signs u_owner in through Better@@ -22,7 +23,7 @@ const guard = (globalThis.__fuobeLoginGuard ??= new LoginGuard());/** The pre-accounts session cookie: no longer accepted, cleared on the next sign-in or sign-out. */const LEGACY_SESSION_COOKIE = "fuobe_session";-export async function POST(request: Request) {+export const POST = handler({ access: "public" }, async (request: Request) => {if (!signInRequired()) return Response.json({ ok: true });const key = LoginGuard.clientKey(request.headers);const wait = guard.blockedFor(key);@@ -51,4 +52,4 @@ export async function POST(request: Request) {for (const c of result.setCookies) headers.append("set-cookie", c);headers.append("set-cookie", `${LEGACY_SESSION_COOKIE}=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax`);return Response.json({ ok: true }, { headers });-}+});diff --git a/src/app/api/auth/logout/route.ts b/src/app/api/auth/logout/route.tsindex e1fda938..3ed5324b 100644--- a/src/app/api/auth/logout/route.ts+++ b/src/app/api/auth/logout/route.ts@@ -1,14 +1,15 @@-import { appendAudit } from "@/server/identity/audit-log";import { signOut } from "@/server/identity/owner";-import { resolvePrincipal } from "@/server/identity/principal";+import { maybeActor } from "@/server/access/actor";+import { audit } from "@/server/access/audit";+import { handler } from "@/server/access/route";/** Sign out: Better Auth deletes the session (so the cookie is dead everywhere) and expires the cookie. */-export async function POST(request: Request) {- const { actor } = await resolvePrincipal(request);+export const POST = handler({ access: "public" }, async (request: Request) => {+ const actor = maybeActor();const cookies = await signOut(request.headers);- if (actor?.via === "session") appendAudit({ action: "auth.sign_out", actorId: actor.userId, via: "session", targetKind: "session", targetId: actor.sessionId ?? null });+ if (actor?.via === "session") audit("auth.sign_out", { kind: "session", id: actor.sessionId ?? null });const headers = new Headers({ "Cache-Control": "no-store" });for (const c of cookies) headers.append("set-cookie", c);headers.append("set-cookie", "fuobe_session=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax");return Response.json({ ok: true }, { headers });-}+});diff --git a/src/app/api/auth/password/route.ts b/src/app/api/auth/password/route.tsindex bb6bd631..67d51efe 100644--- a/src/app/api/auth/password/route.ts+++ b/src/app/api/auth/password/route.ts@@ -2,9 +2,10 @@ import { connection } from "next/server";import { z } from "zod";import { checkOwnerPassword, changeOwnerPassword, ownerPasswordStatus, signInOwner } from "@/server/identity/owner";import { PASSWORD_SIGN_IN_MAX } from "@/server/identity/password";-import { resolvePrincipal } from "@/server/identity/principal";import { listTokens } from "@/server/identity/tokens";import { signInRequired } from "@/server/mode";+import { currentActor } from "@/server/access/actor";+import { handler } from "@/server/access/route";/*** Settings → Security in Personal: whether a password is required, and setting, changing or removing it (removing@@ -14,25 +15,24 @@ import { signInRequired } from "@/server/mode";const Body = z.object({ current: z.string().max(PASSWORD_SIGN_IN_MAX).optional(), password: z.string().max(PASSWORD_SIGN_IN_MAX).nullable() });-async function status(request: Request) {- const { actor } = await resolvePrincipal(request);- return { enabled: signInRequired(), ...ownerPasswordStatus(), tokens: actor ? listTokens(actor.userId) : [] };+function status() {+ return { enabled: signInRequired(), ...ownerPasswordStatus(), tokens: listTokens(currentActor().userId) };}-export async function GET(request: Request) {+export const GET = handler({ access: "signed-in" }, async () => {await connection();- return Response.json(await status(request));-}+ return Response.json(status());+});-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Invalid request" }, { status: 400 });const { current, password } = parsed.data;- const { actor } = await resolvePrincipal(request);+ const actor = currentActor();if (signInRequired()) {- if (actor?.via !== "session" || actor.role !== "owner") return Response.json({ error: "Change the password from a signed-in browser" }, { status: 403 });+ if (actor.via !== "session" || actor.role !== "owner") return Response.json({ error: "Change the password from a signed-in browser" }, { status: 403 });if (!(await checkOwnerPassword(current ?? ""))) return Response.json({ error: "The current password is wrong" }, { status: 403 });- } else if (actor?.via !== "local") {+ } else if (actor.via !== "local") {return Response.json({ error: "Set a password from the computer Fuobe runs on" }, { status: 403 });}try {@@ -47,5 +47,5 @@ export async function POST(request: Request) {if (signedIn.ok) for (const c of signedIn.setCookies) headers.append("set-cookie", c);}headers.append("set-cookie", "fuobe_session=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax");- return Response.json(await status(request), { headers });-}+ return Response.json(status(), { headers });+});diff --git a/src/app/api/auth/tokens/route.ts b/src/app/api/auth/tokens/route.tsindex 8c7e6591..51d36b77 100644--- a/src/app/api/auth/tokens/route.ts+++ b/src/app/api/auth/tokens/route.ts@@ -1,39 +1,35 @@import { connection } from "next/server";import { z } from "zod";-import { resolvePrincipal, type Actor } from "@/server/identity/principal";import { createToken, listTokens, revokeToken } from "@/server/identity/tokens";+import { currentActor } from "@/server/access/actor";+import { gate } from "@/server/access/gates";+import { handler } from "@/server/access/route";/*** API tokens, managed from a signed-in browser (or Just me on this computer): a token can't mint or revoke- * tokens. Each person sees and revokes their own (admins revoking anyone's arrives with the admin console).+ * tokens (access "browser" answers it 403). Each person sees and revokes their own (admins revoking anyone's arrives+ * with the admin console).*/-async function browserActor(request: Request): Promise<Actor | Response> {- const { actor } = await resolvePrincipal(request);- if (actor && (actor.via === "session" || actor.via === "local")) return actor;- return Response.json({ error: "Manage API tokens from a signed-in browser" }, { status: 403 });-}-export async function GET(request: Request) {+export const GET = handler({ access: "browser" }, async () => {await connection();- const actor = await browserActor(request);- if (actor instanceof Response) return actor;+ const actor = currentActor();return Response.json({ tokens: listTokens(actor.userId) });-}+});/** Create a token; the full value is in this response only. */-export async function POST(request: Request) {- const actor = await browserActor(request);- if (actor instanceof Response) return actor;+export const POST = handler({ access: "browser" }, async (request: Request) => {+ const actor = currentActor();+ gate("token.create", actor);const parsed = z.object({ name: z.string().max(60) }).safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Name the token" }, { status: 400 });return Response.json(createToken(actor.userId, parsed.data.name), { status: 201 });-}+});-export async function DELETE(request: Request) {- const actor = await browserActor(request);- if (actor instanceof Response) return actor;+export const DELETE = handler({ access: "browser" }, async (request: Request) => {+ const actor = currentActor();const id = new URL(request.url).searchParams.get("id");if (!id) return Response.json({ error: "Which token?" }, { status: 400 });if (!revokeToken(actor.userId, id)) return Response.json({ error: "No such token" }, { status: 404 });return new Response(null, { status: 204 });-}+});diff --git a/src/app/api/brands/[id]/chat/confirm/route.ts b/src/app/api/brands/[id]/chat/confirm/route.tsindex 24a9ddf2..a29e01ec 100644--- a/src/app/api/brands/[id]/chat/confirm/route.ts+++ b/src/app/api/brands/[id]/chat/confirm/route.ts@@ -2,11 +2,12 @@ import { after } from "next/server";import { z } from "zod";import { confirmProposal } from "@/server/ads";import { failure, readBody } from "@/server/marketing";+import { handler } from "@/server/access/route";const Body = z.object({ messageId: z.string().min(1).max(20), engine: z.enum(["cloud", "open"]) });/** The user said yes to a chat proposal: the ads start rendering. */-export async function POST(request: Request, ctx: RouteContext<"/api/brands/[id]/chat/confirm">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/brands/[id]/chat/confirm">) => {const { id } = await ctx.params;const body = await readBody(request, Body);if (body instanceof Response) return body;@@ -17,4 +18,4 @@ export async function POST(request: Request, ctx: RouteContext<"/api/brands/[id]} catch (e) {return failure(e);}-}+});diff --git a/src/app/api/brands/[id]/chat/route.ts b/src/app/api/brands/[id]/chat/route.tsindex 8b55583b..a14965b2 100644--- a/src/app/api/brands/[id]/chat/route.ts+++ b/src/app/api/brands/[id]/chat/route.ts@@ -3,18 +3,19 @@ import { z } from "zod";import { chat, clearChat, getChat } from "@/server/ads";import { getBrand } from "@/server/brand";import { failure, readBody } from "@/server/marketing";+import { handler } from "@/server/access/route";const Body = z.object({ text: z.string().trim().min(1).max(2000) });/** The brand chat ("what ads should we make for {brand}?"). */-export async function GET(_req: Request, ctx: RouteContext<"/api/brands/[id]/chat">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/brands/[id]/chat">) => {await connection();const { id } = await ctx.params;return getBrand(id) ? Response.json({ messages: getChat(id) }) : Response.json({ error: "Not found" }, { status: 404 });-}+});/** Send a message; the reply may carry a proposal (products × count + direction) to confirm. */-export async function POST(request: Request, ctx: RouteContext<"/api/brands/[id]/chat">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/brands/[id]/chat">) => {const { id } = await ctx.params;const body = await readBody(request, Body, "Write a message");if (body instanceof Response) return body;@@ -23,10 +24,10 @@ export async function POST(request: Request, ctx: RouteContext<"/api/brands/[id]} catch (e) {return failure(e);}-}+});-export async function DELETE(_req: Request, ctx: RouteContext<"/api/brands/[id]/chat">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/brands/[id]/chat">) => {const { id } = await ctx.params;clearChat(id);return new Response(null, { status: 204 });-}+});diff --git a/src/app/api/brands/[id]/research/route.ts b/src/app/api/brands/[id]/research/route.tsindex 07b0883d..431e0ce9 100644--- a/src/app/api/brands/[id]/research/route.ts+++ b/src/app/api/brands/[id]/research/route.ts@@ -1,9 +1,10 @@import { after } from "next/server";import { cancelResearch, retryResearch } from "@/server/brand";import { failure } from "@/server/marketing";+import { handler } from "@/server/access/route";/** Run the website research again (Retry research). */-export async function POST(_req: Request, ctx: RouteContext<"/api/brands/[id]/research">) {+export const POST = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/brands/[id]/research">) => {const { id } = await ctx.params;try {const { brand, run } = retryResearch(id);@@ -12,11 +13,11 @@ export async function POST(_req: Request, ctx: RouteContext<"/api/brands/[id]/re} catch (e) {return (e as Error).message === "Not found" ? Response.json({ error: "Not found" }, { status: 404 }) : failure(e);}-}+});/** Cancel generation: stops the research; the kit keeps what it had. */-export async function DELETE(_req: Request, ctx: RouteContext<"/api/brands/[id]/research">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/brands/[id]/research">) => {const { id } = await ctx.params;const brand = cancelResearch(id);return brand ? Response.json(brand) : Response.json({ error: "Not found" }, { status: 404 });-}+});diff --git a/src/app/api/brands/[id]/route.ts b/src/app/api/brands/[id]/route.tsindex 1442f796..ecece0a4 100644--- a/src/app/api/brands/[id]/route.ts+++ b/src/app/api/brands/[id]/route.ts@@ -2,6 +2,7 @@ import { connection } from "next/server";import { z } from "zod";import { deleteBrand, getBrand, listProducts, updateBrand } from "@/server/brand";import { failure, readBody } from "@/server/marketing";+import { handler } from "@/server/access/route";const list = (max: number, len: number) => z.array(z.string().max(len)).max(max);@@ -26,15 +27,15 @@ const Patch = z.object({});/** One brand kit with its products. */-export async function GET(_req: Request, ctx: RouteContext<"/api/brands/[id]">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/brands/[id]">) => {await connection();const { id } = await ctx.params;const brand = getBrand(id);return brand ? Response.json({ brand, products: listProducts(id) }) : Response.json({ error: "Not found" }, { status: 404 });-}+});/** Edits from the review form. */-export async function PATCH(request: Request, ctx: RouteContext<"/api/brands/[id]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/brands/[id]">) => {const { id } = await ctx.params;const body = await readBody(request, Patch);if (body instanceof Response) return body;@@ -44,10 +45,10 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/brands/[id} catch (e) {return failure(e);}-}+});/** The kit and its products leave the shelf; ads already made stay in the Library. */-export async function DELETE(_req: Request, ctx: RouteContext<"/api/brands/[id]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/brands/[id]">) => {const { id } = await ctx.params;return deleteBrand(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });-}+});diff --git a/src/app/api/brands/route.ts b/src/app/api/brands/route.tsindex 553a65e7..dd9bbefd 100644--- a/src/app/api/brands/route.ts+++ b/src/app/api/brands/route.ts@@ -2,6 +2,7 @@ import { after, connection } from "next/server";import { z } from "zod";import { createBrandFromWebsite, createManualBrand, listBrands } from "@/server/brand";import { failure, readBody } from "@/server/marketing";+import { handler } from "@/server/access/route";const Body = z.union([z.object({ website: z.string().trim().min(1).max(300) }),@@ -14,16 +15,16 @@ const Body = z.union([]);/** Brand kits, newest activity first (with product and ad counts). */-export async function GET() {+export const GET = handler({ access: "signed-in" }, async () => {await connection();return Response.json({ items: listBrands() });-}+});/*** New brand kit: `{website}` starts the research (poll GET /api/brands/:id while status is* "researching"); `{description, images?}` builds one by hand ("Describe your business").*/-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const body = await readBody(request, Body, "Add a website, or describe your business");if (body instanceof Response) return body;try {@@ -36,4 +37,4 @@ export async function POST(request: Request) {} catch (e) {return failure(e);}-}+});diff --git a/src/app/api/canvases/[id]/duplicate/route.ts b/src/app/api/canvases/[id]/duplicate/route.tsindex b9700fdc..0101c942 100644--- a/src/app/api/canvases/[id]/duplicate/route.ts+++ b/src/app/api/canvases/[id]/duplicate/route.ts@@ -1,8 +1,9 @@import { duplicateCanvas } from "@/server/canvas";+import { handler } from "@/server/access/route";/** "Copy of {name}", with the same nodes and results. */-export async function POST(_req: Request, ctx: RouteContext<"/api/canvases/[id]/duplicate">) {+export const POST = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/canvases/[id]/duplicate">) => {const { id } = await ctx.params;const c = duplicateCanvas(id);return c ? Response.json(c, { status: 201 }) : Response.json({ error: "Not found" }, { status: 404 });-}+});diff --git a/src/app/api/canvases/[id]/route.ts b/src/app/api/canvases/[id]/route.tsindex fd4346b9..88796fb1 100644--- a/src/app/api/canvases/[id]/route.ts+++ b/src/app/api/canvases/[id]/route.ts@@ -1,6 +1,7 @@import { connection } from "next/server";import { z } from "zod";import { CanvasConflict, canvasView, deleteCanvas, graphProblem, pagesProblem, parseGraph, parsePages, updateCanvas } from "@/server/canvas";+import { handler } from "@/server/access/route";const Patch = z.object({name: z.string().trim().min(1).max(80).optional(),@@ -12,15 +13,15 @@ const Patch = z.object({});/** The board, its nodes' last runs and the generations they made. */-export async function GET(_req: Request, ctx: RouteContext<"/api/canvases/[id]">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/canvases/[id]">) => {await connection();const { id } = await ctx.params;const view = canvasView(id);return view ? Response.json(view) : Response.json({ error: "Not found" }, { status: 404 });-}+});/** Rename and/or autosave the pages (or one page's graph). */-export async function PATCH(request: Request, ctx: RouteContext<"/api/canvases/[id]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/canvases/[id]">) => {const { id } = await ctx.params;const parsed = Patch.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Give the canvas a name" }, { status: 400 });@@ -35,9 +36,9 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/canvases/[if (e instanceof CanvasConflict) return Response.json({ error: e.message }, { status: e.status });throw e;}-}+});-export async function DELETE(_req: Request, ctx: RouteContext<"/api/canvases/[id]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/canvases/[id]">) => {const { id } = await ctx.params;return deleteCanvas(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });-}+});diff --git a/src/app/api/canvases/[id]/run/route.ts b/src/app/api/canvases/[id]/run/route.tsindex 8857bb32..53eca11a 100644--- a/src/app/api/canvases/[id]/run/route.ts+++ b/src/app/api/canvases/[id]/run/route.ts@@ -1,5 +1,6 @@import { z } from "zod";import { CanvasConflict, graphProblem, pagesProblem, parseGraph, parsePages, runCanvas } from "@/server/canvas";+import { handler } from "@/server/access/route";const Body = z.object({/** The page to run (the first one when omitted). */@@ -20,7 +21,7 @@ const Body = z.object({* Turn the graph into generations: one per generator node that needs to run, chained with* dependsOn along the edges. Fresh and pinned nodes are reused. 422 when nothing could start.*/-export async function POST(request: Request, ctx: RouteContext<"/api/canvases/[id]/run">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/canvases/[id]/run">) => {const { id } = await ctx.params;const parsed = Body.safeParse(await request.json().catch(() => ({})));if (!parsed.success) return Response.json({ error: "Invalid run request" }, { status: 400 });@@ -41,4 +42,4 @@ export async function POST(request: Request, ctx: RouteContext<"/api/canvases/[ireturn Response.json({ ...result, error: result.errors.length > 1 ? `${first} (and ${result.errors.length - 1} more)` : first }, { status: 422 });}return Response.json(result, { status: result.ran.length ? 201 : 200 });-}+});diff --git a/src/app/api/canvases/route.ts b/src/app/api/canvases/route.tsindex a6c37953..ea8931f7 100644--- a/src/app/api/canvases/route.ts+++ b/src/app/api/canvases/route.ts@@ -1,6 +1,7 @@import { connection } from "next/server";import { z } from "zod";import { createCanvas, listCanvases, parseGraph, parsePages } from "@/server/canvas";+import { handler } from "@/server/access/route";const Body = z.object({name: z.string().max(80).optional(),@@ -10,12 +11,12 @@ const Body = z.object({pages: z.unknown().optional(),});-export async function GET() {+export const GET = handler({ access: "signed-in" }, async () => {await connection();return Response.json({ items: listCanvases() });-}+});-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = Body.safeParse(await request.json().catch(() => ({})));if (!parsed.success) return Response.json({ error: "Invalid canvas" }, { status: 400 });const { graph: rawGraph, pages: rawPages, ...rest } = parsed.data;@@ -27,4 +28,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: 422 });}-}+});diff --git a/src/app/api/cinema/projects/[id]/director/route.ts b/src/app/api/cinema/projects/[id]/director/route.tsindex c80c7118..ab8e692e 100644--- a/src/app/api/cinema/projects/[id]/director/route.ts+++ b/src/app/api/cinema/projects/[id]/director/route.ts@@ -2,17 +2,18 @@ import { after, connection } from "next/server";import { clearChat, getChat } from "@/server/cinema";import { askDirector } from "@/server/cinema-director";import { DirectorAsk, body, handle } from "@/server/cinema-schemas";+import { handler } from "@/server/access/route";-export async function GET(_req: Request, ctx: RouteContext<"/api/cinema/projects/[id]/director">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/cinema/projects/[id]/director">) => {await connection();return handle(async () => {const { id } = await ctx.params;return Response.json({ messages: getChat(id) });});-}+});/** Ask the AI Director; answers with the whole conversation (the reply proposes shots, never renders them). */-export async function POST(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/director">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/director">) => {return handle(async () => {const { id } = await ctx.params;const b = await body(request, DirectorAsk, "Write a message first");@@ -21,12 +22,12 @@ export async function POST(request: Request, ctx: RouteContext<"/api/cinema/projafter(() => reply.catch(() => {}));return Response.json({ messages: await reply });});-}+});-export async function DELETE(_req: Request, ctx: RouteContext<"/api/cinema/projects/[id]/director">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/cinema/projects/[id]/director">) => {return handle(async () => {const { id } = await ctx.params;clearChat(id);return new Response(null, { status: 204 });});-}+});diff --git a/src/app/api/cinema/projects/[id]/folders/[folderId]/route.ts b/src/app/api/cinema/projects/[id]/folders/[folderId]/route.tsindex b28ef54f..e11d6de4 100644--- a/src/app/api/cinema/projects/[id]/folders/[folderId]/route.ts+++ b/src/app/api/cinema/projects/[id]/folders/[folderId]/route.ts@@ -1,19 +1,20 @@import { deleteFolder, updateFolder } from "@/server/cinema";import { FolderPatch, body, handle } from "@/server/cinema-schemas";+import { handler } from "@/server/access/route";-export async function PATCH(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/folders/[folderId]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/folders/[folderId]">) => {return handle(async () => {const { id, folderId } = await ctx.params;const patch = await body(request, FolderPatch, "Those folder settings aren't valid");return Response.json(updateFolder(id, folderId, patch));});-}+});/** Its takes and subfolders move up to the parent folder. */-export async function DELETE(_req: Request, ctx: RouteContext<"/api/cinema/projects/[id]/folders/[folderId]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/cinema/projects/[id]/folders/[folderId]">) => {return handle(async () => {const { id, folderId } = await ctx.params;deleteFolder(id, folderId);return new Response(null, { status: 204 });});-}+});diff --git a/src/app/api/cinema/projects/[id]/folders/route.ts b/src/app/api/cinema/projects/[id]/folders/route.tsindex 6347527c..38a121b8 100644--- a/src/app/api/cinema/projects/[id]/folders/route.ts+++ b/src/app/api/cinema/projects/[id]/folders/route.ts@@ -1,10 +1,11 @@import { createFolder } from "@/server/cinema";import { FolderCreate, body, handle } from "@/server/cinema-schemas";+import { handler } from "@/server/access/route";-export async function POST(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/folders">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/folders">) => {return handle(async () => {const { id } = await ctx.params;const input = await body(request, FolderCreate, "Give the folder a name");return Response.json(createFolder(id, input), { status: 201 });});-}+});diff --git a/src/app/api/cinema/projects/[id]/generate/route.ts b/src/app/api/cinema/projects/[id]/generate/route.tsindex aa618ca6..3d369a1e 100644--- a/src/app/api/cinema/projects/[id]/generate/route.ts+++ b/src/app/api/cinema/projects/[id]/generate/route.ts@@ -1,14 +1,15 @@import { generateInProject } from "@/server/cinema-generate";import { GenerateBody, body, handle } from "@/server/cinema-schemas";+import { handler } from "@/server/access/route";/*** Generate from the workspace: plans the run (model, chained steps), checks the project's cost* cap, creates the generations and records them in the project (in `folderId`).*/-export async function POST(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/generate">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/generate">) => {return handle(async () => {const { id } = await ctx.params;const b = await body(request, GenerateBody, "That request isn't valid");return Response.json(generateInProject(id, b.input, b.folderId ?? null), { status: 201 });});-}+});diff --git a/src/app/api/cinema/projects/[id]/items/[generationId]/retry/route.ts b/src/app/api/cinema/projects/[id]/items/[generationId]/retry/route.tsindex a32f81a8..ee1bcdd4 100644--- a/src/app/api/cinema/projects/[id]/items/[generationId]/retry/route.ts+++ b/src/app/api/cinema/projects/[id]/items/[generationId]/retry/route.ts@@ -1,10 +1,11 @@import { retryItem } from "@/server/cinema";import { handle } from "@/server/cinema-schemas";+import { handler } from "@/server/access/route";/** Run a failed take again (same request, same folder). */-export async function POST(_req: Request, ctx: RouteContext<"/api/cinema/projects/[id]/items/[generationId]/retry">) {+export const POST = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/cinema/projects/[id]/items/[generationId]/retry">) => {return handle(async () => {const { id, generationId } = await ctx.params;return Response.json({ items: retryItem(id, generationId) }, { status: 201 });});-}+});diff --git a/src/app/api/cinema/projects/[id]/items/[generationId]/tiles/route.ts b/src/app/api/cinema/projects/[id]/items/[generationId]/tiles/route.tsindex 903e9c3f..534576c3 100644--- a/src/app/api/cinema/projects/[id]/items/[generationId]/tiles/route.ts+++ b/src/app/api/cinema/projects/[id]/items/[generationId]/tiles/route.ts@@ -1,11 +1,12 @@import { setTiles } from "@/server/cinema";import { TilesPut, body, handle } from "@/server/cinema-schemas";+import { handler } from "@/server/access/route";/** The tiles the browser cut from a grid contact sheet (each already saved as an upload). */-export async function PUT(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/items/[generationId]/tiles">) {+export const PUT = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/items/[generationId]/tiles">) => {return handle(async () => {const { id, generationId } = await ctx.params;const b = await body(request, TilesPut, "Those tiles aren't valid");return Response.json(setTiles(id, generationId, b.tiles));});-}+});diff --git a/src/app/api/cinema/projects/[id]/items/route.ts b/src/app/api/cinema/projects/[id]/items/route.tsindex 231293cf..337b7969 100644--- a/src/app/api/cinema/projects/[id]/items/route.ts+++ b/src/app/api/cinema/projects/[id]/items/route.ts@@ -1,13 +1,14 @@import { connection } from "next/server";import { listItems, listStudioGenerations, moveItems, removeItems, setFavorites } from "@/server/cinema";import { ItemsDelete, ItemsPatch, body, handle } from "@/server/cinema-schemas";+import { handler } from "@/server/access/route";/*** The project's generations. `?folder=<id>` one folder (`&nested=1` with its subfolders),* `?folder=root` the takes outside any folder, `?favorites=1` liked takes, `?scope=studio` every* Cinema Studio generation in every project ("My Generations"). Default: the whole project.*/-export async function GET(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/items">) {+export const GET = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/items">) => {await connection();return handle(async () => {const { id } = await ctx.params;@@ -21,10 +22,10 @@ export async function GET(request: Request, ctx: RouteContext<"/api/cinema/proje});return Response.json({ items });});-}+});/** Bulk: move to a folder (`folderId`, null = project root) and/or like / unlike. */-export async function PATCH(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/items">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/items">) => {return handle(async () => {const { id } = await ctx.params;const b = await body(request, ItemsPatch, "Pick the takes to change");@@ -33,13 +34,13 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/cinema/proconst liked = b.favorite !== undefined ? setFavorites(id, b.ids, b.favorite) : 0;return Response.json({ ok: true, moved, liked });});-}+});/** Bulk: take out of the project; `deleteGenerations` moves them to the library's Trash (restorable, still filed here). Only this project's takes are touched. */-export async function DELETE(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/items">) {+export const DELETE = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/items">) => {return handle(async () => {const { id } = await ctx.params;const b = await body(request, ItemsDelete, "Pick the takes to delete");return Response.json({ removed: removeItems(id, b.ids, { deleteGenerations: b.deleteGenerations }) });});-}+});diff --git a/src/app/api/cinema/projects/[id]/route.ts b/src/app/api/cinema/projects/[id]/route.tsindex a364cea8..bbcc45ed 100644--- a/src/app/api/cinema/projects/[id]/route.ts+++ b/src/app/api/cinema/projects/[id]/route.ts@@ -2,9 +2,10 @@ import { connection } from "next/server";import { CinemaError, deleteProject, getProject, listFolders, spentUsd, updateProject } from "@/server/cinema";import { ProjectPatch, body, handle } from "@/server/cinema-schemas";import { cinemaContext } from "@/server/cinema-generate";+import { handler } from "@/server/access/route";/** The project with its folders, its estimated spend and what this install can run (cloud models allowed, a civitai key). */-export async function GET(_req: Request, ctx: RouteContext<"/api/cinema/projects/[id]">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/cinema/projects/[id]">) => {await connection();return handle(async () => {const { id } = await ctx.params;@@ -13,20 +14,20 @@ export async function GET(_req: Request, ctx: RouteContext<"/api/cinema/projectsconst { cloudAllowed, civitai } = cinemaContext();return Response.json({ project, folders: listFolders(id), spentUsd: spentUsd(id), context: { cloudAllowed, civitai } });});-}+});-export async function PATCH(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/cinema/projects/[id]">) => {return handle(async () => {const { id } = await ctx.params;const patch = await body(request, ProjectPatch, "Those project settings aren't valid");return Response.json(updateProject(id, patch));});-}+});-export async function DELETE(_req: Request, ctx: RouteContext<"/api/cinema/projects/[id]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/cinema/projects/[id]">) => {return handle(async () => {const { id } = await ctx.params;deleteProject(id);return new Response(null, { status: 204 });});-}+});diff --git a/src/app/api/cinema/projects/route.ts b/src/app/api/cinema/projects/route.tsindex 051abb94..81de5c63 100644--- a/src/app/api/cinema/projects/route.ts+++ b/src/app/api/cinema/projects/route.ts@@ -1,15 +1,16 @@import { connection } from "next/server";import { createProject, listProjects } from "@/server/cinema";import { ProjectCreate, body, handle } from "@/server/cinema-schemas";+import { handler } from "@/server/access/route";-export async function GET() {+export const GET = handler({ access: "signed-in" }, async () => {await connection();return handle(() => Response.json({ items: listProjects() }));-}+});-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const input = await body(request, ProjectCreate, "Give the project a name");return Response.json(createProject(input), { status: 201 });});-}+});diff --git a/src/app/api/comfyui/route.ts b/src/app/api/comfyui/route.tsindex 8facd2f1..b3efbcc4 100644--- a/src/app/api/comfyui/route.ts+++ b/src/app/api/comfyui/route.ts@@ -1,8 +1,9 @@import { connection } from "next/server";import { loadManifest, modelInventory, probeComfy } from "@/server/providers/comfyui";+import { handler } from "@/server/access/route";/** Workflow library + which required models are present on the connected server. */-export async function GET() {+export const GET = handler({ access: "signed-in" }, async () => {await connection();const manifest = loadManifest();const reachable = await probeComfy(true);@@ -17,4 +18,4 @@ export async function GET() {models: w.models.map((m) => ({ ...m, present: inventory ? present.has(m.file) : null })),})),});-}+});diff --git a/src/app/api/content-factory/claude/route.ts b/src/app/api/content-factory/claude/route.tsindex 789827f4..04faafc5 100644--- a/src/app/api/content-factory/claude/route.ts+++ b/src/app/api/content-factory/claude/route.ts@@ -1,6 +1,7 @@import { z } from "zod";import { claudePrompt, handle, SeriesInputSchema } from "@/server/content-factory";import { body } from "@/server/faceless";+import { handler } from "@/server/access/route";const Ask = SeriesInputSchema.extend({prompt: z.string().trim().min(1, "Say what the video is about").max(2000),@@ -9,6 +10,6 @@ const Ask = SeriesInputSchema.extend({});/** "Generate in Claude": the message to paste into Claude Code (Fuobe's MCP server connected); nothing is sent anywhere. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => Response.json(claudePrompt(await body(request, Ask, "Say what the video is about and pick the settings"))));-}+});diff --git a/src/app/api/content-factory/estimate/route.ts b/src/app/api/content-factory/estimate/route.tsindex e27435c2..5e91ec45 100644--- a/src/app/api/content-factory/estimate/route.ts+++ b/src/app/api/content-factory/estimate/route.ts@@ -1,6 +1,7 @@import { z } from "zod";import { BriefSchema, estimateSeries, handle, SeriesInputSchema } from "@/server/content-factory";import { body } from "@/server/faceless";+import { handler } from "@/server/access/route";const Ask = SeriesInputSchema.extend({seriesId: z.string().max(20).optional(),@@ -9,6 +10,6 @@ const Ask = SeriesInputSchema.extend({});/** What the whole series would cost (one episode at the brief's pace × the episodes), and whether it runs as a demo. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => Response.json(estimateSeries(await body(request, Ask, "Those settings aren't valid"))));-}+});diff --git a/src/app/api/content-factory/series/[id]/episodes/route.ts b/src/app/api/content-factory/series/[id]/episodes/route.tsindex 546fc6d9..34172f87 100644--- a/src/app/api/content-factory/series/[id]/episodes/route.ts+++ b/src/app/api/content-factory/series/[id]/episodes/route.ts@@ -2,6 +2,7 @@ import { z } from "zod";import { MAX_EPISODES } from "@/lib/catalog/content-factory";import { addEpisodes, handle } from "@/server/content-factory";import { body } from "@/server/faceless";+import { handler } from "@/server/access/route";const More = z.object({count: z.number().int().min(1).max(MAX_EPISODES, `Up to ${MAX_EPISODES} episodes at a time`),@@ -10,9 +11,9 @@ const More = z.object({});/** "Next episode": plan and start more episodes after the ones already made. */-export async function POST(request: Request, ctx: RouteContext<"/api/content-factory/series/[id]/episodes">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/content-factory/series/[id]/episodes">) => {return handle(async () => {const { id } = await ctx.params;return Response.json(await addEpisodes(id, await body(request, More, "Say how many episodes to add")));});-}+});diff --git a/src/app/api/content-factory/series/[id]/generate/route.ts b/src/app/api/content-factory/series/[id]/generate/route.tsindex e6d0e8db..a99d6f99 100644--- a/src/app/api/content-factory/series/[id]/generate/route.ts+++ b/src/app/api/content-factory/series/[id]/generate/route.ts@@ -1,13 +1,14 @@import { z } from "zod";import { generateSeries, handle, SeriesInputSchema } from "@/server/content-factory";import { body } from "@/server/faceless";+import { handler } from "@/server/access/route";const Generate = SeriesInputSchema.extend({ review: z.boolean().optional() });/** "Generate here": plan the episodes, make the series' channel and start every episode. */-export async function POST(request: Request, ctx: RouteContext<"/api/content-factory/series/[id]/generate">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/content-factory/series/[id]/generate">) => {return handle(async () => {const { id } = await ctx.params;return Response.json(await generateSeries(id, await body(request, Generate, "Say what the video is about and pick the settings")));});-}+});diff --git a/src/app/api/content-factory/series/[id]/read/route.ts b/src/app/api/content-factory/series/[id]/read/route.tsindex 17132b58..65848570 100644--- a/src/app/api/content-factory/series/[id]/read/route.ts+++ b/src/app/api/content-factory/series/[id]/read/route.ts@@ -1,13 +1,14 @@import { z } from "zod";import { handle, rereadSeries } from "@/server/content-factory";import { body } from "@/server/faceless";+import { handler } from "@/server/access/route";const Read = z.object({ engine: z.enum(["cloud", "open"]) });/** Read the reference clip again (on either engine). */-export async function POST(request: Request, ctx: RouteContext<"/api/content-factory/series/[id]/read">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/content-factory/series/[id]/read">) => {return handle(async () => {const { id } = await ctx.params;return Response.json(await rereadSeries(id, (await body(request, Read, "Pick an engine")).engine));});-}+});diff --git a/src/app/api/content-factory/series/[id]/route.ts b/src/app/api/content-factory/series/[id]/route.tsindex 2f57b7ed..5a9a3198 100644--- a/src/app/api/content-factory/series/[id]/route.ts+++ b/src/app/api/content-factory/series/[id]/route.ts@@ -2,30 +2,31 @@ import { connection } from "next/server";import { z } from "zod";import { BriefSchema, deleteSeries, handle, seriesView, updateSeries } from "@/server/content-factory";import { body } from "@/server/faceless";+import { handler } from "@/server/access/route";const Patch = z.object({ brief: BriefSchema.optional(), name: z.string().max(60).optional() });/** The series: its reference, how far reading it has got, the brief, the plan and the episodes. */-export async function GET(_req: Request, ctx: RouteContext<"/api/content-factory/series/[id]">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/content-factory/series/[id]">) => {await connection();return handle(async () => Response.json(seriesView((await ctx.params).id)));-}+});/** Edit the brief by hand, or rename the series. */-export async function PATCH(request: Request, ctx: RouteContext<"/api/content-factory/series/[id]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/content-factory/series/[id]">) => {return handle(async () => {const { id } = await ctx.params;return Response.json(updateSeries(id, await body(request, Patch, "That brief isn't valid")));});-}+});/*** Deletes the series and its channel, stopping what its episodes still render (finished videos stay in the Library).* `?draft=1` deletes only a draft that was never made (the composer moving on from a clip it was reading).*/-export async function DELETE(request: Request, ctx: RouteContext<"/api/content-factory/series/[id]">) {+export const DELETE = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/content-factory/series/[id]">) => {return handle(async () => {await deleteSeries((await ctx.params).id, { draftOnly: new URL(request.url).searchParams.get("draft") === "1" });return new Response(null, { status: 204 });});-}+});diff --git a/src/app/api/content-factory/series/route.ts b/src/app/api/content-factory/series/route.tsindex 198cf1d2..d7219867 100644--- a/src/app/api/content-factory/series/route.ts+++ b/src/app/api/content-factory/series/route.ts@@ -2,6 +2,7 @@ import { connection } from "next/server";import { z } from "zod";import { createSeries, handle, listSeries, ReferenceSchema } from "@/server/content-factory";import { body } from "@/server/faceless";+import { handler } from "@/server/access/route";const Create = z.object({reference: ReferenceSchema.nullable(),@@ -10,18 +11,18 @@ const Create = z.object({});/** Series that have been made, newest first. */-export async function GET() {+export const GET = handler({ access: "signed-in" }, async () => {await connection();return handle(() => Response.json({ items: listSeries() }));-}+});/*** A new series around a reference: an upload, a link (fetched only through the SSRF-safe fetch; 422 with* `needsUpload` when it gives no clip) or a preset. Reading a clip into a style brief starts straight away.*/-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const input = await body(request, Create, "Add a reference clip, a link or a preset");return Response.json(await createSeries(input), { status: 201 });});-}+});diff --git a/src/app/api/dub/[id]/route.ts b/src/app/api/dub/[id]/route.tsindex 448a9df5..eda8b7b6 100644--- a/src/app/api/dub/[id]/route.ts+++ b/src/app/api/dub/[id]/route.ts@@ -1,18 +1,19 @@import { connection } from "next/server";import { z } from "zod";import { CueSchema, deleteDubSession, dubView, getDubSession, saveDubDraft } from "@/server/dub";+import { handler } from "@/server/access/route";const Patch = z.object({ lang: z.string().min(2).max(12), cues: z.array(CueSchema).max(3000) });-export async function GET(_req: Request, ctx: RouteContext<"/api/dub/[id]">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/dub/[id]">) => {await connection();const { id } = await ctx.params;const s = getDubSession(id);return s ? Response.json(dubView(s)) : Response.json({ error: "Not found" }, { status: 404 });-}+});/** Save the reviewed lines of one language. */-export async function PATCH(request: Request, ctx: RouteContext<"/api/dub/[id]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/dub/[id]">) => {const { id } = await ctx.params;const parsed = Patch.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Those lines can't be saved" }, { status: 400 });@@ -21,10 +22,10 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/dub/[id]">} catch (e) {return Response.json({ error: (e as Error).message }, { status: getDubSession(id) ? 422 : 404 });}-}+});/** Forget the dub (its results stay in the Library). */-export async function DELETE(_req: Request, ctx: RouteContext<"/api/dub/[id]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/dub/[id]">) => {const { id } = await ctx.params;return deleteDubSession(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });-}+});diff --git a/src/app/api/dub/[id]/voice/route.ts b/src/app/api/dub/[id]/voice/route.tsindex 88efd6d9..3d101d3c 100644--- a/src/app/api/dub/[id]/voice/route.ts+++ b/src/app/api/dub/[id]/voice/route.ts@@ -1,5 +1,6 @@import { z } from "zod";import { CueSchema, getDubSession, previewVoiceDub, voiceDub } from "@/server/dub";+import { handler } from "@/server/access/route";const Body = z.object({lang: z.string().min(2).max(12),@@ -9,7 +10,7 @@ const Body = z.object({});/** Speak one language's reviewed lines in the cloned voice: the voice pipeline; `?preview=1` only prices it. */-export async function POST(request: Request, ctx: RouteContext<"/api/dub/[id]/voice">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/dub/[id]/voice">) => {const { id } = await ctx.params;const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Pick the language to voice" }, { status: 400 });@@ -21,4 +22,4 @@ export async function POST(request: Request, ctx: RouteContext<"/api/dub/[id]/vo} catch (e) {return Response.json({ error: (e as Error).message }, { status: 422 });}-}+});diff --git a/src/app/api/dub/route.ts b/src/app/api/dub/route.tsindex d0ed2bdb..d9dc6959 100644--- a/src/app/api/dub/route.ts+++ b/src/app/api/dub/route.ts@@ -2,6 +2,7 @@ import { connection } from "next/server";import { z } from "zod";import { ONE_SHOT_MODELS } from "@/lib/av/dub";import { createDubSession, listDubSessions, previewDub } from "@/server/dub";+import { handler } from "@/server/access/route";const Body = z.object({engine: z.enum(["cloud", "open"]),@@ -16,14 +17,14 @@ const Body = z.object({});/** Recent dubs with the state of every step. */-export async function GET(request: Request) {+export const GET = handler({ access: "signed-in" }, async (request: Request) => {await connection();const limit = Number(new URL(request.url).searchParams.get("limit") ?? 30);return Response.json({ items: listDubSessions(Number.isFinite(limit) ? limit : 30) });-}+});/** Start a dub: one-shot jobs (cloud) or the prepare pipeline (both engines); `?preview=1` only prices it. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) {const first = parsed.error.issues[0];@@ -36,4 +37,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: 422 });}-}+});diff --git a/src/app/api/elements/[id]/lora/route.ts b/src/app/api/elements/[id]/lora/route.tsindex e155df48..38cd3d1f 100644--- a/src/app/api/elements/[id]/lora/route.ts+++ b/src/app/api/elements/[id]/lora/route.ts@@ -2,6 +2,7 @@ import { z } from "zod";import { TRAINING_FAMILY_IDS, type TrainingFamily } from "@/lib/catalog/training";import { attachLora } from "@/server/training";import { getElement } from "@/server/elements";+import { handler } from "@/server/access/route";const Body = z.object({file: z.string().min(1).max(300),@@ -10,7 +11,7 @@ const Body = z.object({});/** Attach a LoRA you trained yourself (already in ComfyUI/models/loras): Z-Image Turbo unless it names its family. */-export async function POST(request: Request, ctx: RouteContext<"/api/elements/[id]/lora">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/elements/[id]/lora">) => {const { id } = await ctx.params;const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Enter the LoRA file name" }, { status: 400 });@@ -21,4 +22,4 @@ export async function POST(request: Request, ctx: RouteContext<"/api/elements/[i} catch (e) {return Response.json({ error: (e as Error).message }, { status: 422 });}-}+});diff --git a/src/app/api/elements/[id]/route.ts b/src/app/api/elements/[id]/route.tsindex 4f8555ad..1e500419 100644--- a/src/app/api/elements/[id]/route.ts+++ b/src/app/api/elements/[id]/route.ts@@ -3,6 +3,7 @@ import { z } from "zod";import { MAX_ELEMENT_PHOTOS } from "@/lib/catalog/elements";import { identityKey } from "@/lib/catalog/training";import { deleteElement, getElement, updateElement } from "@/server/elements";+import { handler } from "@/server/access/route";const Patch = z.object({name: z.string().trim().min(1).max(60).optional(),@@ -12,14 +13,14 @@ const Patch = z.object({removeIdentities: z.array(z.string()).optional(),});-export async function GET(_req: Request, ctx: RouteContext<"/api/elements/[id]">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/elements/[id]">) => {await connection();const { id } = await ctx.params;const el = getElement(id);return el ? Response.json(el) : Response.json({ error: "Not found" }, { status: 404 });-}+});-export async function PATCH(request: Request, ctx: RouteContext<"/api/elements/[id]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/elements/[id]">) => {const { id } = await ctx.params;const parsed = Patch.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Invalid element" }, { status: 400 });@@ -28,10 +29,10 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/elements/[const loras = removeIdentities && current ? current.loras.filter((l) => !removeIdentities.includes(identityKey(l))) : undefined;const el = updateElement(id, { ...patch, ...(loras ? { loras } : {}) });return el ? Response.json(el) : Response.json({ error: "Not found" }, { status: 404 });-}+});-export async function DELETE(_req: Request, ctx: RouteContext<"/api/elements/[id]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/elements/[id]">) => {const { id } = await ctx.params;deleteElement(id);return new Response(null, { status: 204 });-}+});diff --git a/src/app/api/elements/[id]/training-kit/route.ts b/src/app/api/elements/[id]/training-kit/route.tsindex ccc0f0b5..dfbdb792 100644--- a/src/app/api/elements/[id]/training-kit/route.ts+++ b/src/app/api/elements/[id]/training-kit/route.ts@@ -1,8 +1,9 @@import { AITK_FAMILIES, type TrainingFamily } from "@/lib/catalog/training";import { trainingKit } from "@/server/training";+import { handler } from "@/server/access/route";/** Dataset + AI-Toolkit config + README, to train the element's LoRA on any GPU (?family= picks the base; Z-Image Turbo by default). */-export async function GET(req: Request, ctx: RouteContext<"/api/elements/[id]/training-kit">) {+export const GET = handler({ access: "signed-in" }, async (req: Request, ctx: RouteContext<"/api/elements/[id]/training-kit">) => {const { id } = await ctx.params;const asked = new URL(req.url).searchParams.get("family") ?? "z-image-turbo";if (!AITK_FAMILIES.includes(asked as TrainingFamily)) return Response.json({ error: `AI-Toolkit kits are for ${AITK_FAMILIES.join(", ")}` }, { status: 400 });@@ -14,4 +15,4 @@ export async function GET(req: Request, ctx: RouteContext<"/api/elements/[id]/tr} catch (e) {return Response.json({ error: (e as Error).message }, { status: 422 });}-}+});diff --git a/src/app/api/elements/[id]/trainings/route.ts b/src/app/api/elements/[id]/trainings/route.tsindex 5abbcf10..31c5f0b3 100644--- a/src/app/api/elements/[id]/trainings/route.ts+++ b/src/app/api/elements/[id]/trainings/route.ts@@ -4,9 +4,10 @@ import { targetsFor, TRAINING_TARGETS } from "@/lib/catalog/training";import { getElement } from "@/server/elements";import { ensureRunner } from "@/server/generations";import { describeTargets, listTrainings, startTraining } from "@/server/training";+import { handler } from "@/server/access/route";/** The targets this element can train on (each with what stops it, its price and whether it's a demo), and its trainings. */-export async function GET(_req: Request, ctx: RouteContext<"/api/elements/[id]/trainings">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/elements/[id]/trainings">) => {await connection();const { id } = await ctx.params;ensureRunner(); // the background poller also checks training jobs@@ -15,12 +16,12 @@ export async function GET(_req: Request, ctx: RouteContext<"/api/elements/[id]/ttargets: describeTargets(el ? targetsFor(el.kind) : TRAINING_TARGETS),items: listTrainings(id),});-}+});// consent: the person in the photos agreed (required for a character; SOUL_ID_COPY.consent is the line they confirm).const Body = z.object({ target: z.string().min(1), consent: z.boolean().optional() });-export async function POST(request: Request, ctx: RouteContext<"/api/elements/[id]/trainings">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/elements/[id]/trainings">) => {const { id } = await ctx.params;const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Pick what to train" }, { status: 400 });@@ -30,4 +31,4 @@ export async function POST(request: Request, ctx: RouteContext<"/api/elements/[i} catch (e) {return Response.json({ error: (e as Error).message }, { status: 422 });}-}+});diff --git a/src/app/api/elements/route.ts b/src/app/api/elements/route.tsindex 38a77b51..942b81f4 100644--- a/src/app/api/elements/route.ts+++ b/src/app/api/elements/route.ts@@ -2,6 +2,7 @@ import { connection } from "next/server";import { z } from "zod";import { MAX_ELEMENT_PHOTOS } from "@/lib/catalog/elements";import { createElement, listElements } from "@/server/elements";+import { handler } from "@/server/access/route";const Kind = z.enum(["character", "location", "prop", "style", "voice"]);@@ -12,17 +13,17 @@ const Body = z.object({references: z.array(z.string().startsWith("/api/files/")).max(MAX_ELEMENT_PHOTOS),});-export async function GET(request: Request) {+export const GET = handler({ access: "signed-in" }, async (request: Request) => {await connection();const kind = Kind.safeParse(new URL(request.url).searchParams.get("kind"));return Response.json({ items: listElements(kind.success ? kind.data : undefined) });-}+});-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Give the element a name" }, { status: 400 });if (!parsed.data.references.length && !parsed.data.description?.trim()) {return Response.json({ error: "Add at least one photo or a description" }, { status: 400 });}return Response.json(createElement(parsed.data), { status: 201 });-}+});diff --git a/src/app/api/enhance/route.ts b/src/app/api/enhance/route.tsindex 0e350cab..57381813 100644--- a/src/app/api/enhance/route.ts+++ b/src/app/api/enhance/route.ts@@ -1,7 +1,8 @@import { enhancePrompt } from "@/server/enhance";import type { MediaKind, Operation } from "@/lib/catalog/types";+import { handler } from "@/server/access/route";-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const { prompt, kind, op } = (await request.json().catch(() => ({}))) as { prompt?: string; kind?: MediaKind; op?: Operation };if (!prompt?.trim()) return Response.json({ error: "Empty prompt" }, { status: 400 });try {@@ -9,4 +10,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: 502 });}-}+});diff --git a/src/app/api/evolution/direction/route.ts b/src/app/api/evolution/direction/route.tsindex 72ad5c17..77170f73 100644--- a/src/app/api/evolution/direction/route.ts+++ b/src/app/api/evolution/direction/route.ts@@ -1,10 +1,11 @@import { DirectionSchema, writeDirection } from "@/server/evolution";import { body, handle } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";/** Write the creative direction from the references and your words: Claude, Ollama, or Fuobe's offline writer. Never generates. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const input = await body(request, DirectionSchema, "Pick how much should change, then add references or a few words");return Response.json(await writeDirection(input));});-}+});diff --git a/src/app/api/evolution/estimate/route.ts b/src/app/api/evolution/estimate/route.tsindex 2dabbcb7..fad06c24 100644--- a/src/app/api/evolution/estimate/route.ts+++ b/src/app/api/evolution/estimate/route.ts@@ -1,10 +1,11 @@import { estimateEvolution, EvolutionEstimateSchema } from "@/server/evolution";import { body, handle } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";/** The price, the pieces and the notes for the current settings, before anything runs ("Free" on your GPU). */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const input = await body(request, EvolutionEstimateSchema, "Add a clip and pick how much should change");return Response.json(estimateEvolution(input));});-}+});diff --git a/src/app/api/evolution/route.ts b/src/app/api/evolution/route.tsindex b6911fbe..05ccbe46 100644--- a/src/app/api/evolution/route.ts+++ b/src/app/api/evolution/route.ts@@ -1,12 +1,13 @@import { createEvolution, EvolutionBodySchema } from "@/server/evolution";import { body, handle, once } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";/** Evolve a clip (Fuobe Evolution): the direction is written first when none is given; pieces are joined and the sound put back. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const input = await body(request, EvolutionBodySchema, "Add a clip and pick how much should change");// A repeated requestId (a second click on Evolve) gets the run the first one started.const result = await once("evolution", input.requestId, () => createEvolution(input));return Response.json(result, { status: 201 });});-}+});diff --git a/src/app/api/explainer/document/route.ts b/src/app/api/explainer/document/route.tsindex 76dd637a..d1813956 100644--- a/src/app/api/explainer/document/route.ts+++ b/src/app/api/explainer/document/route.ts@@ -1,10 +1,11 @@import { EngineSchema, FacelessError, handle, MAX_DOCUMENT_BYTES, readDocument } from "@/server/faceless";+import { handler } from "@/server/access/route";/*** A PDF or Word source (multipart: "file", "engine"): the text is read on the server and, when the* document is longer than the script writer reads, summarised. The file itself isn't kept.*/-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const form = await request.formData().catch(() => null);const file = form?.get("file");@@ -13,4 +14,4 @@ export async function POST(request: Request) {const engine = EngineSchema.safeParse(form?.get("engine"));return Response.json(await readDocument({ name: file.name, data: Buffer.from(await file.arrayBuffer()), type: file.type }, engine.success ? engine.data : "cloud"));});-}+});diff --git a/src/app/api/explainer/link/route.ts b/src/app/api/explainer/link/route.tsindex fad633f4..1667d7d4 100644--- a/src/app/api/explainer/link/route.ts+++ b/src/app/api/explainer/link/route.ts@@ -1,12 +1,13 @@import { z } from "zod";import { body, EngineSchema, handle, summarizeLink } from "@/server/faceless";+import { handler } from "@/server/access/route";const Ask = z.object({ url: z.string().url("Paste a full link, starting with https://").max(2000), engine: EngineSchema });/** A link source: the page is fetched (public addresses only) and summarised for the script writer. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const { url, engine } = await body(request, Ask, "Paste a link – article, page");return Response.json(await summarizeLink(url, engine));});-}+});diff --git a/src/app/api/explainer/route.ts b/src/app/api/explainer/route.tsindex aad9ea88..e13cd3af 100644--- a/src/app/api/explainer/route.ts+++ b/src/app/api/explainer/route.ts@@ -2,6 +2,7 @@ import { connection } from "next/server";import { z } from "zod";import { MAX_TOPIC } from "@/lib/catalog/faceless";import { body, createEpisode, handle, listEpisodes, SettingsSchema, SourceSchema } from "@/server/faceless";+import { handler } from "@/server/access/route";const Create = z.object({prompt: z.string().max(MAX_TOPIC, "Prompt is too long (max 5000 characters)"),@@ -12,19 +13,19 @@ const Create = z.object({});/** History: your explainers, newest first (`?q=` search, `?liked=1`). */-export async function GET(request: Request) {+export const GET = handler({ access: "signed-in" }, async (request: Request) => {await connection();return handle(() => {const p = new URL(request.url).searchParams;return Response.json({ items: listEpisodes({ kind: "explainer", q: p.get("q") ?? undefined, liked: p.get("liked") === "1", limit: 200 }) });});-}+});/** Explain something: the script is written from the prompt and sources, then rendered. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const input = await body(request, Create, "Add a prompt, or attach a file or link");const episode = createEpisode({ kind: "explainer", topic: input.prompt, sources: input.sources, settings: input.settings, autoRender: !input.review });return Response.json(episode, { status: 201 });});-}+});diff --git a/src/app/api/faceless/channels/[id]/avatar/route.ts b/src/app/api/faceless/channels/[id]/avatar/route.tsindex 44f09c6d..14d196a5 100644--- a/src/app/api/faceless/channels/[id]/avatar/route.ts+++ b/src/app/api/faceless/channels/[id]/avatar/route.ts@@ -1,9 +1,10 @@import { handle, makeAvatar } from "@/server/faceless";+import { handler } from "@/server/access/route";/** Draw a channel avatar in the channel's style (one picture generation; it becomes the channel's picture when it's done). */-export async function POST(_req: Request, ctx: RouteContext<"/api/faceless/channels/[id]/avatar">) {+export const POST = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/faceless/channels/[id]/avatar">) => {return handle(async () => {const { id } = await ctx.params;return Response.json(makeAvatar(id), { status: 201 });});-}+});diff --git a/src/app/api/faceless/channels/[id]/route.ts b/src/app/api/faceless/channels/[id]/route.tsindex 2a435c70..db6b6df0 100644--- a/src/app/api/faceless/channels/[id]/route.ts+++ b/src/app/api/faceless/channels/[id]/route.ts@@ -1,6 +1,7 @@import { connection } from "next/server";import { z } from "zod";import { body, deleteChannel, FacelessError, GenreSchema, getChannel, handle, listEpisodes, SettingsSchema, updateChannel } from "@/server/faceless";+import { handler } from "@/server/access/route";const Patch = z.object({name: z.string().max(60).optional(),@@ -12,7 +13,7 @@ const Patch = z.object({});/** The channel with its episodes. */-export async function GET(_req: Request, ctx: RouteContext<"/api/faceless/channels/[id]">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/faceless/channels/[id]">) => {await connection();return handle(async () => {const { id } = await ctx.params;@@ -20,21 +21,21 @@ export async function GET(_req: Request, ctx: RouteContext<"/api/faceless/channeif (!channel) throw new FacelessError("Channel not found", 404);return Response.json({ channel, episodes: listEpisodes({ channelId: id, limit: 200 }) });});-}+});-export async function PATCH(request: Request, ctx: RouteContext<"/api/faceless/channels/[id]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/faceless/channels/[id]">) => {return handle(async () => {const { id } = await ctx.params;const patch = await body(request, Patch, "Those channel settings aren't valid");return Response.json(await updateChannel(id, patch));});-}+});/** Deletes the channel and its episodes, stopping what they still render (finished videos stay in the Library). */-export async function DELETE(_req: Request, ctx: RouteContext<"/api/faceless/channels/[id]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/faceless/channels/[id]">) => {return handle(async () => {const { id } = await ctx.params;await deleteChannel(id);return new Response(null, { status: 204 });});-}+});diff --git a/src/app/api/faceless/channels/route.ts b/src/app/api/faceless/channels/route.tsindex 84522075..f7e0c5c4 100644--- a/src/app/api/faceless/channels/route.ts+++ b/src/app/api/faceless/channels/route.ts@@ -1,6 +1,7 @@import { connection } from "next/server";import { z } from "zod";import { body, createChannel, EngineSchema, GenreSchema, handle, listChannels } from "@/server/faceless";+import { handler } from "@/server/access/route";const Create = z.object({idea: z.string().trim().min(1, "Describe the channel first").max(500, "Keep the channel idea under 500 characters"),@@ -11,15 +12,15 @@ const Create = z.object({});/** Your channels, newest first, with episode counts and the latest finished episode. */-export async function GET() {+export const GET = handler({ access: "signed-in" }, async () => {await connection();return handle(() => Response.json({ items: listChannels() }));-}+});/** Create a channel (its name is written for you when you don't give one). */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const input = await body(request, Create, "Describe the channel and pick a genre");return Response.json(await createChannel(input), { status: 201 });});-}+});diff --git a/src/app/api/faceless/episodes/[id]/[action]/route.ts b/src/app/api/faceless/episodes/[id]/[action]/route.tsindex 908c0468..11b4fd46 100644--- a/src/app/api/faceless/episodes/[id]/[action]/route.ts+++ b/src/app/api/faceless/episodes/[id]/[action]/route.ts@@ -1,4 +1,5 @@import { episodeView, handle, renderEpisode, retryEpisode, rewriteEpisode, undoChange, upscaleEpisode } from "@/server/faceless";+import { handler } from "@/server/access/route";const ACTIONS = {/** Render the reviewed script. */@@ -13,7 +14,7 @@ const ACTIONS = {upscale: upscaleEpisode,} as const;-export async function POST(_req: Request, ctx: RouteContext<"/api/faceless/episodes/[id]/[action]">) {+export const POST = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/faceless/episodes/[id]/[action]">) => {return handle(async () => {const { id, action } = await ctx.params;const run = ACTIONS[action as keyof typeof ACTIONS];@@ -21,4 +22,4 @@ export async function POST(_req: Request, ctx: RouteContext<"/api/faceless/episorun(id);return Response.json(episodeView(id));});-}+});diff --git a/src/app/api/faceless/episodes/[id]/change/route.ts b/src/app/api/faceless/episodes/[id]/change/route.tsindex 6a9307c4..95353dc9 100644--- a/src/app/api/faceless/episodes/[id]/change/route.ts+++ b/src/app/api/faceless/episodes/[id]/change/route.ts@@ -1,11 +1,12 @@import { applyChange, body, ChangeSchema, episodeView, handle, previewChange } from "@/server/faceless";+import { handler } from "@/server/access/route";/*** The timeline editor: `{ blocks, part, instruction | narration }` returns what the change re-runs and its* price; with `apply: true` it re-runs those steps (that block's picture or clips, the joins after it,* the mix and the subtitles, or the narration).*/-export async function POST(request: Request, ctx: RouteContext<"/api/faceless/episodes/[id]/change">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/faceless/episodes/[id]/change">) => {return handle(async () => {const { id } = await ctx.params;const c = await body(request, ChangeSchema, "Pick a scene and describe the change");@@ -13,4 +14,4 @@ export async function POST(request: Request, ctx: RouteContext<"/api/faceless/epapplyChange(id, c);return Response.json(episodeView(id), { status: 201 });});-}+});diff --git a/src/app/api/faceless/episodes/[id]/route.ts b/src/app/api/faceless/episodes/[id]/route.tsindex 3a075834..cde244b5 100644--- a/src/app/api/faceless/episodes/[id]/route.ts+++ b/src/app/api/faceless/episodes/[id]/route.ts@@ -1,6 +1,7 @@import { connection } from "next/server";import { z } from "zod";import { BlockSchema, body, deleteEpisode, episodeView, handle, SettingsSchema, updateEpisode } from "@/server/faceless";+import { handler } from "@/server/access/route";const Patch = z.object({title: z.string().max(120).optional(),@@ -10,29 +11,29 @@ const Patch = z.object({});/** The episode with every step's generation, its progress, spend and estimate. */-export async function GET(_req: Request, ctx: RouteContext<"/api/faceless/episodes/[id]">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/faceless/episodes/[id]">) => {await connection();return handle(async () => {const { id } = await ctx.params;return Response.json(episodeView(id));});-}+});/** Rename, like, or (before rendering) edit the script and settings. */-export async function PATCH(request: Request, ctx: RouteContext<"/api/faceless/episodes/[id]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/faceless/episodes/[id]">) => {return handle(async () => {const { id } = await ctx.params;const patch = await body(request, Patch, "Those changes aren't valid");updateEpisode(id, patch);return Response.json(episodeView(id));});-}+});/** Deletes the episode and stops what it still renders (its finished videos stay in the Library). */-export async function DELETE(_req: Request, ctx: RouteContext<"/api/faceless/episodes/[id]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/faceless/episodes/[id]">) => {return handle(async () => {const { id } = await ctx.params;await deleteEpisode(id);return new Response(null, { status: 204 });});-}+});diff --git a/src/app/api/faceless/episodes/route.ts b/src/app/api/faceless/episodes/route.tsindex 5120a4c0..b962bdb7 100644--- a/src/app/api/faceless/episodes/route.ts+++ b/src/app/api/faceless/episodes/route.ts@@ -3,6 +3,7 @@ import { z } from "zod";import { CF_LENGTH_VALUES } from "@/lib/catalog/content-factory";import { FACELESS_LENGTHS, MAX_SCRIPT, MAX_TOPIC } from "@/lib/catalog/faceless";import { body, createEpisode, FacelessError, getChannel, handle, listEpisodes, SettingsSchema } from "@/server/faceless";+import { handler } from "@/server/access/route";const Create = z.object({channelId: z.string().max(40),@@ -14,16 +15,16 @@ const Create = z.object({});/** Episodes, newest first (`?channel=` for one channel). */-export async function GET(request: Request) {+export const GET = handler({ access: "signed-in" }, async (request: Request) => {await connection();return handle(() => {const p = new URL(request.url).searchParams;return Response.json({ items: listEpisodes({ channelId: p.get("channel") ?? undefined, kind: "faceless", q: p.get("q") ?? undefined, limit: 200 }) });});-}+});/** A new episode: the script is written (or your pasted script split into scenes) in the background, then it waits for your review. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const input = await body(request, Create, "Pick a topic and the video settings");// A Content Factory channel (its settings carry a style brief) also makes 30-second episodes.@@ -31,4 +32,4 @@ export async function POST(request: Request) {if (!lengths.includes(input.settings.length)) throw new FacelessError("Choose one of the offered video lengths");return Response.json(createEpisode({ kind: "faceless", channelId: input.channelId, topic: input.topic, script: input.script, settings: input.settings, saveLook: input.saveLook }), { status: 201 });});-}+});diff --git a/src/app/api/faceless/estimate/route.ts b/src/app/api/faceless/estimate/route.tsindex d69688fa..0504a9ab 100644--- a/src/app/api/faceless/estimate/route.ts+++ b/src/app/api/faceless/estimate/route.ts@@ -1,5 +1,6 @@import { z } from "zod";import { BlockSchema, body, estimateEpisode, GenreSchema, handle, SettingsSchema } from "@/server/faceless";+import { handler } from "@/server/access/route";const Ask = z.object({kind: z.enum(["faceless", "explainer"]),@@ -9,6 +10,6 @@ const Ask = z.object({});/** What an episode would cost (by part), whether it runs as a demo, and what's in the way. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => Response.json(estimateEpisode(await body(request, Ask, "Those settings aren't valid"))));-}+});diff --git a/src/app/api/faceless/topics/route.ts b/src/app/api/faceless/topics/route.tsindex 0111dd4c..a3db904f 100644--- a/src/app/api/faceless/topics/route.ts+++ b/src/app/api/faceless/topics/route.ts@@ -1,5 +1,6 @@import { z } from "zod";import { body, EngineSchema, GenreSchema, getChannel, handle, suggestTopics } from "@/server/faceless";+import { handler } from "@/server/access/route";const Ask = z.object({idea: z.string().trim().min(1).max(500).optional(),@@ -11,7 +12,7 @@ const Ask = z.object({});/** 4–6 episode topics for a channel (the install's LLM, or templates offline). */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const q = await body(request, Ask, "Describe the channel first");const channel = q.channelId ? getChannel(q.channelId) : null;@@ -20,4 +21,4 @@ export async function POST(request: Request) {const reference = channel?.reference ? [channel.reference.title, channel.reference.author].filter(Boolean).join(" by ") || undefined : undefined;return Response.json(await suggestTopics({ idea, genre: q.genre ?? channel?.genre ?? "education", engine: q.engine, avoid: q.avoid, round: q.round, reference }));});-}+});diff --git a/src/app/api/faceless/voices/preview/route.ts b/src/app/api/faceless/voices/preview/route.tsindex e1a101e2..3672cf75 100644--- a/src/app/api/faceless/voices/preview/route.ts+++ b/src/app/api/faceless/voices/preview/route.ts@@ -1,12 +1,13 @@import { z } from "zod";import { body, handle, voicePreview } from "@/server/faceless";+import { handler } from "@/server/access/route";const Ask = z.object({ id: z.string().min(1).max(80) });/** A short sample of a premade narrator voice: one speech generation, reused once it exists. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const { id } = await body(request, Ask, "Pick a voice");return Response.json(voicePreview({ kind: "preset", id }));});-}+});diff --git a/src/app/api/files/[...path]/route.ts b/src/app/api/files/[...path]/route.tsindex f6a7e920..4700f911 100644--- a/src/app/api/files/[...path]/route.ts+++ b/src/app/api/files/[...path]/route.ts@@ -1,6 +1,7 @@import { fileResponse } from "@/server/file-response";+import { handler } from "@/server/access/route";-export async function GET(request: Request, ctx: RouteContext<"/api/files/[...path]">) {+export const GET = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/files/[...path]">) => {const { path: parts } = await ctx.params;let rel: string;try {@@ -9,4 +10,4 @@ export async function GET(request: Request, ctx: RouteContext<"/api/files/[...pareturn new Response("Bad path", { status: 400 });}return fileResponse(request, rel);-}+});diff --git a/src/app/api/folders/[id]/route.ts b/src/app/api/folders/[id]/route.tsindex a0f0d235..08018775 100644--- a/src/app/api/folders/[id]/route.ts+++ b/src/app/api/folders/[id]/route.ts@@ -1,6 +1,7 @@import { connection } from "next/server";import { z } from "zod";import { deleteFolder, getFolder, LibraryError, updateFolder } from "@/server/library";+import { handler } from "@/server/access/route";const Patch = z.object({name: z.string().trim().min(1).max(60).optional(),@@ -10,15 +11,15 @@ const Patch = z.object({pinned: z.boolean().optional(),});-export async function GET(_req: Request, ctx: RouteContext<"/api/folders/[id]">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/folders/[id]">) => {await connection();const { id } = await ctx.params;const f = getFolder(id);return f ? Response.json(f) : Response.json({ error: "Not found" }, { status: 404 });-}+});/** Rename, recolour, pin or move (refused into itself or one of its subfolders). */-export async function PATCH(request: Request, ctx: RouteContext<"/api/folders/[id]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/folders/[id]">) => {const { id } = await ctx.params;const parsed = Patch.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: parsed.error.issues.some((i) => i.path[0] === "parentId") ? "Pick a folder to move it into, or null for the top of the Library" : "Give the folder a name" }, { status: 400 });@@ -28,10 +29,10 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/folders/[i} catch (e) {return Response.json({ error: (e as Error).message }, { status: e instanceof LibraryError ? e.status : 409 });}-}+});/** Delete the folder; its results and subfolders move up to its parent (the library root at the top). */-export async function DELETE(_req: Request, ctx: RouteContext<"/api/folders/[id]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/folders/[id]">) => {const { id } = await ctx.params;return deleteFolder(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });-}+});diff --git a/src/app/api/folders/[id]/zip/route.ts b/src/app/api/folders/[id]/zip/route.tsindex 03bae3e7..61ffebdf 100644--- a/src/app/api/folders/[id]/zip/route.ts+++ b/src/app/api/folders/[id]/zip/route.ts@@ -1,13 +1,14 @@import { connection } from "next/server";import { folderZipEntries, LibraryError, ZIP_MAX_BYTES } from "@/server/library";import { zipSize, zipStream } from "@/server/zip";+import { handler } from "@/server/access/route";/*** Download a folder as one zip: its finished results, and each subfolder's in a folder of its own.* `?check=1` answers {files, size} (or the error) without the zip, so the page can explain a refusal.* Helper steps are left out, as on the folder's page, unless `?steps=1` (Show steps is on).*/-export async function GET(request: Request, ctx: RouteContext<"/api/folders/[id]/zip">) {+export const GET = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/folders/[id]/zip">) => {await connection();const { id } = await ctx.params;const sp = new URL(request.url).searchParams;@@ -31,4 +32,4 @@ export async function GET(request: Request, ctx: RouteContext<"/api/folders/[id]"Cache-Control": "no-store",},});-}+});diff --git a/src/app/api/folders/route.ts b/src/app/api/folders/route.tsindex 02c01a80..038059d7 100644--- a/src/app/api/folders/route.ts+++ b/src/app/api/folders/route.ts@@ -1,18 +1,19 @@import { connection } from "next/server";import { z } from "zod";import { createFolder, LibraryError, listFolders } from "@/server/library";+import { handler } from "@/server/access/route";/** `parentId`: a folder's id, or null (or left out) for the library root; "" is refused, not stored as a parent nothing has. */const Body = z.object({ name: z.string().trim().min(1).max(60), color: z.string().max(20).optional(), parentId: z.string().min(1).max(40).nullable().optional() });/** Every folder, flat: each has its parentId (null at the library root) and pinnedAt. */-export async function GET() {+export const GET = handler({ access: "signed-in" }, async () => {await connection();return Response.json({ items: listFolders() });-}+});/** A new folder; `parentId` makes it a subfolder. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: parsed.error.issues.some((i) => i.path[0] === "parentId") ? "Pick a folder to put it in, or null for the top of the Library" : "Give the folder a name" }, { status: 400 });try {@@ -20,4 +21,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: e instanceof LibraryError ? e.status : 409 });}-}+});diff --git a/src/app/api/generations/[id]/cancel/route.ts b/src/app/api/generations/[id]/cancel/route.tsindex e8618143..f4aeff35 100644--- a/src/app/api/generations/[id]/cancel/route.ts+++ b/src/app/api/generations/[id]/cancel/route.ts@@ -1,7 +1,8 @@import { cancelGeneration, getGeneration } from "@/server/generations";+import { handler } from "@/server/access/route";-export async function POST(_req: Request, ctx: RouteContext<"/api/generations/[id]/cancel">) {+export const POST = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/generations/[id]/cancel">) => {const { id } = await ctx.params;await cancelGeneration(id);return Response.json(getGeneration(id));-}+});diff --git a/src/app/api/generations/[id]/finish/route.ts b/src/app/api/generations/[id]/finish/route.tsindex 6aecfc51..5e314168 100644--- a/src/app/api/generations/[id]/finish/route.ts+++ b/src/app/api/generations/[id]/finish/route.ts@@ -1,4 +1,5 @@import { FinishError, finishOutput } from "@/server/generations";+import { handler } from "@/server/access/route";const MAX_BYTES = 64 * 1024 * 1024;const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);@@ -7,7 +8,7 @@ const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);* Fuobe Soul's finished picture (the look's grade and overlay, made in the browser): it replaces the raw output,* which stays as meta.original. Form fields: file (PNG), index (the output's place).*/-export async function POST(request: Request, ctx: RouteContext<"/api/generations/[id]/finish">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/generations/[id]/finish">) => {const { id } = await ctx.params;const form = await request.formData().catch(() => null);const file = form?.get("file");@@ -22,4 +23,4 @@ export async function POST(request: Request, ctx: RouteContext<"/api/generationsif (e instanceof FinishError) return Response.json({ error: e.message }, { status: e.status });throw e;}-}+});diff --git a/src/app/api/generations/[id]/route.ts b/src/app/api/generations/[id]/route.tsindex e27de293..ad896871 100644--- a/src/app/api/generations/[id]/route.ts+++ b/src/app/api/generations/[id]/route.ts@@ -2,16 +2,17 @@ import { connection } from "next/server";import { getGeneration, setFavorite } from "@/server/generations";import { deleteForever, setPinned, setReview, trashGenerations } from "@/server/library";import { isReviewStatus } from "@/lib/library";+import { handler } from "@/server/access/route";-export async function GET(_req: Request, ctx: RouteContext<"/api/generations/[id]">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/generations/[id]">) => {await connection();const { id } = await ctx.params;const g = getGeneration(id);return g ? Response.json(g) : Response.json({ error: "Not found" }, { status: 404 });-}+});/** Favorite, pin (`pinned`) or set the review status (`review`, null clears it). */-export async function PATCH(request: Request, ctx: RouteContext<"/api/generations/[id]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/generations/[id]">) => {const { id } = await ctx.params;const body = (await request.json().catch(() => ({}))) as { favorite?: boolean; pinned?: boolean; review?: unknown };if (body.review !== undefined && body.review !== null && !isReviewStatus(body.review)) return Response.json({ error: "Pick a review status" }, { status: 400 });@@ -20,12 +21,12 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/generationif (body.review !== undefined) setReview([id], body.review);const g = getGeneration(id);return g ? Response.json(g) : Response.json({ error: "Not found" }, { status: 404 });-}+});/** Move to the Trash (restore with POST /api/generations/bulk {action: "restore"}); `?forever=1` deletes for good. */-export async function DELETE(request: Request, ctx: RouteContext<"/api/generations/[id]">) {+export const DELETE = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/generations/[id]">) => {const { id } = await ctx.params;if (new URL(request.url).searchParams.get("forever") === "1") await deleteForever([id]);else trashGenerations([id]);return new Response(null, { status: 204 });-}+});diff --git a/src/app/api/generations/bulk/route.ts b/src/app/api/generations/bulk/route.tsindex 1478d64c..8a27c9c3 100644--- a/src/app/api/generations/bulk/route.ts+++ b/src/app/api/generations/bulk/route.ts@@ -1,5 +1,6 @@import { z } from "zod";import { deleteForever, moveToFolder, restoreGenerations, setFavorites, setPinned, setReview, trashGenerations } from "@/server/library";+import { handler } from "@/server/access/route";const Body = z.object({action: z.enum(["trash", "restore", "delete", "favorite", "unfavorite", "move", "pin", "unpin", "review"]),@@ -11,7 +12,7 @@ const Body = z.object({});/** One action on many generations: Trash / Restore / Delete forever / (un)favorite / move to a folder / (un)pin / review status. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Pick something first" }, { status: 400 });const { action, ids, folderId, review } = parsed.data;@@ -34,4 +35,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: 422 });}-}+});diff --git a/src/app/api/generations/facets/route.ts b/src/app/api/generations/facets/route.tsindex 3d81521f..771e66fb 100644--- a/src/app/api/generations/facets/route.ts+++ b/src/app/api/generations/facets/route.ts@@ -1,8 +1,9 @@import { connection } from "next/server";import { libraryFacets } from "@/server/library";+import { handler } from "@/server/access/route";/** Counts for the Library's filter menus: models used, kinds, favorites, failed, pinned, review statuses, helper steps, Trash. `steps=1` counts the steps in. */-export async function GET(request: Request) {+export const GET = handler({ access: "signed-in" }, async (request: Request) => {await connection();return Response.json(libraryFacets({ steps: new URL(request.url).searchParams.get("steps") === "1" }));-}+});diff --git a/src/app/api/generations/local/route.ts b/src/app/api/generations/local/route.tsindex 4387fa3e..80bc018e 100644--- a/src/app/api/generations/local/route.ts+++ b/src/app/api/generations/local/route.ts@@ -1,5 +1,6 @@import { z } from "zod";import { recordLocalGeneration } from "@/server/generations";+import { handler } from "@/server/access/route";const Body = z.object({feature: z.string().min(1).max(80),@@ -12,7 +13,7 @@ const Body = z.object({});/** Record a result rendered in the browser (e.g. a colour grade) so it shows up in the library. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Invalid result" }, { status: 400 });try {@@ -20,4 +21,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: 422 });}-}+});diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.tsindex f6da8919..ccc2f417 100644--- a/src/app/api/generations/route.ts+++ b/src/app/api/generations/route.ts@@ -3,6 +3,7 @@ import { OPERATION_LABELS } from "@/lib/catalog/types";import { createGenerations, listGenerations, outputKind, previewGeneration } from "@/server/generations";import { ensureTrashPurge, listOptionsFrom } from "@/server/library";import { GenerationRequestSchema } from "@/server/request-schema";+import { handler } from "@/server/access/route";/*** List generations, newest first. Filters: kind / kinds, features (`x*` = prefix), models, statuses,@@ -10,14 +11,14 @@ import { GenerationRequestSchema } from "@/server/request-schema";* paging with before=<createdAt>:<id> of the last row (<deletedAt>:<id> in the Trash; a bare* timestamp still works) and limit (≤ 200).*/-export async function GET(request: Request) {+export const GET = handler({ access: "signed-in" }, async (request: Request) => {await connection();ensureTrashPurge();return Response.json({ items: listGenerations(listOptionsFrom(new URL(request.url).searchParams)) });-}+});/** Start a generation; `?preview=1` only says what it would run as (model, operation, jobs, outputs, cost). */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = GenerationRequestSchema.safeParse(await request.json().catch(() => null));if (!parsed.success) {return Response.json({ error: parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ") }, { status: 400 });@@ -37,4 +38,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: 422 });}-}+});diff --git a/src/app/api/generations/stream/route.ts b/src/app/api/generations/stream/route.tsindex ae67c849..f27fab4c 100644--- a/src/app/api/generations/stream/route.ts+++ b/src/app/api/generations/stream/route.ts@@ -1,6 +1,7 @@import { connection } from "next/server";import { ensureRunner } from "@/server/generations";import { generationEventStream } from "@/server/live";+import { handler } from "@/server/access/route";/*** Live generation updates (server-sent events), behind the same sign-in as the REST API (proxy):@@ -9,9 +10,9 @@ import { generationEventStream } from "@/server/live";* : ping every 15 s* Sent on every insert or update of a generation row (status, progress, outputs…).*/-export async function GET(request: Request) {+export const GET = handler({ access: "signed-in" }, async (request: Request) => {// Never prerendered, and the runner that produces the updates is running.await connection();ensureRunner();return generationEventStream(request.signal);-}+});diff --git a/src/app/api/generations/trash/route.ts b/src/app/api/generations/trash/route.tsindex 13f95375..16b0400d 100644--- a/src/app/api/generations/trash/route.ts+++ b/src/app/api/generations/trash/route.ts@@ -1,15 +1,16 @@import { connection } from "next/server";import { listGenerations } from "@/server/generations";import { emptyTrash, ensureTrashPurge, listOptionsFrom } from "@/server/library";+import { handler } from "@/server/access/route";/** The Trash, most recently deleted first (paging: before=<deletedAt>:<id> of the last row). Same filters as GET /api/generations. */-export async function GET(request: Request) {+export const GET = handler({ access: "signed-in" }, async (request: Request) => {await connection();ensureTrashPurge();return Response.json({ items: listGenerations({ ...listOptionsFrom(new URL(request.url).searchParams), trashed: true }) });-}+});/** Empty the Trash: everything in it is deleted for good. */-export async function DELETE() {+export const DELETE = handler({ access: "signed-in" }, async () => {return Response.json({ count: await emptyTrash() });-}+});diff --git a/src/app/api/generations/zip/route.ts b/src/app/api/generations/zip/route.tsindex 85e9b67d..eb58343f 100644--- a/src/app/api/generations/zip/route.ts+++ b/src/app/api/generations/zip/route.ts@@ -1,9 +1,10 @@import { connection } from "next/server";import { ZIP_MAX_BYTES, zipEntries } from "@/server/library";import { zipSize, zipStream } from "@/server/zip";+import { handler } from "@/server/access/route";/** Download the finished outputs of several generations as one zip: GET ?ids=a,b,c (up to 500). */-export async function GET(request: Request) {+export const GET = handler({ access: "signed-in" }, async (request: Request) => {await connection();const ids = (new URL(request.url).searchParams.get("ids") ?? "").split(",").map((s) => s.trim()).filter(Boolean);if (!ids.length) return Response.json({ error: "Pick something to download" }, { status: 400 });@@ -20,4 +21,4 @@ export async function GET(request: Request) {"Cache-Control": "no-store",},});-}+});diff --git a/src/app/api/genjutsu/describe/route.ts b/src/app/api/genjutsu/describe/route.tsindex 9586b694..5cdbc61c 100644--- a/src/app/api/genjutsu/describe/route.ts+++ b/src/app/api/genjutsu/describe/route.ts@@ -1,10 +1,11 @@import { describeCharacter, DescribeSchema } from "@/server/genjutsu";import { body, handle } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";/** "Describe my character": the engine's text model writes what the character looks like from their picture. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const input = await body(request, DescribeSchema, "Add a picture of your character first");return Response.json(await describeCharacter(input));});-}+});diff --git a/src/app/api/genjutsu/estimate/route.ts b/src/app/api/genjutsu/estimate/route.tsindex fdab6c41..4b101538 100644--- a/src/app/api/genjutsu/estimate/route.ts+++ b/src/app/api/genjutsu/estimate/route.ts@@ -1,10 +1,11 @@import { estimateGenjutsu, GenjutsuEstimateSchema } from "@/server/genjutsu";import { body, handle } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";/** The price, the model, the pieces and the notes for the current settings, before anything runs. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const input = await body(request, GenjutsuEstimateSchema, "Add a clip and pick a mode");return Response.json(await estimateGenjutsu(input));});-}+});diff --git a/src/app/api/genjutsu/route.ts b/src/app/api/genjutsu/route.tsindex 1c79d6f7..810c6a8a 100644--- a/src/app/api/genjutsu/route.ts+++ b/src/app/api/genjutsu/route.ts@@ -1,12 +1,13 @@import { createGenjutsu, GenjutsuBodySchema } from "@/server/genjutsu";import { body, handle, once } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";/** Run a Genjutsu: the pieces or windows are made, joined, and the clip's sound put back. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const input = await body(request, GenjutsuBodySchema, "Add a clip, pick a mode and add your references");// A repeated requestId (a second click on Generate) gets the run the first one started.const { final, items } = await once("genjutsu", input.requestId, () => createGenjutsu(input));return Response.json({ final, items }, { status: 201 });});-}+});diff --git a/src/app/api/genjutsu/transcribe/route.ts b/src/app/api/genjutsu/transcribe/route.tsindex 544b963e..7893e22f 100644--- a/src/app/api/genjutsu/transcribe/route.ts+++ b/src/app/api/genjutsu/transcribe/route.ts@@ -1,10 +1,11 @@import { transcribeClip, TranscribeSchema } from "@/server/genjutsu";import { body, handle } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";/** The clip's words for Character swap's "What's said": one transcription the page picks the part's lines from. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const input = await body(request, TranscribeSchema, "Add a clip first");return Response.json(transcribeClip(input), { status: 201 });});-}+});diff --git a/src/app/api/identity/[...all]/route.ts b/src/app/api/identity/[...all]/route.tsindex b853e61f..bc714082 100644--- a/src/app/api/identity/[...all]/route.ts+++ b/src/app/api/identity/[...all]/route.ts@@ -1,5 +1,6 @@import { getAuth } from "@/server/identity/auth";import { signInRequired } from "@/server/mode";+import { handler } from "@/server/access/route";/*** Better Auth's router (docs/research/accounts-8.md §7.1), mounted at /api/identity. Only allowlisted endpoints@@ -12,5 +13,6 @@ async function handle(request: Request): Promise<Response> {return getAuth().handler(request);}-export const GET = handle;-export const POST = handle;+// Public: signing in is how someone becomes an actor. Better Auth answers for itself (its own allowlist and checks).+export const GET = handler({ access: "public" }, handle);+export const POST = handler({ access: "public" }, handle);diff --git a/src/app/api/influencer/estimate/route.ts b/src/app/api/influencer/estimate/route.tsindex 09326e16..cf897b63 100644--- a/src/app/api/influencer/estimate/route.ts+++ b/src/app/api/influencer/estimate/route.ts@@ -1,11 +1,12 @@import { POST as influencer } from "../route";+import { handler } from "@/server/access/route";/*** The price of an AI Influencer run without starting it: the same body as POST /api/influencer?preview=1, at the* `<route>/estimate` path the evaluation harness prices studio routes at.*/-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const url = new URL(request.url.replace(/\/estimate(?=\/?(\?|$))/, ""));url.searchParams.set("preview", "1");return influencer(new Request(url, { method: "POST", headers: request.headers, body: await request.text() }));-}+});diff --git a/src/app/api/influencer/route.ts b/src/app/api/influencer/route.tsindex 1ce51dc8..4e32f99b 100644--- a/src/app/api/influencer/route.ts+++ b/src/app/api/influencer/route.ts@@ -1,6 +1,7 @@import { z } from "zod";import { MAX_CLOTHING, MAX_DIRECTION } from "@/lib/influencer";import { createInfluencer, previewInfluencer, type InfluencerBody } from "@/server/influencer";+import { handler } from "@/server/access/route";const File = z.string().startsWith("/api/files/").max(500);@@ -30,7 +31,7 @@ function bodyError(issues: z.core.$ZodIssue[]): string {* Seedream 5.0 Pro when asked), the Soul Cast sheet workflow on the open engine, each followed by Qwen-Image-Edit 2511* for a face, a reference or clothing. `?preview=1` (or POST /api/influencer/estimate) prices it instead.*/-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: bodyError(parsed.error.issues) }, { status: 400 });const body = parsed.data as InfluencerBody;@@ -40,4 +41,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: 422 });}-}+});diff --git a/src/app/api/katana/[id]/retry/route.ts b/src/app/api/katana/[id]/retry/route.tsindex 57aad703..18a44076 100644--- a/src/app/api/katana/[id]/retry/route.ts+++ b/src/app/api/katana/[id]/retry/route.ts@@ -1,7 +1,8 @@import { getKatana, rerunKatana, retryKatana } from "@/server/katana";+import { handler } from "@/server/access/route";/** Retry the failed steps of a run (and the ones after them); `?all=1` starts the same run again from scratch. */-export async function POST(request: Request, ctx: RouteContext<"/api/katana/[id]/retry">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/katana/[id]/retry">) => {const { id } = await ctx.params;if (!getKatana(id)) return Response.json({ error: "Not found" }, { status: 404 });try {@@ -10,4 +11,4 @@ export async function POST(request: Request, ctx: RouteContext<"/api/katana/[id]} catch (e) {return Response.json({ error: (e as Error).message }, { status: 422 });}-}+});diff --git a/src/app/api/katana/[id]/route.ts b/src/app/api/katana/[id]/route.tsindex 88fad2dc..f492efdc 100644--- a/src/app/api/katana/[id]/route.ts+++ b/src/app/api/katana/[id]/route.ts@@ -1,15 +1,16 @@import { connection } from "next/server";import { deleteKatana, getKatana } from "@/server/katana";+import { handler } from "@/server/access/route";-export async function GET(_req: Request, ctx: RouteContext<"/api/katana/[id]">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/katana/[id]">) => {await connection();const { id } = await ctx.params;const job = getKatana(id);return job ? Response.json(job) : Response.json({ error: "Not found" }, { status: 404 });-}+});/** Forget the run: steps still running are stopped first (the clips it made stay in the Library). */-export async function DELETE(_req: Request, ctx: RouteContext<"/api/katana/[id]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/katana/[id]">) => {const { id } = await ctx.params;return deleteKatana(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });-}+});diff --git a/src/app/api/katana/route.ts b/src/app/api/katana/route.tsindex ddf27759..26ec5889 100644--- a/src/app/api/katana/route.ts+++ b/src/app/api/katana/route.ts@@ -1,15 +1,16 @@import { connection } from "next/server";import { createKatana, KatanaBody, listKatana, previewKatana } from "@/server/katana";+import { handler } from "@/server/access/route";/** Recent Katana runs with the state of every step. */-export async function GET(request: Request) {+export const GET = handler({ access: "signed-in" }, async (request: Request) => {await connection();const limit = Number(new URL(request.url).searchParams.get("limit") ?? 20);return Response.json({ items: listKatana(Number.isFinite(limit) ? limit : 20) });-}+});/** Start a run; `?preview=1` only plans and prices it (segments, steps, cost). */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = KatanaBody.safeParse(await request.json().catch(() => null));if (!parsed.success) {const path = String(parsed.error.issues[0]?.path[0] ?? "");@@ -22,4 +23,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: 422 });}-}+});diff --git a/src/app/api/layers/[id]/jobs/[jobId]/route.ts b/src/app/api/layers/[id]/jobs/[jobId]/route.tsindex 807c428f..31b2b02a 100644--- a/src/app/api/layers/[id]/jobs/[jobId]/route.ts+++ b/src/app/api/layers/[id]/jobs/[jobId]/route.ts@@ -1,20 +1,21 @@import { z } from "zod";import { endJob } from "@/server/layers";+import { handler } from "@/server/access/route";const Patch = z.object({ state: z.enum(["dismissed", "applied"]) });/** Dismiss a finished job (a failure you've read, a text detection you've used). */-export async function PATCH(request: Request, ctx: RouteContext<"/api/layers/[id]/jobs/[jobId]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/layers/[id]/jobs/[jobId]">) => {const { id, jobId } = await ctx.params;const parsed = Patch.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Invalid change" }, { status: 400 });const job = await endJob(id, jobId, { state: parsed.data.state });return job ? Response.json(job) : Response.json({ error: "Not found" }, { status: 404 });-}+});/** Cancel a job that's still running (its generations are canceled too). */-export async function DELETE(_req: Request, ctx: RouteContext<"/api/layers/[id]/jobs/[jobId]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/layers/[id]/jobs/[jobId]">) => {const { id, jobId } = await ctx.params;const job = await endJob(id, jobId, { cancel: true });return job ? Response.json(job) : Response.json({ error: "Not found" }, { status: 404 });-}+});diff --git a/src/app/api/layers/[id]/jobs/route.ts b/src/app/api/layers/[id]/jobs/route.tsindex 5bb43b4b..7d900298 100644--- a/src/app/api/layers/[id]/jobs/route.ts+++ b/src/app/api/layers/[id]/jobs/route.ts@@ -1,11 +1,12 @@import { JobInputSchema, LayersError, startJob } from "@/server/layers";+import { handler } from "@/server/access/route";/*** Start a tool (decompose, separate a layer, edit text, remove background, a regional edit, upscale,* relight, angles, expand, generate a layer): its generations run on the chosen engine; the editor* applies the result when it lands. 422 with the reason when it can't start.*/-export async function POST(request: Request, ctx: RouteContext<"/api/layers/[id]/jobs">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/layers/[id]/jobs">) => {const { id } = await ctx.params;const parsed = JobInputSchema.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Could not start the tool: the request was incomplete" }, { status: 400 });@@ -14,4 +15,4 @@ export async function POST(request: Request, ctx: RouteContext<"/api/layers/[id]} catch (e) {return Response.json({ error: (e as Error).message }, { status: e instanceof LayersError ? e.status : 422 });}-}+});diff --git a/src/app/api/layers/[id]/route.ts b/src/app/api/layers/[id]/route.tsindex 8a9007ee..77c19ed3 100644--- a/src/app/api/layers/[id]/route.ts+++ b/src/app/api/layers/[id]/route.ts@@ -1,6 +1,7 @@import { connection } from "next/server";import { z } from "zod";import { deleteProject, LayersError, parseDoc, projectView, updateProject } from "@/server/layers";+import { handler } from "@/server/access/route";const Patch = z.object({name: z.string().max(200).optional(),@@ -13,14 +14,14 @@ const Patch = z.object({});/** The project, its versions, the head document and its tools' jobs (with their results). */-export async function GET(_req: Request, ctx: RouteContext<"/api/layers/[id]">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/layers/[id]">) => {await connection();const { id } = await ctx.params;const view = projectView(id);return view ? Response.json(view) : Response.json({ error: "Not found" }, { status: 404 });-}+});-export async function PATCH(request: Request, ctx: RouteContext<"/api/layers/[id]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/layers/[id]">) => {const { id } = await ctx.params;const parsed = Patch.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Invalid change" }, { status: 400 });@@ -32,10 +33,10 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/layers/[id} catch (e) {return Response.json({ error: (e as Error).message }, { status: e instanceof LayersError ? e.status : 422 });}-}+});/** Delete the project and all of its versions; its images stay in the library. */-export async function DELETE(_req: Request, ctx: RouteContext<"/api/layers/[id]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/layers/[id]">) => {const { id } = await ctx.params;return deleteProject(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });-}+});diff --git a/src/app/api/layers/[id]/versions/route.ts b/src/app/api/layers/[id]/versions/route.tsindex 2824f60f..8ce535ea 100644--- a/src/app/api/layers/[id]/versions/route.ts+++ b/src/app/api/layers/[id]/versions/route.ts@@ -1,5 +1,6 @@import { z } from "zod";import { createVersion, LayersError, parseDoc } from "@/server/layers";+import { handler } from "@/server/access/route";const Body = z.object({doc: z.unknown().optional(),@@ -11,7 +12,7 @@ const Body = z.object({});/** Save a version (a tool's result, or a restored older version); it becomes the head. */-export async function POST(request: Request, ctx: RouteContext<"/api/layers/[id]/versions">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/layers/[id]/versions">) => {const { id } = await ctx.params;const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Invalid version" }, { status: 400 });@@ -22,4 +23,4 @@ export async function POST(request: Request, ctx: RouteContext<"/api/layers/[id]} catch (e) {return Response.json({ error: (e as Error).message }, { status: e instanceof LayersError ? e.status : 422 });}-}+});diff --git a/src/app/api/layers/renders/route.ts b/src/app/api/layers/renders/route.tsindex 84fa6f31..8e5526ae 100644--- a/src/app/api/layers/renders/route.ts+++ b/src/app/api/layers/renders/route.ts@@ -1,4 +1,5 @@import { saveFile } from "@/server/storage";+import { handler } from "@/server/access/route";const MAX_BYTES = 64 * 1024 * 1024;const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);@@ -8,7 +9,7 @@ const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);* composite, a mask, a merged region, a colour grade). Stored like an upload but as "derived", so it* stays out of the Library's Uploads and the pickers; projects that use it keep it (ASSET_REFS).*/-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const form = await request.formData().catch(() => null);const file = form?.get("file");if (!(file instanceof File)) return Response.json({ error: "No file" }, { status: 400 });@@ -17,4 +18,4 @@ export async function POST(request: Request) {if (file.type !== "image/png" || !data.subarray(0, 8).equals(PNG_MAGIC)) return Response.json({ error: "Renders are PNG images" }, { status: 415 });const asset = saveFile({ data, contentType: "image/png", name: file.name.slice(0, 120), source: "derived" });return Response.json(asset, { status: 201 });-}+});diff --git a/src/app/api/layers/route.ts b/src/app/api/layers/route.tsindex ce00b3f4..5ea7e9a9 100644--- a/src/app/api/layers/route.ts+++ b/src/app/api/layers/route.ts@@ -1,6 +1,7 @@import { connection } from "next/server";import { z } from "zod";import { createProject, FileUrl, LayersError, listProjects } from "@/server/layers";+import { handler } from "@/server/access/route";const Body = z.object({/** The image to open: an upload or a result (an /api/files/ URL). */@@ -14,13 +15,13 @@ const Body = z.object({});/** Your Layers projects, most recently edited first. */-export async function GET() {+export const GET = handler({ access: "signed-in" }, async () => {await connection();return Response.json({ items: listProjects() });-}+});/** Open an image in Layers: a new project with the image as its only layer. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Only images can be edited here. Pick an image or upload one." }, { status: 400 });try {@@ -29,4 +30,4 @@ export async function POST(request: Request) {const status = e instanceof LayersError ? e.status : 422;return Response.json({ error: (e as Error).message }, { status });}-}+});diff --git a/src/app/api/loras/route.ts b/src/app/api/loras/route.tsindex 57754a4e..9a64a345 100644--- a/src/app/api/loras/route.ts+++ b/src/app/api/loras/route.ts@@ -3,12 +3,13 @@ import { LORA_LIBRARY, LORA_LIBRARY_AS_OF } from "@/lib/catalog/lora-library.genimport { licenceLine } from "@/lib/catalog/loras";import { downloadToComfy, filesInLoraFolder, listLoraCopies, LoraError } from "@/server/loras";import { getSetting } from "@/server/settings";+import { handler } from "@/server/access/route";/*** The LoRA library for Settings → LoRAs: every researched LoRA with its licence, where it downloads from,* whether it is in the LoRA folder and where Fuobe mirrored it. Keys are never in the answer.*/-export async function GET() {+export const GET = handler({ access: "signed-in" }, async () => {await connection();const folder = getSetting("comfyLorasDir");// A folder setting that can't be read (a file, no permission) is said, not a 500.@@ -37,10 +38,10 @@ export async function GET() {mirrored: mirrored.get(e.file) ?? [],})),});-}+});/** Download one library LoRA into the LoRA folder now (`{ file }`), instead of before the first run that needs it. */-export async function POST(request: Request) {+export const POST = handler({ access: "perm:install.settings" }, async (request: Request) => {const body = (await request.json().catch(() => ({}))) as { file?: unknown };if (typeof body.file !== "string" || !body.file) return Response.json({ error: "Say which LoRA to download" }, { status: 400 });try {@@ -49,4 +50,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: e instanceof LoraError ? 422 : 500 });}-}+});diff --git a/src/app/api/marketing/click-to-ad/estimate/route.ts b/src/app/api/marketing/click-to-ad/estimate/route.tsindex f62da1b4..18300da8 100644--- a/src/app/api/marketing/click-to-ad/estimate/route.ts+++ b/src/app/api/marketing/click-to-ad/estimate/route.ts@@ -1,6 +1,7 @@import { ClickToAdBody, estimateClickToAd, readBody } from "@/server/marketing";+import { handler } from "@/server/access/route";-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const body = await readBody(request, ClickToAdBody, "Select a product or enter a product URL");if (body instanceof Response) return body;try {@@ -8,4 +9,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ costUsd: null, demo: false, steps: [], notes: [], runs: 0, blocker: (e as Error).message });}-}+});diff --git a/src/app/api/marketing/click-to-ad/route.ts b/src/app/api/marketing/click-to-ad/route.tsindex 59106e0d..97a6c005 100644--- a/src/app/api/marketing/click-to-ad/route.ts+++ b/src/app/api/marketing/click-to-ad/route.ts@@ -1,7 +1,8 @@import { ClickToAdBody, failure, readBody, runClickToAd } from "@/server/marketing";+import { handler } from "@/server/access/route";/** Click to Ad: a 9:16 voiced ad with captions from a product kit and a style. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const body = await readBody(request, ClickToAdBody, "Select a product or enter a product URL");if (body instanceof Response) return body;try {@@ -9,4 +10,4 @@ export async function POST(request: Request) {} catch (e) {return failure(e);}-}+});diff --git a/src/app/api/marketing/estimate/route.ts b/src/app/api/marketing/estimate/route.tsindex eb50509b..4b16a5ac 100644--- a/src/app/api/marketing/estimate/route.ts+++ b/src/app/api/marketing/estimate/route.ts@@ -1,7 +1,8 @@import { estimateMarketing, MarketingBody, readBody } from "@/server/marketing";+import { handler } from "@/server/access/route";/** Price and check a Marketing Studio run before it starts; what's missing comes back as `blocker`. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const body = await readBody(request, MarketingBody);if (body instanceof Response) return body;try {@@ -9,4 +10,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ costUsd: null, demo: false, steps: [], notes: [], runs: 0, blocker: (e as Error).message });}-}+});diff --git a/src/app/api/marketing/runs/[id]/again/route.ts b/src/app/api/marketing/runs/[id]/again/route.tsindex d2966ea7..d8916118 100644--- a/src/app/api/marketing/runs/[id]/again/route.ts+++ b/src/app/api/marketing/runs/[id]/again/route.ts@@ -1,11 +1,12 @@import { failure, rerun } from "@/server/marketing";+import { handler } from "@/server/access/route";/** Run again: the same template, product and settings as a new run. */-export async function POST(_req: Request, ctx: RouteContext<"/api/marketing/runs/[id]/again">) {+export const POST = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/marketing/runs/[id]/again">) => {const { id } = await ctx.params;try {return Response.json({ runs: await rerun(id) }, { status: 201 });} catch (e) {return (e as Error).message === "Not found" ? Response.json({ error: "Not found" }, { status: 404 }) : failure(e);}-}+});diff --git a/src/app/api/marketing/runs/[id]/compose/route.ts b/src/app/api/marketing/runs/[id]/compose/route.tsindex 252a7c5c..c10ffa2e 100644--- a/src/app/api/marketing/runs/[id]/compose/route.ts+++ b/src/app/api/marketing/runs/[id]/compose/route.ts@@ -1,5 +1,6 @@import { z } from "zod";import { failure, readBody, saveRunComposite } from "@/server/marketing";+import { handler } from "@/server/access/route";const Body = z.object({url: z.string().startsWith("/api/files/"),@@ -12,7 +13,7 @@ const Body = z.object({});/** Save a result with its words set in the browser (an uploaded PNG: open models, Fuobe Marketing Image) to the Library. */-export async function POST(request: Request, ctx: RouteContext<"/api/marketing/runs/[id]/compose">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/marketing/runs/[id]/compose">) => {const { id } = await ctx.params;const body = await readBody(request, Body, "Upload the image first");if (body instanceof Response) return body;@@ -21,4 +22,4 @@ export async function POST(request: Request, ctx: RouteContext<"/api/marketing/r} catch (e) {return (e as Error).message === "Not found" ? Response.json({ error: "Not found" }, { status: 404 }) : failure(e);}-}+});diff --git a/src/app/api/marketing/runs/[id]/route.ts b/src/app/api/marketing/runs/[id]/route.tsindex bac88f6b..bbacef14 100644--- a/src/app/api/marketing/runs/[id]/route.ts+++ b/src/app/api/marketing/runs/[id]/route.ts@@ -1,15 +1,16 @@import { connection } from "next/server";import { deleteRun, getRun } from "@/server/marketing";+import { handler } from "@/server/access/route";-export async function GET(_req: Request, ctx: RouteContext<"/api/marketing/runs/[id]">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/marketing/runs/[id]">) => {await connection();const { id } = await ctx.params;const run = getRun(id);return run ? Response.json(run) : Response.json({ error: "Not found" }, { status: 404 });-}+});/** Forget a run (its results stay in the Library). */-export async function DELETE(_req: Request, ctx: RouteContext<"/api/marketing/runs/[id]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/marketing/runs/[id]">) => {const { id } = await ctx.params;return deleteRun(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });-}+});diff --git a/src/app/api/marketing/runs/route.ts b/src/app/api/marketing/runs/route.tsindex 22f5d092..ee891e0d 100644--- a/src/app/api/marketing/runs/route.ts+++ b/src/app/api/marketing/runs/route.ts@@ -1,20 +1,21 @@import { connection } from "next/server";import { z } from "zod";import { failure, listRuns, MarketingBody, readBody, runMarketing } from "@/server/marketing";+import { handler } from "@/server/access/route";const Feature = z.enum(["marketing", "click-to-ad", "ad-multiplier"]);/** Runs of one flow (`?feature=marketing|click-to-ad|ad-multiplier`), newest first, with every step's generation. */-export async function GET(request: Request) {+export const GET = handler({ access: "signed-in" }, async (request: Request) => {await connection();const q = new URL(request.url).searchParams;const feature = Feature.safeParse(q.get("feature") ?? "marketing");if (!feature.success) return Response.json({ error: "Unknown feature" }, { status: 400 });return Response.json({ items: listRuns(feature.data, Number(q.get("limit")) || 30) });-}+});/** Marketing Studio: make a template (or a free prompt) with a product, avatar, hook and brand kit. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const body = await readBody(request, MarketingBody);if (body instanceof Response) return body;try {@@ -22,4 +23,4 @@ export async function POST(request: Request) {} catch (e) {return failure(e);}-}+});diff --git a/src/app/api/marketing/script/route.ts b/src/app/api/marketing/script/route.tsindex 031195ef..83fd0bc8 100644--- a/src/app/api/marketing/script/route.ts+++ b/src/app/api/marketing/script/route.ts@@ -1,5 +1,6 @@import { z } from "zod";import { clickToAdScript, failure, readBody } from "@/server/marketing";+import { handler } from "@/server/access/route";const Body = z.object({engine: z.enum(["cloud", "open"]),@@ -10,7 +11,7 @@ const Body = z.object({});/** Write a Click to Ad voiceover script to review (Auto, or with custom instructions). */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const body = await readBody(request, Body, "Pick a product and a style");if (body instanceof Response) return body;try {@@ -18,4 +19,4 @@ export async function POST(request: Request) {} catch (e) {return failure(e);}-}+});diff --git a/src/app/api/mcp/route.ts b/src/app/api/mcp/route.tsindex 08ce06cf..7c4557a5 100644--- a/src/app/api/mcp/route.ts+++ b/src/app/api/mcp/route.ts@@ -1,10 +1,12 @@import { handleMcp } from "@/server/mcp";+import { currentActor } from "@/server/access/actor";+import { handler } from "@/server/access/route";/*** MCP endpoint (streamable HTTP, stateless, JSON responses). Point an MCP client at* http(s)://<host>/api/mcp; with a password set, send `Authorization: Bearer fuobe_…`.*/-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {// Browsers send Origin: a web page on another site must not reach this server through the// user's browser (DNS rebinding, required by the MCP spec). Native clients send none.const origin = request.headers.get("origin");@@ -14,15 +16,16 @@ export async function POST(request: Request) {const body = await request.json().catch(() => undefined);if (body === undefined) return Response.json({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }, { status: 400 });if (Array.isArray(body)) return Response.json({ jsonrpc: "2.0", id: null, error: { code: -32600, message: "Batches aren't supported" } }, { status: 400 });- const res = await handleMcp(body);+ // Tools run as the token's (or session's) person.+ const res = await handleMcp(body, currentActor());return res ? Response.json(res) : new Response(null, { status: 202 });-}+});/** No server-initiated stream: this server only answers requests. */-export function GET() {+export const GET = handler({ access: "signed-in" }, () => {return new Response("Method Not Allowed", { status: 405, headers: { Allow: "POST" } });-}+});-export function DELETE() {+export const DELETE = handler({ access: "signed-in" }, () => {return new Response("Method Not Allowed", { status: 405, headers: { Allow: "POST" } });-}+});diff --git a/src/app/api/media/probe/route.ts b/src/app/api/media/probe/route.tsindex 7899918b..fdddc8f4 100644--- a/src/app/api/media/probe/route.ts+++ b/src/app/api/media/probe/route.ts@@ -1,14 +1,15 @@import { z } from "zod";import { probeSource } from "@/server/shorts";import { body, handle } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";/*** An uploaded clip's length, size, frame rate and whether it has sound, from its header (MP4 / MOV, WebM).* The composer prices clip-length tools with it and says what comes out (Upscale hub: "24 → 60 fps").*/-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const { url } = await body(request, z.object({ url: z.string().startsWith("/api/files/").max(500) }), "Upload the clip first");return Response.json(await probeSource(url));});-}+});diff --git a/src/app/api/mixed-media/estimate/route.ts b/src/app/api/mixed-media/estimate/route.tsindex 3f2dc7f1..c4d55c13 100644--- a/src/app/api/mixed-media/estimate/route.ts+++ b/src/app/api/mixed-media/estimate/route.ts@@ -1,10 +1,11 @@import { estimateMixed } from "@/server/mixed-media";import { MixedEstimateSchema, body, handle } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";/** Frames, cost of the render and of a preview frame, and notes for the current settings. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const input = await body(request, MixedEstimateSchema, "Pick a preset and the part of the clip to use");return Response.json(await estimateMixed(input));});-}+});diff --git a/src/app/api/mixed-media/preview/route.ts b/src/app/api/mixed-media/preview/route.tsindex 39a4381d..1e06d2e6 100644--- a/src/app/api/mixed-media/preview/route.ts+++ b/src/app/api/mixed-media/preview/route.ts@@ -1,10 +1,11 @@import { createMixedPreview } from "@/server/mixed-media";import { MixedBodySchema, body, handle, once } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";/** Generate one frame with the current settings before the full video. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const input = await body(request, MixedBodySchema, "Pick a preset and upload a clip first");return Response.json(await once("mixed-preview", input.requestId, () => createMixedPreview(input)), { status: 201 });});-}+});diff --git a/src/app/api/mixed-media/progress/route.ts b/src/app/api/mixed-media/progress/route.tsindex 4a11a714..4a7734e4 100644--- a/src/app/api/mixed-media/progress/route.ts+++ b/src/app/api/mixed-media/progress/route.ts@@ -1,12 +1,13 @@import { framesProgress } from "@/server/mixed-media";import { handle } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";/** How far a per-frame render's frame edits are (?id=<the render's finished video>): counts, and the first frame that failed. */-export async function GET(request: Request) {+export const GET = handler({ access: "signed-in" }, async (request: Request) => {return handle(() => {const id = new URL(request.url).searchParams.get("id")?.trim() ?? "";if (!id || id.length > 64) return Response.json({ error: "Which render?" }, { status: 400 });const progress = framesProgress(id);return progress ? Response.json(progress) : Response.json({ error: "This render no longer exists" }, { status: 404 });});-}+});diff --git a/src/app/api/mixed-media/retry/route.ts b/src/app/api/mixed-media/retry/route.tsindex 329d66e5..4d0da24a 100644--- a/src/app/api/mixed-media/retry/route.ts+++ b/src/app/api/mixed-media/retry/route.ts@@ -1,11 +1,12 @@import { z } from "zod";import { retryMixed } from "@/server/mixed-media";import { body, handle, once } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";/** Run a render again with the same settings ("Try again" in History); a repeated requestId gets the first answer. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const input = await body(request, z.object({ id: z.string().min(1).max(64), requestId: z.string().trim().min(8).max(64).optional() }), "Pick a render to try again");return Response.json(await once("mixed-retry", input.requestId, () => retryMixed(input.id)), { status: 201 });});-}+});diff --git a/src/app/api/mixed-media/route.ts b/src/app/api/mixed-media/route.tsindex 1b02db46..c1e6e071 100644--- a/src/app/api/mixed-media/route.ts+++ b/src/app/api/mixed-media/route.ts@@ -1,12 +1,13 @@import { createMixed } from "@/server/mixed-media";import { MixedBodySchema, body, handle, once } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";/** Render a Mixed Media video (open: per frame; cloud: cut → frames or restyle → original sound). `items` leaves out the per-frame edits (`frames` counts them). */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const input = await body(request, MixedBodySchema, "Pick a preset, upload a clip and choose up to 10 seconds");// A repeated requestId (a second click on Generate video) gets the render the first one started.const { final, items, frames } = await once("mixed-render", input.requestId, () => createMixed(input));return Response.json({ final, items, frames }, { status: 201 });});-}+});diff --git a/src/app/api/models/route.ts b/src/app/api/models/route.tsindex 06f9b58d..a512bc7b 100644--- a/src/app/api/models/route.ts+++ b/src/app/api/models/route.ts@@ -9,6 +9,7 @@ import { provider } from "@/server/providers";import { llmBackends } from "@/server/providers/llm";import { offeredDefault, offeredModels } from "@/server/model-access";import { engineMode, getSetting } from "@/server/settings";+import { handler } from "@/server/access/route";/** A provider for one of its routes is set up. */const connected = (m: ModelDef) => m.routes.some((r) => (r.provider === "llm" ? llmBackends(r).length > 0 : provider(r.provider).isConfigured()));@@ -50,7 +51,7 @@ const DEFAULTS: Record<string, { cloud?: string; open?: string }> = {* goes today (`runs`, which follows Settings → Demo mode). Models switched off in Settings → Models & licences* are left out, and a default that is off gives way to the next model that is on.*/-export async function GET(request: Request) {+export const GET = handler({ access: "signed-in" }, async (request: Request) => {await connection();const p = new URL(request.url).searchParams;const kind = p.get("kind") || undefined;@@ -75,4 +76,4 @@ export async function GET(request: Request) {);const demoMode = getSetting("demoMode");return Response.json({ engineMode: mode, demoMode, defaults, items: list.map((m) => ({ ...toModelInfo(m), connected: connected(m), runs: runsAs(m, demoMode) })) });-}+});diff --git a/src/app/api/moodboards/[id]/retry/route.ts b/src/app/api/moodboards/[id]/retry/route.tsindex 414670be..14e9254a 100644--- a/src/app/api/moodboards/[id]/retry/route.ts+++ b/src/app/api/moodboards/[id]/retry/route.ts@@ -1,10 +1,11 @@import { z } from "zod";import { retryMoodboard } from "@/server/moodboards";+import { handler } from "@/server/access/route";const Body = z.object({ engine: z.enum(["cloud", "open"]).optional() });/** Run a board's cover job again (after a failure, or on the other engine). */-export async function POST(request: Request, ctx: RouteContext<"/api/moodboards/[id]/retry">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/moodboards/[id]/retry">) => {const { id } = await ctx.params;const parsed = Body.safeParse(await request.json().catch(() => ({})));try {@@ -12,4 +13,4 @@ export async function POST(request: Request, ctx: RouteContext<"/api/moodboards/} catch (e) {return Response.json({ error: (e as Error).message }, { status: /not found/i.test((e as Error).message) ? 404 : 409 });}-}+});diff --git a/src/app/api/moodboards/[id]/route.ts b/src/app/api/moodboards/[id]/route.tsindex a20a8950..566517aa 100644--- a/src/app/api/moodboards/[id]/route.ts+++ b/src/app/api/moodboards/[id]/route.ts@@ -1,17 +1,18 @@import { connection } from "next/server";import { z } from "zod";import { deleteMoodboard, getMoodboard, renameMoodboard } from "@/server/moodboards";+import { handler } from "@/server/access/route";const Patch = z.object({ name: z.string().max(200) });-export async function GET(_req: Request, ctx: RouteContext<"/api/moodboards/[id]">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/moodboards/[id]">) => {await connection();const { id } = await ctx.params;const m = getMoodboard(id);return m ? Response.json(m) : Response.json({ error: "Not found" }, { status: 404 });-}+});-export async function PATCH(request: Request, ctx: RouteContext<"/api/moodboards/[id]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/moodboards/[id]">) => {const { id } = await ctx.params;const parsed = Patch.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Please enter a moodboard name" }, { status: 400 });@@ -20,9 +21,9 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/moodboards} catch (e) {return Response.json({ error: (e as Error).message }, { status: /not found/i.test((e as Error).message) ? 404 : 400 });}-}+});-export async function DELETE(_req: Request, ctx: RouteContext<"/api/moodboards/[id]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/moodboards/[id]">) => {const { id } = await ctx.params;return deleteMoodboard(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });-}+});diff --git a/src/app/api/moodboards/[id]/train/route.ts b/src/app/api/moodboards/[id]/train/route.tsindex 12e4da7e..67ca8a92 100644--- a/src/app/api/moodboards/[id]/train/route.ts+++ b/src/app/api/moodboards/[id]/train/route.ts@@ -1,17 +1,18 @@import { connection } from "next/server";import { z } from "zod";import { moodboardTrainingTargets, trainMoodboard } from "@/server/moodboards";+import { handler } from "@/server/access/route";/** The style trainings a board can run (each with its price, what stops it and whether it would be a demo). */-export async function GET() {+export const GET = handler({ access: "signed-in" }, async () => {await connection();return Response.json({ targets: moodboardTrainingTargets() });-}+});const Body = z.object({ target: z.string().min(1).optional() }).nullable();/** Train the board as a Fuobe look: a Z-Image Turbo style LoRA on your GPU (AI-Toolkit) or in the cloud (fal). */-export async function POST(request: Request, ctx: RouteContext<"/api/moodboards/[id]/train">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/moodboards/[id]/train">) => {const { id } = await ctx.params;const parsed = Body.safeParse(await request.json().catch(() => null));try {@@ -19,4 +20,4 @@ export async function POST(request: Request, ctx: RouteContext<"/api/moodboards/} catch (e) {return Response.json({ error: (e as Error).message }, { status: /not found/i.test((e as Error).message) ? 404 : 409 });}-}+});diff --git a/src/app/api/moodboards/route.ts b/src/app/api/moodboards/route.tsindex f9d03769..132b1739 100644--- a/src/app/api/moodboards/route.ts+++ b/src/app/api/moodboards/route.ts@@ -1,6 +1,7 @@import { connection } from "next/server";import { z } from "zod";import { createMoodboard, curatedMoodboards, listMoodboards } from "@/server/moodboards";+import { handler } from "@/server/access/route";const Body = z.object({name: z.string().max(200),@@ -10,12 +11,12 @@ 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 const GET = handler({ access: "signed-in" }, async () => {await connection();return Response.json({ items: listMoodboards(), curated: curatedMoodboards() });-}+});-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Upload at least 5 photos to continue." }, { status: 400 });try {@@ -23,4 +24,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: 400 });}-}+});diff --git a/src/app/api/palettes/[id]/route.ts b/src/app/api/palettes/[id]/route.tsindex 141b1b03..b14b2f05 100644--- a/src/app/api/palettes/[id]/route.ts+++ b/src/app/api/palettes/[id]/route.ts@@ -1,9 +1,10 @@import { z } from "zod";import { deletePalette, renamePalette } from "@/server/palettes";+import { handler } from "@/server/access/route";const Patch = z.object({ name: z.string().trim().min(1).max(60) });-export async function PATCH(request: Request, ctx: RouteContext<"/api/palettes/[id]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/palettes/[id]">) => {const { id } = await ctx.params;const parsed = Patch.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Give the palette a name" }, { status: 400 });@@ -12,13 +13,13 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/palettes/[} catch (e) {return Response.json({ error: (e as Error).message }, { status: /not found/i.test((e as Error).message) ? 404 : 400 });}-}+});-export async function DELETE(_req: Request, ctx: RouteContext<"/api/palettes/[id]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/palettes/[id]">) => {const { id } = await ctx.params;try {return deletePalette(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });} catch (e) {return Response.json({ error: (e as Error).message }, { status: 400 });}-}+});diff --git a/src/app/api/palettes/lock/route.ts b/src/app/api/palettes/lock/route.tsindex 53931544..d0e97a3b 100644--- a/src/app/api/palettes/lock/route.ts+++ b/src/app/api/palettes/lock/route.ts@@ -1,5 +1,6 @@import { z } from "zod";import { createLockedRun, SignatureSchema } from "@/server/palettes";+import { handler } from "@/server/access/route";const Hex = z.string().regex(/^#?[0-9a-fA-F]{6}$/);@@ -33,7 +34,7 @@ const RequestSchema = z.object({const Body = z.object({ request: RequestSchema, colors: z.array(Hex).min(1).max(16), strength: z.number().min(0).max(1).optional() });/** Make the images, then recolour each one to the palette (open engine: a chained palette-transfer step). */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ") }, { status: 400 });try {@@ -42,4 +43,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: 422 });}-}+});diff --git a/src/app/api/palettes/route.ts b/src/app/api/palettes/route.tsindex d647574e..2f1ea391 100644--- a/src/app/api/palettes/route.ts+++ b/src/app/api/palettes/route.ts@@ -1,6 +1,7 @@import { connection } from "next/server";import { z } from "zod";import { createPalette, listPalettes, signatureCaps } from "@/server/palettes";+import { handler } from "@/server/access/route";const Body = z.object({name: z.string().trim().min(1).max(60),@@ -11,12 +12,12 @@ 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 const GET = handler({ access: "signed-in" }, async () => {await connection();return Response.json({ items: listPalettes(), caps: signatureCaps() });-}+});-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Give the palette a name and 1–12 colours" }, { status: 400 });try {@@ -24,4 +25,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: 400 });}-}+});diff --git a/src/app/api/photodump/character/route.ts b/src/app/api/photodump/character/route.tsindex 339a659b..12c5b0db 100644--- a/src/app/api/photodump/character/route.ts+++ b/src/app/api/photodump/character/route.ts@@ -1,5 +1,6 @@import { z } from "zod";import { createSheet, previewSheet, type SheetRun } from "@/server/photodump";+import { handler } from "@/server/access/route";const Engine = z.enum(["cloud", "open"]);@@ -32,7 +33,7 @@ function bodyError(mode: unknown, issues: z.core.$ZodIssue[]): string {* Character Sheet: a turnaround sheet from 1–5 reference photos, from a Soul Cast build, or from a* description (the AI Influencer app). `?preview=1` prices it instead.*/-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const body = (await request.json().catch(() => null)) as { mode?: unknown } | null;const parsed = Body.safeParse(body);if (!parsed.success) return Response.json({ error: bodyError(body?.mode, parsed.error.issues) }, { status: 400 });@@ -43,4 +44,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: 422 });}-}+});diff --git a/src/app/api/photodump/fashion/route.ts b/src/app/api/photodump/fashion/route.tsindex ebeebd7d..7476e448 100644--- a/src/app/api/photodump/fashion/route.ts+++ b/src/app/api/photodump/fashion/route.ts@@ -1,5 +1,6 @@import { z } from "zod";import { createFashion, previewFashion, type FashionRun } from "@/server/photodump";+import { handler } from "@/server/access/route";const File = z.string().startsWith("/api/files/");const Engine = z.enum(["cloud", "open"]);@@ -14,7 +15,7 @@ const Body = z.discriminatedUnion("step", [* Fashion Factory steps: 4 base shots of the character in the template's set, the outfit (try-on),* and the photoset (one photo per template shot). `?preview=1` prices a step instead.*/-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Template required" }, { status: 400 });const input = parsed.data as FashionRun;@@ -24,4 +25,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: 422 });}-}+});diff --git a/src/app/api/photodump/packs/[id]/route.ts b/src/app/api/photodump/packs/[id]/route.tsindex 3df0c708..0f768fbf 100644--- a/src/app/api/photodump/packs/[id]/route.ts+++ b/src/app/api/photodump/packs/[id]/route.ts@@ -1,6 +1,7 @@import { deleteUserPack } from "@/server/photodump";+import { handler } from "@/server/access/route";-export async function DELETE(_req: Request, ctx: RouteContext<"/api/photodump/packs/[id]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/photodump/packs/[id]">) => {const { id } = await ctx.params;return deleteUserPack(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });-}+});diff --git a/src/app/api/photodump/packs/route.ts b/src/app/api/photodump/packs/route.tsindex b37fcde7..d5a5f1f8 100644--- a/src/app/api/photodump/packs/route.ts+++ b/src/app/api/photodump/packs/route.ts@@ -1,16 +1,17 @@import { connection } from "next/server";import { z } from "zod";import { createUserPack, listUserPacks } from "@/server/photodump";+import { handler } from "@/server/access/route";const Body = z.object({ name: z.string().max(200), refs: z.array(z.string().startsWith("/api/files/")).max(40) });-export async function GET() {+export const GET = handler({ access: "signed-in" }, async () => {await connection();return Response.json({ packs: listUserPacks() });-}+});/** Create a pack from up to 15 reference photos: each becomes one photo of the dump. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Upload your reference set up to 15 photos" }, { status: 400 });try {@@ -18,4 +19,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: 400 });}-}+});diff --git a/src/app/api/photodump/retry/route.ts b/src/app/api/photodump/retry/route.tsindex a375ecac..262789f9 100644--- a/src/app/api/photodump/retry/route.ts+++ b/src/app/api/photodump/retry/route.ts@@ -1,5 +1,6 @@import { z } from "zod";import { retryPhoto } from "@/server/photodump";+import { handler } from "@/server/access/route";const Body = z.object({ id: z.string().min(1).max(40) });@@ -7,7 +8,7 @@ const Body = z.object({ id: z.string().min(1).max(40) });* Retry a failed or canceled photo of a Photodump / Fashion Factory / Character Sheet run: the same* request in the same batch, replacing the failed one (it goes to the Trash).*/-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Pick the photo to retry" }, { status: 400 });try {@@ -15,4 +16,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: 422 });}-}+});diff --git a/src/app/api/photodump/route.ts b/src/app/api/photodump/route.tsindex 5ca3d5a9..7b8386d1 100644--- a/src/app/api/photodump/route.ts+++ b/src/app/api/photodump/route.ts@@ -1,6 +1,7 @@import { connection } from "next/server";import { z } from "zod";import { createPhotodump, listUserPacks, previewPhotodump } from "@/server/photodump";+import { handler } from "@/server/access/route";const Body = z.object({@@ -14,16 +15,16 @@ const Body = z.refine((b) => !!b.elementId || !!b.selfie, { message: "Pick a character or add a selfie" });/** Your own packs (the built-in ones ship with the page). */-export async function GET() {+export const GET = handler({ access: "signed-in" }, async () => {await connection();return Response.json({ packs: listUserPacks() });-}+});/*** Generate a photodump: one photo per pack shot, as one batch. `?preview=1` prices it instead* (model, photo count, cost, demo, notes, or the error that would stop it).*/-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: parsed.error.issues[0]?.message ?? "Pick a pack" }, { status: 400 });if (new URL(request.url).searchParams.get("preview")) return Response.json(previewPhotodump(parsed.data));@@ -32,4 +33,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: 422 });}-}+});diff --git a/src/app/api/products/[id]/route.ts b/src/app/api/products/[id]/route.tsindex a6764d03..9b97b738 100644--- a/src/app/api/products/[id]/route.ts+++ b/src/app/api/products/[id]/route.ts@@ -1,15 +1,16 @@import { connection } from "next/server";import { deleteProduct, getProduct, ProductFields, updateProduct } from "@/server/brand";import { failure, readBody } from "@/server/marketing";+import { handler } from "@/server/access/route";-export async function GET(_req: Request, ctx: RouteContext<"/api/products/[id]">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/products/[id]">) => {await connection();const { id } = await ctx.params;const p = getProduct(id);return p ? Response.json(p) : Response.json({ error: "Not found" }, { status: 404 });-}+});-export async function PATCH(request: Request, ctx: RouteContext<"/api/products/[id]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/products/[id]">) => {const { id } = await ctx.params;const body = await readBody(request, ProductFields.partial(), "Check the product");if (body instanceof Response) return body;@@ -19,9 +20,9 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/products/[} catch (e) {return failure(e);}-}+});-export async function DELETE(_req: Request, ctx: RouteContext<"/api/products/[id]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/products/[id]">) => {const { id } = await ctx.params;return deleteProduct(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });-}+});diff --git a/src/app/api/products/read/route.ts b/src/app/api/products/read/route.tsindex daceff9f..22431d20 100644--- a/src/app/api/products/read/route.ts+++ b/src/app/api/products/read/route.ts@@ -1,6 +1,7 @@import { z } from "zod";import { readProductLink } from "@/server/brand";import { failure, readBody } from "@/server/marketing";+import { handler } from "@/server/access/route";const Body = z.object({url: z.string().trim().min(1).max(600),@@ -12,7 +13,7 @@ const Body = z.object({});/** Add product(s) from a link: names, descriptions, prices and pictures read from the page. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const body = await readBody(request, Body, "Use a valid product link.");if (body instanceof Response) return body;try {@@ -21,4 +22,4 @@ export async function POST(request: Request) {} catch (e) {return failure(e);}-}+});diff --git a/src/app/api/products/route.ts b/src/app/api/products/route.tsindex b21c518e..db9011c4 100644--- a/src/app/api/products/route.ts+++ b/src/app/api/products/route.ts@@ -2,16 +2,17 @@ import { connection } from "next/server";import { z } from "zod";import { createProduct, listProducts, ProductFields } from "@/server/brand";import { failure, readBody } from "@/server/marketing";+import { handler } from "@/server/access/route";/** Products: all, a brand's (`?brand=<id>`) or the unassigned ones (`?brand=none`). */-export async function GET(request: Request) {+export const GET = handler({ access: "signed-in" }, async (request: Request) => {await connection();const brand = new URL(request.url).searchParams.get("brand");return Response.json({ items: listProducts(brand === null ? undefined : brand === "none" ? null : brand) });-}+});/** Add a product by hand. A name the brand already has answers 409 unless `force` is set ("Create anyway"). */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const body = await readBody(request, ProductFields.extend({ force: z.boolean().optional() }), "Check the product");if (body instanceof Response) return body;const { force, ...input } = body;@@ -20,4 +21,4 @@ export async function POST(request: Request) {} catch (e) {return failure(e);}-}+});diff --git a/src/app/api/providers/test/route.ts b/src/app/api/providers/test/route.tsindex 59206797..9c86d925 100644--- a/src/app/api/providers/test/route.ts+++ b/src/app/api/providers/test/route.ts@@ -3,6 +3,7 @@ import { testCivitaiKey } from "@/server/loras";import { testAiToolkit } from "@/server/training";import { PROVIDERS } from "@/server/providers";import { validateSetting, withCandidates, type SettingName } from "@/server/settings";+import { handler } from "@/server/access/route";/*** Test a provider's connection. With `value` (the provider's main setting) or `values` (by setting@@ -11,7 +12,7 @@ import { validateSetting, withCandidates, type SettingName } from "@/server/sett* unsaved one), so a provider that reaches several servers tests that one: the Anthropic key is* checked with Anthropic even when text steps run on Ollama. Nothing is stored here.*/-export async function POST(request: Request) {+export const POST = handler({ access: "perm:install.settings" }, async (request: Request) => {const body = (await request.json().catch(() => ({}))) as { provider?: unknown; value?: unknown; values?: unknown; field?: unknown };const provider = body.provider;// The civitai key isn't a model provider's (it downloads LoRAs), nor is AI-Toolkit (it trains them).@@ -36,4 +37,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ ok: false, detail: `Couldn't run the test: ${(e as Error).message}` });}-}+});diff --git a/src/app/api/remove-object/estimate/route.ts b/src/app/api/remove-object/estimate/route.tsindex 57e638d1..e181d598 100644--- a/src/app/api/remove-object/estimate/route.ts+++ b/src/app/api/remove-object/estimate/route.ts@@ -1,10 +1,11 @@import { estimateRemoval, RemovalEstimateSchema } from "@/server/remove-object";import { body, handle } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";/** The price, the pieces and the notes for the current settings, before anything runs. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const input = await body(request, RemovalEstimateSchema, "Add a clip and pick how to point at what goes");return Response.json(await estimateRemoval(input));});-}+});diff --git a/src/app/api/remove-object/preview/route.ts b/src/app/api/remove-object/preview/route.tsindex d85dc9b0..2ac3bb4b 100644--- a/src/app/api/remove-object/preview/route.ts+++ b/src/app/api/remove-object/preview/route.ts@@ -1,11 +1,12 @@import { createRemovalPreview, RemovalBodySchema } from "@/server/remove-object";import { body, handle, once } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";/** A mask preview of the first seconds: what the engine would remove (SAM 3.1). */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const input = await body(request, RemovalBodySchema, "Add a clip and say, click or paint what to remove");const preview = await once("remove-object-preview", input.requestId, () => createRemovalPreview(input));return Response.json(preview, { status: 201 });});-}+});diff --git a/src/app/api/remove-object/route.ts b/src/app/api/remove-object/route.tsindex d172ad22..509d116e 100644--- a/src/app/api/remove-object/route.ts+++ b/src/app/api/remove-object/route.ts@@ -1,12 +1,13 @@import { createRemoval, RemovalBodySchema } from "@/server/remove-object";import { body, handle, once } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";/** Remove an object from a clip: the pieces or windows are erased, joined, and the clip's sound put back. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const input = await body(request, RemovalBodySchema, "Add a clip and say, click or paint what to remove");// A repeated requestId (a second click on Remove) gets the run the first one started.const { final, items } = await once("remove-object", input.requestId, () => createRemoval(input));return Response.json({ final, items }, { status: 201 });});-}+});diff --git a/src/app/api/search-index/route.ts b/src/app/api/search-index/route.tsindex 85bab563..d212ebb8 100644--- a/src/app/api/search-index/route.ts+++ b/src/app/api/search-index/route.ts@@ -1,9 +1,10 @@import { paletteIndex } from "@/lib/palette-index";+import { handler } from "@/server/access/route";/*** The ⌘K palette's catalog: apps, camera motions, effects and models, slim (names, categories, where* each opens). Static, so it's prerendered at build time; the palette loads it once, on first open.*/-export async function GET() {+export const GET = handler({ access: "signed-in" }, async () => {return Response.json(paletteIndex());-}+});diff --git a/src/app/api/settings/models/route.ts b/src/app/api/settings/models/route.tsindex cdf1ee3c..2f6663a4 100644--- a/src/app/api/settings/models/route.ts+++ b/src/app/api/settings/models/route.ts@@ -2,16 +2,17 @@ import { connection } from "next/server";import { LICENCE_CLASSES } from "@/lib/licences";import type { AccessChange } from "@/lib/model-access";import { accessList, changeAccess, knownSwitch } from "@/server/model-access";+import { handler } from "@/server/access/route";/*** Settings → Models & licences: every model, LoRA and node pack with its licence and its switch, and the* switches per licence class and provider (GET); flip switches (PUT `{ changes: AccessChange[] }`, answered with* the list as it is now). Everything is on until an admin turns it off.*/-export async function GET() {+export const GET = handler({ access: "signed-in" }, async () => {await connection();return Response.json(accessList());-}+});const KINDS = new Set(["model", "class", "provider", "pack", "lora"]);const NOUN = { model: "Model", provider: "Provider", pack: "Node pack", lora: "LoRA" } as const;@@ -34,7 +35,7 @@ function readChange(v: unknown): AccessChange | string {return { kind, id, on: c.on };}-export async function PUT(request: Request) {+export const PUT = handler({ access: "perm:install.settings" }, async (request: Request) => {const body = (await request.json().catch(() => ({}))) as { changes?: unknown };if (!Array.isArray(body.changes) || !body.changes.length) return Response.json({ error: "Send { changes: [...] }" }, { status: 400 });const changes = body.changes.map(readChange);@@ -42,4 +43,4 @@ export async function PUT(request: Request) {if (bad) return Response.json({ error: bad }, { status: 400 });changeAccess(changes as AccessChange[]);return Response.json(accessList());-}+});diff --git a/src/app/api/settings/route.ts b/src/app/api/settings/route.tsindex bf5ff8f5..dc85093a 100644--- a/src/app/api/settings/route.ts+++ b/src/app/api/settings/route.ts@@ -1,12 +1,13 @@import { connection } from "next/server";import { publicSettings, setSetting, SETTINGS, validateSetting, type SettingName } from "@/server/settings";+import { handler } from "@/server/access/route";-export async function GET() {+export const GET = handler({ access: "signed-in" }, async () => {await connection();return Response.json({ settings: publicSettings() });-}+});-export async function PUT(request: Request) {+export const PUT = handler({ access: "perm:install.settings" }, async (request: Request) => {const body = (await request.json().catch(() => ({}))) as Record<string, unknown>;const entries = Object.entries(body).filter(([name, value]) => name in SETTINGS && typeof value === "string") as [SettingName, string][];try {@@ -16,4 +17,4 @@ export async function PUT(request: Request) {}for (const [name, value] of entries) setSetting(name, value.trim());return Response.json({ settings: publicSettings() });-}+});diff --git a/src/app/api/shares/[id]/route.ts b/src/app/api/shares/[id]/route.tsindex 9b34879e..7190966a 100644--- a/src/app/api/shares/[id]/route.ts+++ b/src/app/api/shares/[id]/route.ts@@ -2,6 +2,7 @@ import { connection } from "next/server";import { z } from "zod";import { MAX_EXPIRY_DAYS } from "@/lib/share";import { getShare, revokeShare, ShareError, updateShare } from "@/server/shares";+import { handler } from "@/server/access/route";const Patch = z.object({title: z.string().max(300).optional(),@@ -15,15 +16,15 @@ const Patch = z.object({newLink: z.literal(true).optional(),});-export async function GET(_req: Request, ctx: RouteContext<"/api/shares/[id]">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/shares/[id]">) => {await connection();const { id } = await ctx.params;const s = getShare(id);return s ? Response.json(s) : Response.json({ error: "Not found" }, { status: 404 });-}+});/** Change a link: its words, prompts on or off, a new expiry from now, or a new token. */-export async function PATCH(request: Request, ctx: RouteContext<"/api/shares/[id]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/shares/[id]">) => {const { id } = await ctx.params;const parsed = Patch.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Invalid change" }, { status: 400 });@@ -34,10 +35,10 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/shares/[idif (e instanceof ShareError) return Response.json({ error: e.message }, { status: e.status });throw e;}-}+});/** Revoke: the link stops working at once. */-export async function DELETE(_req: Request, ctx: RouteContext<"/api/shares/[id]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/shares/[id]">) => {const { id } = await ctx.params;return revokeShare(id) ? new Response(null, { status: 204 }) : Response.json({ error: "That link doesn't exist anymore" }, { status: 404 });-}+});diff --git a/src/app/api/shares/route.ts b/src/app/api/shares/route.tsindex 89ddc55e..5257e4ff 100644--- a/src/app/api/shares/route.ts+++ b/src/app/api/shares/route.ts@@ -3,6 +3,7 @@ import { z } from "zod";import { MAX_EXPIRY_DAYS, SHARE_KINDS } from "@/lib/share";import { authEnabled } from "@/server/auth";import { createShare, listShares, MAX_PUBLISH_ITEMS, ShareError } from "@/server/shares";+import { handler } from "@/server/access/route";const Body = z.object({kind: z.enum(SHARE_KINDS as [string, ...string[]]),@@ -18,16 +19,16 @@ const Body = z.object({});/** Every share link (Library → Shared), and whether sign-in is on (the share dialog warns when it isn't). */-export async function GET() {+export const GET = handler({ access: "signed-in" }, async () => {await connection();return Response.json({ items: listShares(), signIn: authEnabled() });-}+});/*** A new read-only link to a result, a folder, a Cinema project, or (kind "publish") a page of picked* results. The answer carries the token once; only its hash is stored.*/-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: parsed.error.issues.some((i) => i.path[0] === "items") ? `Pick up to ${MAX_PUBLISH_ITEMS} results` : "That isn't something Fuobe can share" }, { status: 400 });try {@@ -37,4 +38,4 @@ export async function POST(request: Request) {if (e instanceof ShareError) return Response.json({ error: e.message }, { status: e.status });throw e;}-}+});diff --git a/src/app/api/shorts/estimate/route.ts b/src/app/api/shorts/estimate/route.tsindex e9937d52..595cac19 100644--- a/src/app/api/shorts/estimate/route.ts+++ b/src/app/api/shorts/estimate/route.ts@@ -1,10 +1,11 @@import { estimateShorts } from "@/server/shorts";import { ShortsEstimateSchema, body, handle } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";/** What a session would cost (or that it runs as a demo), how many segments it makes, and notes. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const input = await body(request, ShortsEstimateSchema, "Pick a preset and the part of the clip to restyle");return Response.json(await estimateShorts(input));});-}+});diff --git a/src/app/api/shorts/presets/[id]/route.ts b/src/app/api/shorts/presets/[id]/route.tsindex 374cde8b..acc46cac 100644--- a/src/app/api/shorts/presets/[id]/route.ts+++ b/src/app/api/shorts/presets/[id]/route.ts@@ -1,18 +1,19 @@import { deleteCustomPreset, ShortsError, updateCustomPreset } from "@/server/shorts";import { PresetPatchSchema, body, handle } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";-export async function PATCH(request: Request, ctx: RouteContext<"/api/shorts/presets/[id]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/shorts/presets/[id]">) => {return handle(async () => {const { id } = await ctx.params;const patch = await body(request, PresetPatchSchema, "Those preset settings aren't valid");return Response.json(updateCustomPreset(id, patch));});-}+});-export async function DELETE(_req: Request, ctx: RouteContext<"/api/shorts/presets/[id]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/shorts/presets/[id]">) => {return handle(async () => {const { id } = await ctx.params;if (!deleteCustomPreset(id)) throw new ShortsError("This preset no longer exists", 404);return new Response(null, { status: 204 });});-}+});diff --git a/src/app/api/shorts/presets/route.ts b/src/app/api/shorts/presets/route.tsindex 1461326f..76c53578 100644--- a/src/app/api/shorts/presets/route.ts+++ b/src/app/api/shorts/presets/route.ts@@ -1,17 +1,18 @@import { connection } from "next/server";import { createCustomPreset, listCustomPresets } from "@/server/shorts";import { PresetBodySchema, body, handle } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";/** The user's own presets ("Created by you"). */-export async function GET() {+export const GET = handler({ access: "signed-in" }, async () => {await connection();return handle(() => Response.json({ items: listCustomPresets() }));-}+});/** Create a preset from up to 10 reference images. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const input = await body(request, PresetBodySchema, "Add 1–10 reference images");return Response.json(createCustomPreset(input), { status: 201 });});-}+});diff --git a/src/app/api/shorts/probe/route.ts b/src/app/api/shorts/probe/route.tsindex 2c10ced2..466a7950 100644--- a/src/app/api/shorts/probe/route.ts+++ b/src/app/api/shorts/probe/route.ts@@ -1,11 +1,12 @@import { z } from "zod";import { probeSource } from "@/server/shorts";import { body, handle } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";/** An uploaded clip's length, size, frame rate and whether it has sound (from its MP4 / MOV header). */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const { url } = await body(request, z.object({ url: z.string().startsWith("/api/files/").max(500) }), "Upload the clip first");return Response.json(await probeSource(url));});-}+});diff --git a/src/app/api/shorts/sessions/[id]/route.ts b/src/app/api/shorts/sessions/[id]/route.tsindex 1cda7a0d..3e6be8c1 100644--- a/src/app/api/shorts/sessions/[id]/route.ts+++ b/src/app/api/shorts/sessions/[id]/route.ts@@ -2,30 +2,31 @@ import { connection } from "next/server";import { z } from "zod";import { deleteSession, getSession, regenerateCost, renameSession } from "@/server/shorts";import { body, handle } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";/** The session with its generations (segments, takes, stitches) and what one more take costs. */-export async function GET(_req: Request, ctx: RouteContext<"/api/shorts/sessions/[id]">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/shorts/sessions/[id]">) => {await connection();return handle(async () => {const { id } = await ctx.params;const s = getSession(id);return Response.json({ ...s, regenerateUsd: regenerateCost(s) });});-}+});-export async function PATCH(request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]">) => {return handle(async () => {const { id } = await ctx.params;const { title } = await body(request, z.object({ title: z.string().trim().min(1).max(120) }), "Give the short a name");return Response.json(renameSession(id, title));});-}+});/** Delete the session; its videos move to the Trash unless ?keep=1. */-export async function DELETE(request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]">) {+export const DELETE = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]">) => {return handle(async () => {const { id } = await ctx.params;const keep = new URL(request.url).searchParams.get("keep") === "1";return Response.json({ trashed: deleteSession(id, { keep }) });});-}+});diff --git a/src/app/api/shorts/sessions/[id]/segments/[index]/primary/route.ts b/src/app/api/shorts/sessions/[id]/segments/[index]/primary/route.tsindex 7515b42f..32af5059 100644--- a/src/app/api/shorts/sessions/[id]/segments/[index]/primary/route.ts+++ b/src/app/api/shorts/sessions/[id]/segments/[index]/primary/route.ts@@ -1,9 +1,10 @@import { z } from "zod";import { makePrimary, ShortsError } from "@/server/shorts";import { body, handle } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";/** Make a take the one the stitch uses. */-export async function POST(request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]/segments/[index]/primary">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]/segments/[index]/primary">) => {return handle(async () => {const { id, index } = await ctx.params;const i = Number(index);@@ -11,4 +12,4 @@ export async function POST(request: Request, ctx: RouteContext<"/api/shorts/sessconst { generationId } = await body(request, z.object({ generationId: z.string().min(1).max(40) }), "Pick a take");return Response.json(makePrimary(id, i, generationId));});-}+});diff --git a/src/app/api/shorts/sessions/[id]/segments/[index]/route.ts b/src/app/api/shorts/sessions/[id]/segments/[index]/route.tsindex 8f22022f..866f3e1f 100644--- a/src/app/api/shorts/sessions/[id]/segments/[index]/route.ts+++ b/src/app/api/shorts/sessions/[id]/segments/[index]/route.ts@@ -1,8 +1,9 @@import { regenerateSegment, ShortsError } from "@/server/shorts";import { NonceSchema, handle, once, optionalBody } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";/** Regenerate: one more take of this segment (a repeated requestId gets the first answer, not a second take). */-export async function POST(request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]/segments/[index]">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]/segments/[index]">) => {return handle(async () => {const { id, index } = await ctx.params;const i = Number(index);@@ -10,4 +11,4 @@ export async function POST(request: Request, ctx: RouteContext<"/api/shorts/sessconst { requestId } = await optionalBody(request, NonceSchema);return Response.json(await once(`shorts-take:${id}:${i}`, requestId, () => regenerateSegment(id, i)), { status: 201 });});-}+});diff --git a/src/app/api/shorts/sessions/[id]/stitch/route.ts b/src/app/api/shorts/sessions/[id]/stitch/route.tsindex cb2861f3..8f0a1a28 100644--- a/src/app/api/shorts/sessions/[id]/stitch/route.ts+++ b/src/app/api/shorts/sessions/[id]/stitch/route.ts@@ -1,11 +1,12 @@import { stitchSession } from "@/server/shorts";import { NonceSchema, handle, once, optionalBody } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";/** Stitch again: join the chosen takes and put the original sound back (a repeated requestId gets the first answer). */-export async function POST(request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]/stitch">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]/stitch">) => {return handle(async () => {const { id } = await ctx.params;const { requestId } = await optionalBody(request, NonceSchema);return Response.json(await once(`shorts-stitch:${id}`, requestId, () => stitchSession(id)), { status: 201 });});-}+});diff --git a/src/app/api/shorts/sessions/route.ts b/src/app/api/shorts/sessions/route.tsindex 35ce9261..99ff5468 100644--- a/src/app/api/shorts/sessions/route.ts+++ b/src/app/api/shorts/sessions/route.ts@@ -1,18 +1,19 @@import { connection } from "next/server";import { createSession, listSessions } from "@/server/shorts";import { ShortsBodySchema, body, handle, once } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";/** Shorts sessions, newest first (History). */-export async function GET() {+export const GET = handler({ access: "signed-in" }, async () => {await connection();return handle(() => Response.json({ items: listSessions() }));-}+});/** Start a session: cut the clip into segments, restyle each, stitch them under the original sound. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => {const input = await body(request, ShortsBodySchema, "Pick a preset, upload a clip and choose the part to restyle");// A repeated requestId (a second click on Generate) gets the session the first one started.return Response.json(await once("shorts-session", input.requestId, () => createSession(input)), { status: 201 });});-}+});diff --git a/src/app/api/status/route.ts b/src/app/api/status/route.tsindex 5e51ffb4..9f32acd4 100644--- a/src/app/api/status/route.ts+++ b/src/app/api/status/route.ts@@ -4,9 +4,10 @@ import { comfyRam, probeComfy } from "@/server/providers/comfyui";import { nothingConnected, type EngineModeName } from "@/lib/connections";import { getSetting, setSetting } from "@/server/settings";import { offeredSummary } from "@/server/model-access";+import { handler } from "@/server/access/route";/** Which providers are usable right now — drives badges, the demo-mode notice and Home's first-run guide. */-export async function GET() {+export const GET = handler({ access: "signed-in" }, async () => {await connection();const comfy = await probeComfy(true);const ram = comfy ? comfyRam() : undefined;@@ -35,4 +36,4 @@ export async function GET() {// Settings → Models & licences: the models switched off, so pickers leave them out (absent while everything is on)....(access && { access }),});-}+});diff --git a/src/app/api/storyboards/[id]/film/route.ts b/src/app/api/storyboards/[id]/film/route.tsindex d1d659a0..43296bbd 100644--- a/src/app/api/storyboards/[id]/film/route.ts+++ b/src/app/api/storyboards/[id]/film/route.ts@@ -1,10 +1,11 @@import { z } from "zod";import { createStoryboardFilm } from "@/server/storyboard";+import { handler } from "@/server/access/route";const Body = z.object({ modelId: z.string().max(100).optional() });/** Animate a storyboard's frames into clips and join them into one film. */-export async function POST(request: Request, ctx: RouteContext<"/api/storyboards/[id]/film">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/storyboards/[id]/film">) => {const parsed = Body.safeParse((await request.json().catch(() => ({}))) ?? {});if (!parsed.success) return Response.json({ error: "Invalid request" }, { status: 400 });try {@@ -12,4 +13,4 @@ export async function POST(request: Request, ctx: RouteContext<"/api/storyboards} catch (e) {return Response.json({ error: (e as Error).message }, { status: 422 });}-}+});diff --git a/src/app/api/storyboards/estimate/route.ts b/src/app/api/storyboards/estimate/route.tsindex d5ebde86..6d30b454 100644--- a/src/app/api/storyboards/estimate/route.ts+++ b/src/app/api/storyboards/estimate/route.ts@@ -1,7 +1,8 @@import { estimateStoryboard, StoryboardBodySchema } from "@/server/storyboard";+import { handler } from "@/server/access/route";/** What a board costs before it runs ("Free" on your GPU): every frame, the look's model for frame 1. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = StoryboardBodySchema.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: parsed.error.issues.map((i) => i.message).join("; ") }, { status: 400 });try {@@ -9,4 +10,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: 422 });}-}+});diff --git a/src/app/api/storyboards/route.ts b/src/app/api/storyboards/route.tsindex 016e7185..89b79659 100644--- a/src/app/api/storyboards/route.ts+++ b/src/app/api/storyboards/route.ts@@ -1,7 +1,8 @@import { createStoryboard, StoryboardBodySchema } from "@/server/storyboard";+import { handler } from "@/server/access/route";/** Popcorn-style storyboard: consecutive frames, each made from the previous one. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const parsed = StoryboardBodySchema.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: parsed.error.issues.map((i) => i.message).join("; ") }, { status: 400 });try {@@ -9,4 +10,4 @@ export async function POST(request: Request) {} catch (e) {return Response.json({ error: (e as Error).message }, { status: 422 });}-}+});diff --git a/src/app/api/swap-studio/projects/[id]/anchors/route.ts b/src/app/api/swap-studio/projects/[id]/anchors/route.tsindex 0c2a888f..081adf5f 100644--- a/src/app/api/swap-studio/projects/[id]/anchors/route.ts+++ b/src/app/api/swap-studio/projects/[id]/anchors/route.ts@@ -1,10 +1,11 @@import { AnchorSchema, makeAnchor } from "@/server/swap-studio";import { body, handle } from "@/server/shorts-schemas";+import { handler } from "@/server/access/route";/** A scene anchor for a shot (or a reference for a segment): your character put into its first frame. */-export async function POST(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/anchors">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/anchors">) => {return handle(async () => {const { id } = await ctx.params;return Response.json(makeAnchor(id, await body(request, AnchorSchema, "Pick a shot")), { status: 201 });});-}+});diff --git a/src/app/api/swap-studio/projects/[id]/assemble/route.ts b/src/app/api/swap-studio/projects/[id]/assemble/route.tsindex 772dd456..3f82f3f5 100644--- a/src/app/api/swap-studio/projects/[id]/assemble/route.ts+++ b/src/app/api/swap-studio/projects/[id]/assemble/route.ts@@ -1,13 +1,14 @@import { z } from "zod";import { body, handle } from "@/server/shorts-schemas";import { assemble } from "@/server/swap-studio";+import { handler } from "@/server/access/route";const Assemble = z.object({ clipId: z.string().min(1).max(80) });/** Assemble a clip: its chosen takes over the original timeline, with the clip's own sound. */-export async function POST(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/assemble">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/assemble">) => {return handle(async () => {const { id } = await ctx.params;return Response.json(assemble(id, (await body(request, Assemble, "Pick a clip")).clipId), { status: 201 });});-}+});diff --git a/src/app/api/swap-studio/projects/[id]/clips/route.ts b/src/app/api/swap-studio/projects/[id]/clips/route.tsindex 5405e038..58075198 100644--- a/src/app/api/swap-studio/projects/[id]/clips/route.ts+++ b/src/app/api/swap-studio/projects/[id]/clips/route.ts@@ -1,10 +1,11 @@import { body, handle } from "@/server/shorts-schemas";import { addClip, ClipSchema } from "@/server/swap-studio";+import { handler } from "@/server/access/route";/** Add an uploaded clip (MP4, MOV, MKV, WebM or AVI, at most 149.66 s); on your GPU its 24 fps copy starts now. */-export async function POST(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/clips">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/clips">) => {return handle(async () => {const { id } = await ctx.params;return Response.json(await addClip(id, await body(request, ClipSchema, "Upload a clip first")), { status: 201 });});-}+});diff --git a/src/app/api/swap-studio/projects/[id]/decisions/route.ts b/src/app/api/swap-studio/projects/[id]/decisions/route.tsindex 7fafdabf..67bac14d 100644--- a/src/app/api/swap-studio/projects/[id]/decisions/route.ts+++ b/src/app/api/swap-studio/projects/[id]/decisions/route.ts@@ -1,13 +1,14 @@import { connection } from "next/server";import { handle } from "@/server/shorts-schemas";import { decisions } from "@/server/swap-studio";+import { handler } from "@/server/access/route";/** "Export decisions": every clip's review and every take's favourite, decision and notes, as a JSON download. */-export async function GET(_req: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/decisions">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/decisions">) => {await connection();return handle(async () => {const out = decisions((await ctx.params).id);const name = out.project.replace(/[^\w.-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "character-swap";return new Response(JSON.stringify(out, null, 2), { headers: { "Content-Type": "application/json; charset=utf-8", "Content-Disposition": `attachment; filename="${name}-decisions.json"` } });});-}+});diff --git a/src/app/api/swap-studio/projects/[id]/estimate/route.ts b/src/app/api/swap-studio/projects/[id]/estimate/route.tsindex 143df68c..ee3e7286 100644--- a/src/app/api/swap-studio/projects/[id]/estimate/route.ts+++ b/src/app/api/swap-studio/projects/[id]/estimate/route.ts@@ -1,9 +1,10 @@import { connection } from "next/server";import { handle } from "@/server/shorts-schemas";import { estimateProject } from "@/server/swap-studio";+import { handler } from "@/server/access/route";/** Prices before running: one take of each segment, each shot's and the project's queue, masks, anchors, words and assembly. */-export async function GET(_req: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/estimate">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/estimate">) => {await connection();return handle(async () => Response.json(estimateProject((await ctx.params).id)));-}+});diff --git a/src/app/api/swap-studio/projects/[id]/masks/route.ts b/src/app/api/swap-studio/projects/[id]/masks/route.tsindex af0d49ee..dba925ee 100644--- a/src/app/api/swap-studio/projects/[id]/masks/route.ts+++ b/src/app/api/swap-studio/projects/[id]/masks/route.ts@@ -1,10 +1,11 @@import { body, handle } from "@/server/shorts-schemas";import { makeMask, MaskSchema } from "@/server/swap-studio";+import { handler } from "@/server/access/route";/** Who to swap, as a mask: Track shot (from a frame to the shot's end) or Update frame — a new mask version. */-export async function POST(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/masks">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/masks">) => {return handle(async () => {const { id } = await ctx.params;return Response.json(makeMask(id, await body(request, MaskSchema, "Pick a shot, a frame and who to swap")), { status: 201 });});-}+});diff --git a/src/app/api/swap-studio/projects/[id]/prepare/route.ts b/src/app/api/swap-studio/projects/[id]/prepare/route.tsindex edc21ba2..a27159c1 100644--- a/src/app/api/swap-studio/projects/[id]/prepare/route.ts+++ b/src/app/api/swap-studio/projects/[id]/prepare/route.ts@@ -1,13 +1,14 @@import { z } from "zod";import { body, handle } from "@/server/shorts-schemas";import { prepareClip } from "@/server/swap-studio";+import { handler } from "@/server/access/route";const Prepare = z.object({ clipId: z.string().min(1).max(80) });/** Your GPU: make the clip's 24 fps copy (again). The cloud: its browser copy, when the page can't play the clip. */-export async function POST(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/prepare">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/prepare">) => {return handle(async () => {const { id } = await ctx.params;return Response.json(prepareClip(id, (await body(request, Prepare, "Pick a clip")).clipId));});-}+});diff --git a/src/app/api/swap-studio/projects/[id]/queue/route.ts b/src/app/api/swap-studio/projects/[id]/queue/route.tsindex 52b12b12..c4018311 100644--- a/src/app/api/swap-studio/projects/[id]/queue/route.ts+++ b/src/app/api/swap-studio/projects/[id]/queue/route.ts@@ -1,10 +1,11 @@import { body, handle } from "@/server/shorts-schemas";import { QueueSchema, queueTakes } from "@/server/swap-studio";+import { handler } from "@/server/access/route";/** Queue segment / Queue from here / Queue all segments: a take for each, continuations waiting for what they continue from. */-export async function POST(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/queue">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/queue">) => {return handle(async () => {const { id } = await ctx.params;return Response.json(queueTakes(id, await body(request, QueueSchema, "Pick a segment to queue")), { status: 201 });});-}+});diff --git a/src/app/api/swap-studio/projects/[id]/route.ts b/src/app/api/swap-studio/projects/[id]/route.tsindex c3c39f5f..504d8147 100644--- a/src/app/api/swap-studio/projects/[id]/route.ts+++ b/src/app/api/swap-studio/projects/[id]/route.ts@@ -1,25 +1,26 @@import { connection } from "next/server";import { body, handle } from "@/server/shorts-schemas";import { deleteProject, EditSchema, editProject, projectView } from "@/server/swap-studio";+import { handler } from "@/server/access/route";/** The project with every job's state (finished jobs are filled in, ready waiting takes launched). */-export async function GET(_req: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]">) {+export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]">) => {await connection();return handle(async () => Response.json(projectView((await ctx.params).id)));-}+});/** One edit (rename, character, cuts, shot and segment settings, layouts, takes, review…): the project as it is after it. */-export async function PATCH(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]">) {+export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]">) => {return handle(async () => {const { id } = await ctx.params;return Response.json(await editProject(id, await body(request, EditSchema, "That change isn't valid")));});-}+});/** Delete the project, stopping what it still makes (the assembled clips stay in the Library). */-export async function DELETE(_req: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]">) {+export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]">) => {return handle(async () => {await deleteProject((await ctx.params).id);return new Response(null, { status: 204 });});-}+});diff --git a/src/app/api/swap-studio/projects/[id]/stop/route.ts b/src/app/api/swap-studio/projects/[id]/stop/route.tsindex 190a02fe..752c5f55 100644--- a/src/app/api/swap-studio/projects/[id]/stop/route.ts+++ b/src/app/api/swap-studio/projects/[id]/stop/route.ts@@ -1,10 +1,11 @@import { body, handle } from "@/server/shorts-schemas";import { stopJob, StopSchema } from "@/server/swap-studio";+import { handler } from "@/server/access/route";/** Stop a mask, anchor, transcript, 24 fps copy or assembly that is still being made. */-export async function POST(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/stop">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/stop">) => {return handle(async () => {const { id } = await ctx.params;return Response.json(await stopJob(id, await body(request, StopSchema, "Pick a job to stop")));});-}+});diff --git a/src/app/api/swap-studio/projects/[id]/takes/stop/route.ts b/src/app/api/swap-studio/projects/[id]/takes/stop/route.tsindex 0036cada..3bec1cb3 100644--- a/src/app/api/swap-studio/projects/[id]/takes/stop/route.ts+++ b/src/app/api/swap-studio/projects/[id]/takes/stop/route.ts@@ -1,10 +1,11 @@import { body, handle } from "@/server/shorts-schemas";import { stopTake, TakeRefSchema } from "@/server/swap-studio";+import { handler } from "@/server/access/route";/** Stop a take (waiting: it doesn't run; running: it is canceled, and the takes waiting on it stop too). */-export async function POST(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/takes/stop">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/takes/stop">) => {return handle(async () => {const { id } = await ctx.params;return Response.json(await stopTake(id, await body(request, TakeRefSchema, "Pick a take")));});-}+});diff --git a/src/app/api/swap-studio/projects/[id]/transcribe/route.ts b/src/app/api/swap-studio/projects/[id]/transcribe/route.tsindex c8820b0e..7d33e536 100644--- a/src/app/api/swap-studio/projects/[id]/transcribe/route.ts+++ b/src/app/api/swap-studio/projects/[id]/transcribe/route.ts@@ -1,13 +1,14 @@import { z } from "zod";import { body, handle } from "@/server/shorts-schemas";import { transcribe } from "@/server/swap-studio";+import { handler } from "@/server/access/route";const Transcribe = z.object({ clipId: z.string().min(1).max(80) });/** The clip's words, with who speaks when (Scribe v2 on the cloud, Qwen3-ASR on your GPU). */-export async function POST(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/transcribe">) {+export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/transcribe">) => {return handle(async () => {const { id } = await ctx.params;return Response.json(transcribe(id, (await body(request, Transcribe, "Pick a clip")).clipId));});-}+});diff --git a/src/app/api/swap-studio/projects/route.ts b/src/app/api/swap-studio/projects/route.tsindex deedcc01..41860840 100644--- a/src/app/api/swap-studio/projects/route.ts+++ b/src/app/api/swap-studio/projects/route.ts@@ -1,14 +1,15 @@import { connection } from "next/server";import { body, handle } from "@/server/shorts-schemas";import { createProject, CreateSchema, listProjects } from "@/server/swap-studio";+import { handler } from "@/server/access/route";/** Character Swap Studio projects, most recently changed first. */-export async function GET() {+export const GET = handler({ access: "signed-in" }, async () => {await connection();return handle(() => Response.json({ items: listProjects() }));-}+});/** A new project: a name, the engine, and (optionally) the character. */-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {return handle(async () => Response.json(createProject(await body(request, CreateSchema, "Name the project and pick an engine")), { status: 201 }));-}+});diff --git a/src/app/api/uploads/route.ts b/src/app/api/uploads/route.tsindex 851e7978..b8784837 100644--- a/src/app/api/uploads/route.ts+++ b/src/app/api/uploads/route.ts@@ -1,11 +1,12 @@import { contentTypeFor, saveFile } from "@/server/storage";+import { handler } from "@/server/access/route";const MAX_BYTES = 200 * 1024 * 1024;const ALLOWED = /^(image\/(png|jpeg|webp|gif)|video\/(mp4|webm|quicktime|x-matroska|x-msvideo)|audio\/(mpeg|wav|x-wav|ogg|flac|mp4|webm))$/;/** Names browsers give AVI and Matroska files, to the one Fuobe stores them under. */const VIDEO_ALIASES: Record<string, string> = { "video/avi": "video/x-msvideo", "video/msvideo": "video/x-msvideo", "video/vnd.avi": "video/x-msvideo", "video/mkv": "video/x-matroska" };-export async function POST(request: Request) {+export const POST = handler({ access: "signed-in" }, async (request: Request) => {const form = await request.formData().catch(() => null);const file = form?.get("file");if (!(file instanceof File)) return Response.json({ error: "No file" }, { status: 400 });@@ -21,4 +22,4 @@ export async function POST(request: Request) {source: "upload",});return Response.json(asset, { status: 201 });-}+});diff --git a/src/app/s/[token]/f/[...path]/route.ts b/src/app/s/[token]/f/[...path]/route.tsindex 4ac2b0f0..619b6d83 100644--- a/src/app/s/[token]/f/[...path]/route.ts+++ b/src/app/s/[token]/f/[...path]/route.ts@@ -2,6 +2,7 @@ import { shareRoute } from "@/lib/share";import { fileResponse } from "@/server/file-response";import { findShare } from "@/server/share-access";import { shareServesFile } from "@/server/shares";+import { handler } from "@/server/access/route";const NOINDEX = { "X-Robots-Tag": "noindex, nofollow, noarchive", "Referrer-Policy": "no-referrer" };@@ -11,11 +12,11 @@ const NOINDEX = { "X-Robots-Tag": "noindex, nofollow, noarchive", "Referrer-Poli* another share's files or anything else in the files folder. Files go out without the generation* data saved inside them (ComfyUI's prompt and workflow, EXIF, XMP, tags): see media-clean.ts.*/-export async function GET(request: Request, ctx: RouteContext<"/s/[token]/f/[...path]">) {+export const GET = handler({ access: "public" }, async (request: Request, ctx: RouteContext<"/s/[token]/f/[...path]">) => {const { token, path: parts } = await ctx.params;const rel = shareRoute(`/s/${token}/f/${parts.join("/")}`)?.file;const row = rel ? findShare(token) : null;if (!rel || !row || !shareServesFile(row, rel)) return new Response("Not found", { status: 404, headers: NOINDEX });// Revoking stops new requests at once; a browser may keep what it already has for a few minutes.return fileResponse(request, rel, { cache: "private, max-age=300", headers: NOINDEX, clean: true });-}+});diff --git a/tests/assist-connectors.test.ts b/tests/assist-connectors.test.tsindex a61b243d..0b51163d 100644--- a/tests/assist-connectors.test.ts+++ b/tests/assist-connectors.test.ts@@ -92,7 +92,7 @@ describe("connectors in Settings", () => {it("keeps the token on the server: every view masks it, and the API never returns it", async () => {const c = connectors.createConnector({ name: "Notion", url: "https://mcp.notion.com/mcp?workspace=SECRET", token: `Bearer ${TOKEN}` });expect(c).toMatchObject({ name: "Notion", slug: "notion", url: "https://mcp.notion.com/mcp?••••", hasToken: true, enabled: true, token: "sk-l••••cdef" });- const res = await listRoute.GET();+ const res = await listRoute.GET(new Request("http://localhost/"));const body = await res.text();expect(body).not.toContain(TOKEN);expect(body).not.toContain("SECRET");@@ -114,7 +114,7 @@ describe("connectors in Settings", () => {const secret = "ODk1YjQ2NzQtZmFrZS1zZWNyZXQtMTIzNDU2";const c = connectors.createConnector({ name: "Zapier", url: `https://mcp.zapier.com/api/mcp/s/${secret}/mcp` });expect(c.url).toBe("https://mcp.zapier.com/api/mcp/s/…/mcp");- const body = await (await listRoute.GET()).text();+ const body = await (await listRoute.GET(new Request("http://localhost/"))).text();expect(body).not.toContain(secret);// The full URL stays on the server: the duplicate check and the Claude request use it.expect(() => connectors.createConnector({ name: "Zapier again", url: `https://mcp.zapier.com/api/mcp/s/${secret}/mcp` })).toThrow(/already/);diff --git a/tests/canvas-api.test.ts b/tests/canvas-api.test.tsindex 629830a5..4591a15e 100644--- a/tests/canvas-api.test.ts+++ b/tests/canvas-api.test.ts@@ -81,7 +81,7 @@ describe("canvas API", () => {res = await one.PATCH(req("PATCH", { graph: { ...board, edges: [...board.edges, { id: "bad", source: "p", target: "vid", targetHandle: "audio" }] } }), ctx(id));expect(((await res.json()) as Canvas).pages[0].graph.edges.map((e) => e.id)).toEqual(["e1", "e2", "e3"]);- res = await list.GET();+ res = await list.GET(new Request("http://localhost/"));const items = ((await res.json()) as { items: CanvasSummary[] }).items;expect(items[0]).toMatchObject({ id, name: "Fox film", nodeCount: 4, preview: null });expect(items[0].outline.boxes).toHaveLength(4);@@ -115,7 +115,7 @@ describe("canvas API", () => {res = await one.GET(req("GET"), ctx(id));const view = (await res.json()) as { canvas: Canvas; generations: Generation[] };expect(view.generations.map((g) => g.status).sort()).toEqual(["succeeded", "succeeded"]);- const listed = ((await (await list.GET()).json()) as { items: CanvasSummary[] }).items.find((c) => c.id === id)!;+ const listed = ((await (await list.GET(new Request("http://localhost/"))).json()) as { items: CanvasSummary[] }).items.find((c) => c.id === id)!;// Cards prefer a still over a clip.expect(listed.preview).toEqual({ url: gens.getGeneration(img.id)!.outputs[0].url, kind: "image" });@@ -154,7 +154,7 @@ describe("canvas API", () => {view = (await (await one.GET(req("GET"), ctx(id))).json()) as typeof view;expect(view.generations.map((g) => g.id)).not.toContain(imgId);// The card's preview no longer shows the trashed image.- const card = ((await (await list.GET()).json()) as { items: CanvasSummary[] }).items.find((c) => c.id === id)!;+ const card = ((await (await list.GET(new Request("http://localhost/"))).json()) as { items: CanvasSummary[] }).items.find((c) => c.id === id)!;expect(card.preview?.url).not.toBe(gens.getGeneration(imgId, { includeDeleted: true })!.outputs[0].url);res = await run.POST(req("POST", {}), ctx(id));diff --git a/tests/canvas-plus.test.ts b/tests/canvas-plus.test.tsindex 484d696f..9f102092 100644--- a/tests/canvas-plus.test.ts+++ b/tests/canvas-plus.test.ts@@ -490,7 +490,7 @@ describe("pages", () => {// Reloaded as stored.const view = (await (await one.GET(req("GET"), ctx(c.id))).json()) as { canvas: Canvas };expect(view.canvas.pages[1].graph.comments![0].replies![0].text).toBe("Or a fox");- const card = ((await (await list.GET()).json()) as { items: { id: string; pageCount: number; nodeCount: number }[] }).items.find((x) => x.id === c.id)!;+ const card = ((await (await list.GET(new Request("http://localhost/"))).json()) as { items: { id: string; pageCount: number; nodeCount: number }[] }).items.find((x) => x.id === c.id)!;expect(card).toMatchObject({ pageCount: 2, nodeCount: 4 });// Bad pages are refused, naming the page.diff --git a/tests/connections.test.ts b/tests/connections.test.tsindex 4aa2efb6..00977042 100644--- a/tests/connections.test.ts+++ b/tests/connections.test.ts@@ -332,7 +332,7 @@ describe("POST /api/providers/test with unsaved values", () => {});describe("GET /api/status", () => {- const onboarded = async () => ((await (await statusRoute()).json()) as { onboarded: boolean }).onboarded;+ const onboarded = async () => ((await (await statusRoute(new Request("http://localhost/"))).json()) as { onboarded: boolean }).onboarded;it("says whether the first-run guide was put away", async () => {expect(await onboarded()).toBe(false);diff --git a/tests/eval-harness.test.ts b/tests/eval-harness.test.tsindex e87b97df..ffdf6a80 100644--- a/tests/eval-harness.test.ts+++ b/tests/eval-harness.test.ts@@ -64,7 +64,7 @@ type Row = Record<string, unknown> & { id: string; status: string; variant: striconst ctx = (params: Record<string, unknown>) => ({ params: Promise.resolve(params) }) as never;const ROUTES: [string, RegExp, (req: Request, m: RegExpExecArray) => Promise<Response>][] = [- ["GET", /^\/api\/status$/, () => status.GET()],+ ["GET", /^\/api\/status$/, () => status.GET(new Request("http://localhost/"))],["GET", /^\/api\/models$/, (r) => models.GET(r)],["POST", /^\/api\/generations$/, (r) => generations.POST(r)],["GET", /^\/api\/generations\/([^/]+)$/, (r, m) => generation.GET(r, ctx({ id: m[1] }))],diff --git a/tests/genjutsu-api.test.ts b/tests/genjutsu-api.test.tsindex 0449adf1..afba9c7e 100644--- a/tests/genjutsu-api.test.ts+++ b/tests/genjutsu-api.test.ts@@ -143,7 +143,7 @@ describe("Genjutsu: estimates", () => {});describe("key mixes: a run is all real or all a demo, so a missing key is said before anything is paid for", () => {- const say = async (b: Record<string, unknown>, route: { POST: (r: Request) => Promise<Response> } = estimateRoute) => {+ const say = async (b: Record<string, unknown>, route: { POST: (r: Request, ctx?: unknown) => Promise<Response> } = estimateRoute) => {const res = await route.POST(json(b));const out = await res.json();expect(res.status, JSON.stringify(out)).toBe(422);diff --git a/tests/image-studios-api.test.ts b/tests/image-studios-api.test.tsindex 196a27a2..cce333ec 100644--- a/tests/image-studios-api.test.ts+++ b/tests/image-studios-api.test.ts@@ -238,7 +238,7 @@ describe("moodboards", () => {expect(res.status).toBe(409);expect((await res.json()).error).toMatch(/cloud APIs only/);expect(moodboards.getMoodboard(m.id)!.lora).toBeNull();- const targets = (await (await trainRoute.GET()).json()).targets as { id: string; price: string; blocker: string | null; demo: boolean }[];+ const targets = (await (await trainRoute.GET(new Request("http://localhost/"))).json()).targets as { id: string; price: string; blocker: string | null; demo: boolean }[];expect(targets.map((t) => [t.id, t.price])).toEqual([["aitk-z-image", "Free"],["fal-z-image-style", "≈ $3.39 (1,500 steps)"],diff --git a/tests/layers-api.test.ts b/tests/layers-api.test.tsindex 68c93dcc..f08dc3cc 100644--- a/tests/layers-api.test.ts+++ b/tests/layers-api.test.ts@@ -228,7 +228,7 @@ describe("layers API", () => {expect(view.doc).toMatchObject({ width: 1920, height: 1080, decomposed: false, source });expect(view.jobs).toEqual([]);- res = await list.GET();+ res = await list.GET(new Request("http://localhost/"));const items = ((await res.json()) as { items: LayerProject[] }).items;expect(items.map((p) => p.id)).toEqual([id]);@@ -246,7 +246,7 @@ describe("layers API", () => {expect(started.generationIds).toHaveLength(1);// The card says it's processing; a second decomposition is refused while it runs.- res = await list.GET();+ res = await list.GET(new Request("http://localhost/"));expect(((await res.json()) as { items: LayerProject[] }).items[0].status).toBe("processing");res = await jobs.POST(req("POST", { tool: "decompose", engine: "cloud", image: source, frame: [0, 0, 1920, 1080] }), ctx({ id }));expect(res.status).toBe(409);@@ -458,7 +458,7 @@ describe("layers API", () => {// Until the editor lays the layers out, the card says they're ready to see (not “Processing…” for good).expect(v.project).toMatchObject({ status: "unopened", layers: 1 });expect(v.project.pendingLayers).toBe(v.jobs[0].result?.outputs.filter((o) => o.kind === "image").length);- const card = ((await (await list.GET()).json()) as { items: LayerProject[] }).items.find((p) => p.id === v.project.id);+ const card = ((await (await list.GET(new Request("http://localhost/"))).json()) as { items: LayerProject[] }).items.find((p) => p.id === v.project.id);expect(card?.status).toBe("unopened");const bad = await list.POST(req("POST", { source, width: 512, height: 512, generationId: "nope" }));expect(bad.status).toBe(400);diff --git a/tests/library.test.ts b/tests/library.test.tsindex d376c9a9..6f104669 100644--- a/tests/library.test.ts+++ b/tests/library.test.ts@@ -320,7 +320,7 @@ describe("folder routes", () => {const f = (await res.json()) as { id: string; name: string };expect((await folderRoutes.POST(body({ name: "routes" }))).status).toBe(409);expect((await folderRoutes.POST(body({ name: " " }))).status).toBe(400);- expect(((await (await folderRoutes.GET()).json()) as { items: { id: string }[] }).items.map((x) => x.id)).toContain(f.id);+ expect(((await (await folderRoutes.GET(new Request("http://localhost/"))).json()) as { items: { id: string }[] }).items.map((x) => x.id)).toContain(f.id);const renamed = await folderIdRoutes.PATCH(body({ name: "Routes 2" }, "PATCH"), ctx(f.id));expect(((await renamed.json()) as { name: string }).name).toBe("Routes 2");expect((await folderIdRoutes.PATCH(body({ name: "x" }, "PATCH"), ctx("missing"))).status).toBe(404);@@ -514,7 +514,7 @@ describe("nested folders", () => {expect(sub.parentId).toBe(top.id);expect((await folderRoutes.POST(jsonReq("/api/folders", "POST", { name: "Orphan", parentId: "missing" }))).status).toBe(404);// The flat list has both, each with its parent.- const all = ((await (await folderRoutes.GET()).json()) as { items: { id: string; parentId: string | null }[] }).items;+ const all = ((await (await folderRoutes.GET(new Request("http://localhost/"))).json()) as { items: { id: string; parentId: string | null }[] }).items;expect(all.find((f) => f.id === sub.id)?.parentId).toBe(top.id);// PATCH moves (409 into its own subfolder), pins and unpins.expect((await folderIdRoutes.PATCH(jsonReq("/x", "PATCH", { parentId: sub.id }), ctxOf(top.id))).status).toBe(409);diff --git a/tests/lora-fetch.test.ts b/tests/lora-fetch.test.tsindex e4addb78..c9daea1d 100644--- a/tests/lora-fetch.test.ts+++ b/tests/lora-fetch.test.ts@@ -328,7 +328,7 @@ describe("Settings → LoRAs (/api/loras)", () => {setSetting("civitaiKey", KEY);setSetting("comfyLorasDir", folder);fs.writeFileSync(path.join(folder, "AWPortrait-Z.safetensors"), "x");- const res = await route.GET();+ const res = await route.GET(new Request("http://localhost/"));const text = await res.text();expect(text).not.toContain(KEY);const body = JSON.parse(text) as { folder: string; civitaiKey: boolean; loras: { key: string; inFolder: boolean; licence: string; target?: string }[] };@@ -342,13 +342,13 @@ describe("Settings → LoRAs (/api/loras)", () => {const file = path.join(folder, "not-a-folder.txt");fs.writeFileSync(file, "x");setSetting("comfyLorasDir", file);- const res = await route.GET();+ const res = await route.GET(new Request("http://localhost/"));expect(res.status).toBe(200);const body = (await res.json()) as { folderProblem?: string; loras: unknown[] };expect(body.folderProblem).toBe(`The LoRA folder ${file} is a file, not a folder`);expect(body.loras.length).toBeGreaterThan(100);setSetting("comfyLorasDir", path.join(folder, "missing"));- expect(((await (await route.GET()).json()) as { folderProblem?: string }).folderProblem).toMatch(/doesn't exist on this machine/);+ expect(((await (await route.GET(new Request("http://localhost/"))).json()) as { folderProblem?: string }).folderProblem).toMatch(/doesn't exist on this machine/);});it("downloads one LoRA on request, or says why it can't", async () => {diff --git a/tests/marketing-api.test.ts b/tests/marketing-api.test.tsindex accf57d8..8b37572d 100644--- a/tests/marketing-api.test.ts+++ b/tests/marketing-api.test.ts@@ -150,7 +150,7 @@ describe("brand kits", () => {});it("lists, edits (cleaning values) and cancels through the routes", async () => {- const list = await (await brandsRoute.GET()).json();+ const list = await (await brandsRoute.GET(new Request("http://localhost/"))).json();expect(list.items[0]).toMatchObject({ id: brandId, productCount: 2 });const res = await brandRoute.PATCH(json("PATCH", { tagline: " Slow Sunday granola ", colors: ["#ABCDEF", "nope", "rgb(1,2,3)"], tone: ["Warm", "Warm", ""], language: "de" }), params({ id: brandId }));const b = await res.json();diff --git a/tests/model-access-listings.test.ts b/tests/model-access-listings.test.tsindex 907d0d2e..9922764d 100644--- a/tests/model-access-listings.test.ts+++ b/tests/model-access-listings.test.ts@@ -54,9 +54,9 @@ describe("Models & licences in listings and picks", () => {});it("tells the browser what is off through /api/status, and nothing while everything is on", async () => {- expect(((await (await status()).json()) as { access?: unknown }).access).toBeUndefined();+ expect(((await (await status(new Request("http://localhost/"))).json()) as { access?: unknown }).access).toBeUndefined();changeAccess([{ kind: "provider", id: "replicate", on: false }, { kind: "class", id: "research", on: false }]);- const body = (await (await status()).json()) as { access: { off: string[] } };+ const body = (await (await status(new Request("http://localhost/"))).json()) as { access: { off: string[] } };expect(body.access.off).toContain("oss-reactor");expect(body.access.off.length).toBeGreaterThan(5);});@@ -92,7 +92,7 @@ describe("Models & licences in listings and picks", () => {});it("lists every model, LoRA and node pack with its licence, and flips switches through the settings API", async () => {- const list = (await (await settingsRoute.GET()).json()) as import("@/lib/model-access").AccessList;+ const list = (await (await settingsRoute.GET(new Request("http://localhost/"))).json()) as import("@/lib/model-access").AccessList;expect(list.models.length).toBeGreaterThan(300);// The library's 118 LoRAs (Fuobe Try-On's try-on LoRA, the Storyboard's next-scene LoRA, and since O11 Fuobe Angles'// Multiple-angles and Fuobe Speak's FusioniX among them), the preset LoRA map's files that aren't library files, anddiff --git a/tests/share-links.test.ts b/tests/share-links.test.tsindex 9510c3ce..583151ba 100644--- a/tests/share-links.test.ts+++ b/tests/share-links.test.ts@@ -435,7 +435,7 @@ describe("the owner's API", () => {expect(created.status).toBe(201);const { share: s, token } = (await created.json()) as { share: { id: string; expiresAt: number }; token: string };expect(s.expiresAt).toBeGreaterThan(Date.now());- const list = (await (await listRoute.GET()).json()) as { items: ShareListItem[]; signIn: boolean };+ const list = (await (await listRoute.GET(new Request("http://localhost/"))).json()) as { items: ShareListItem[]; signIn: boolean };const row = list.items.find((x) => x.id === s.id)!;expect(row).toMatchObject({ count: 1, gone: false, thumb: { kind: "image" } });expect(JSON.stringify(list)).not.toContain(token);diff --git a/tests/swap-studio-api.test.ts b/tests/swap-studio-api.test.tsindex 8d2e7e91..a20f3343 100644--- a/tests/swap-studio-api.test.ts+++ b/tests/swap-studio-api.test.ts@@ -88,7 +88,7 @@ describe("Character Swap Studio: the cloud, as a demo", () => {expect(created).toMatchObject({ name: "Rain scene", engine: "cloud", character: { image: hero } });expect(recordExists({ kind: "swap-project", ids: [id] })).toBe(true);expect(recordExists({ kind: "swap-project", ids: ["swap-nope"] })).toBe(false);- const list = await (await projects.GET()).json();+ const list = await (await projects.GET(new Request("http://localhost/"))).json();expect(list.items[0]).toMatchObject({ id, clips: 0 });const p = await post(clips, id, { url: clip, name: "dance.mp4" });