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
Revert "Merge branch 'o/acc-2' into claude/fuobe-parity-4"
Claudeead40f0a3fa4
diff --git a/src/app/api/ads/batches/route.ts b/src/app/api/ads/batches/route.tsindex c40546c1..66cc78ae 100644--- a/src/app/api/ads/batches/route.ts+++ b/src/app/api/ads/batches/route.ts@@ -1,11 +1,9 @@import { after } from "next/server";import { BatchBody, createBatch } from "@/server/ads";import { failure, readBody } from "@/server/marketing";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";/** "Create N ads": creatives land in the grid at once; copy and pictures follow in the background. */-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(request: Request) {const body = await readBody(request, BatchBody, "Pick products and how many ads to make");if (body instanceof Response) return body;try {@@ -13,7 +11,6 @@ export const POST = handler({ access: "signed-in" }, async (request: Request) =>after(() => run);return Response.json({ batchId, creatives }, { status: 201 });} catch (e) {- rethrowAccess(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 0c8023d0..a130ce06 100644--- a/src/app/api/ads/creatives/[id]/retry/route.ts+++ b/src/app/api/ads/creatives/[id]/retry/route.ts@@ -1,15 +1,12 @@import { retryCreative } from "@/server/ads";import { failure } from "@/server/marketing";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";/** Make a failed ad again (this spends credits again). */-export const POST = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/ads/creatives/[id]/retry">) => {+export async function POST(_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) {- rethrowAccess(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 edbafe7d..d2baef11 100644--- a/src/app/api/ads/creatives/[id]/route.ts+++ b/src/app/api/ads/creatives/[id]/route.ts@@ -1,18 +1,17 @@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 const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/ads/creatives/[id]">) => {+export async function PATCH(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 const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/ads/creatives/[id]">) => {+export async function DELETE(_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 715546d0..11de5945 100644--- a/src/app/api/ads/creatives/[id]/save/route.ts+++ b/src/app/api/ads/creatives/[id]/save/route.ts@@ -1,20 +1,17 @@import { z } from "zod";import { saveComposite } from "@/server/ads";import { failure, readBody } from "@/server/marketing";-import { rethrowAccess } from "@/server/access/errors";-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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/ads/creatives/[id]/save">) => {+export async function POST(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;try {return Response.json(saveComposite(id, body), { status: 201 });} catch (e) {- rethrowAccess(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 c9e31826..684aca37 100644--- a/src/app/api/ads/creatives/route.ts+++ b/src/app/api/ads/creatives/route.ts@@ -1,12 +1,11 @@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 const GET = handler({ access: "signed-in" }, async (request: Request) => {+export async function GET(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 75fb685c..ae2d9285 100644--- a/src/app/api/ads/estimate/route.ts+++ b/src/app/api/ads/estimate/route.ts@@ -1,16 +1,13 @@import { BatchBody, estimateBatch } from "@/server/ads";import { readBody } from "@/server/marketing";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";/** The total before the run: ads × price per ad (+ the copy), and which model renders them. */-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(request: Request) {const body = await readBody(request, BatchBody, "Pick products and how many ads to make");if (body instanceof Response) return body;try {return Response.json(estimateBatch(body));} catch (e) {- rethrowAccess(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 1fe5cba9..a8d6f938 100644--- a/src/app/api/ads/multiplier/estimate/route.ts+++ b/src/app/api/ads/multiplier/estimate/route.ts@@ -1,14 +1,11 @@import { estimateMultiplier, MultiplierBody, readBody } from "@/server/marketing";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(request: Request) {const body = await readBody(request, MultiplierBody, "Add a reference video to recreate");if (body instanceof Response) return body;try {return Response.json(await estimateMultiplier(body));} catch (e) {- rethrowAccess(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 124379fb..f6125701 100644--- a/src/app/api/ads/multiplier/route.ts+++ b/src/app/api/ads/multiplier/route.ts@@ -1,15 +1,12 @@import { failure, MultiplierBody, readBody, runMultiplier } from "@/server/marketing";-import { rethrowAccess } from "@/server/access/errors";-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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(request: Request) {const body = await readBody(request, MultiplierBody, "Add a reference video to recreate");if (body instanceof Response) return body;try {return Response.json({ runs: await runMultiplier(body) }, { status: 201 });} catch (e) {- rethrowAccess(e);return failure(e);}-});+}diff --git a/src/app/api/assets/[id]/route.ts b/src/app/api/assets/[id]/route.tsindex 0c75cefe..0c142bd9 100644--- a/src/app/api/assets/[id]/route.ts+++ b/src/app/api/assets/[id]/route.ts@@ -3,20 +3,19 @@ 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 const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assets/[id]">) => {+export async function GET(_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 const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assets/[id]">) => {+export async function DELETE(_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 });@@ -25,4 +24,4 @@ export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctxreturn 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 df2d4899..88181793 100644--- a/src/app/api/assets/route.ts+++ b/src/app/api/assets/route.ts@@ -2,10 +2,9 @@ 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 const GET = handler({ access: "signed-in" }, async (request: Request) => {+export async function GET(request: Request) {await connection();const u = new URL(request.url);return Response.json({@@ -16,4 +15,4 @@ export const GET = handler({ access: "signed-in" }, async (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 00506bbc..2d548cc6 100644--- a/src/app/api/assist/[id]/approval/route.ts+++ b/src/app/api/assist/[id]/approval/route.ts@@ -1,13 +1,11 @@import { after } from "next/server";import { z } from "zod";import { answerApproval, AssistBusyError, run } from "@/server/assist/agent";-import { rethrowAccess } from "@/server/access/errors";-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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/assist/[id]/approval">) => {+export async function POST(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,7 +15,6 @@ export const POST = handler({ access: "signed-in" }, async (request: Request, ctafter(() => reply);return Response.json(thread);} catch (e) {- rethrowAccess(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 0359613e..227b0934 100644--- a/src/app/api/assist/[id]/messages/route.ts+++ b/src/app/api/assist/[id]/messages/route.ts@@ -1,10 +1,8 @@import { after } from "next/server";import { addMessage, AssistBusyError, run } from "@/server/assist/agent";import { AssistMessage } from "@/server/assist/schemas";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";-export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/assist/[id]/messages">) => {+export async function POST(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,7 +12,6 @@ export const POST = handler({ access: "signed-in" }, async (request: Request, ctafter(() => reply);return Response.json(thread);} catch (e) {- rethrowAccess(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 89be83ef..72490fca 100644--- a/src/app/api/assist/[id]/route.ts+++ b/src/app/api/assist/[id]/route.ts@@ -2,8 +2,6 @@ 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 { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Patch = z.object({autoApprove: z.boolean().optional(),@@ -12,26 +10,25 @@ const Patch = z.object({mode: ModeChoice.optional(),});-export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/[id]">) => {+export async function GET(_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 const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/assist/[id]">) => {+export async function PATCH(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 {const t = await updateThread((await ctx.params).id, parsed.data);return t ? Response.json(t) : Response.json({ error: "Not found" }, { status: 404 });} catch (e) {- rethrowAccess(e);return Response.json({ error: (e as Error).message }, { status: e instanceof AssistBusyError ? 409 : 400 });}-});+}-export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/[id]">) => {+export async function DELETE(_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 b9b75c36..b6677c2d 100644--- a/src/app/api/assist/connectors/[connectorId]/route.ts+++ b/src/app/api/assist/connectors/[connectorId]/route.ts@@ -1,21 +1,18 @@import { ConnectorError, deleteConnector, updateConnector } from "@/server/assist/connectors";import { ConnectorBody } from "@/server/assist/schemas";-import { rethrowAccess } from "@/server/access/errors";-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 const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/assist/connectors/[connectorId]">) => {+export async function PATCH(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 {const c = updateConnector((await ctx.params).connectorId, parsed.data);return c ? Response.json(c) : Response.json({ error: "Not found" }, { status: 404 });} catch (e) {- rethrowAccess(e);return Response.json({ error: (e as Error).message }, { status: e instanceof ConnectorError ? e.status : 500 });}-});+}-export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/connectors/[connectorId]">) => {+export async function DELETE(_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 782aaff2..8295fc7f 100644--- a/src/app/api/assist/connectors/route.ts+++ b/src/app/api/assist/connectors/route.ts@@ -1,22 +1,19 @@import { connection } from "next/server";import { ConnectorError, createConnector, listConnectors } from "@/server/assist/connectors";import { ConnectorBody } from "@/server/assist/schemas";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";/** Custom MCP connectors, tokens masked. */-export const GET = handler({ access: "signed-in" }, async () => {+export async function GET() {await connection();return Response.json({ items: listConnectors() });-});+}-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 {return Response.json(createConnector(parsed.data), { status: 201 });} catch (e) {- rethrowAccess(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 14f443b8..502a138e 100644--- a/src/app/api/assist/memory/[memoryId]/route.ts+++ b/src/app/api/assist/memory/[memoryId]/route.ts@@ -1,22 +1,19 @@import { z } from "zod";import { deleteMemory, MemoryError, updateMemory } from "@/server/assist/memory";import { MemoryCategorySchema } from "@/server/assist/schemas";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Patch = z.object({ text: z.string().trim().min(1).max(500).optional(), category: MemoryCategorySchema.optional() });-export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/assist/memory/[memoryId]">) => {+export async function PATCH(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 {return Response.json(updateMemory((await ctx.params).memoryId, parsed.data));} catch (e) {- rethrowAccess(e);return Response.json({ error: (e as Error).message }, { status: e instanceof MemoryError ? e.status : 500 });}-});+}-export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/memory/[memoryId]">) => {+export async function DELETE(_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 3f3dfe93..078e209a 100644--- a/src/app/api/assist/memory/import/route.ts+++ b/src/app/api/assist/memory/import/route.ts@@ -2,8 +2,6 @@ import { z } from "zod";import { parseMemoryImport } from "@/lib/assist";import { importMemories, MemoryError } from "@/server/assist/memory";import { MemoryCategorySchema } from "@/server/assist/schemas";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Body = z.object({/** Pasted text (parsed here) … */@@ -15,7 +13,7 @@ const Body = z.object({});/** Import memories pasted from another assistant (Claude, ChatGPT, Codex…). */-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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,7 +21,6 @@ export const POST = handler({ access: "signed-in" }, async (request: Request) =>try {return Response.json(importMemories(items, parsed.data.scope, parsed.data.scope === "project" ? (parsed.data.projectId ?? null) : null));} catch (e) {- rethrowAccess(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 2cc9c403..3055b204 100644--- a/src/app/api/assist/memory/route.ts+++ b/src/app/api/assist/memory/route.ts@@ -2,8 +2,6 @@ import { connection } from "next/server";import { z } from "zod";import { addMemory, listMemories, MemoryError } from "@/server/assist/memory";import { MemoryCategorySchema } from "@/server/assist/schemas";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Add = z.object({text: z.string().trim().min(1).max(500),@@ -13,23 +11,22 @@ const Add = z.object({});/** Memories: `?scope=personal|project|all` and `?project=<id>`. */-export const GET = handler({ access: "signed-in" }, async (request: Request) => {+export async function GET(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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 {return Response.json(addMemory({ ...parsed.data, source: "user" }), { status: 201 });} catch (e) {- rethrowAccess(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 69e495c4..35efacf7 100644--- a/src/app/api/assist/projects/[projectId]/assets/route.ts+++ b/src/app/api/assist/projects/[projectId]/assets/route.ts@@ -1,12 +1,11 @@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 const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/projects/[projectId]/assets">) => {+export async function GET(_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 47b05647..85f73681 100644--- a/src/app/api/assist/projects/[projectId]/route.ts+++ b/src/app/api/assist/projects/[projectId]/route.ts@@ -1,27 +1,24 @@import { connection } from "next/server";import { deleteProject, getProject, ProjectError, updateProject } from "@/server/assist/projects";import { ProjectBody } from "@/server/assist/schemas";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";-export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/projects/[projectId]">) => {+export async function GET(_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 const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/assist/projects/[projectId]">) => {+export async function PATCH(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 {return Response.json(updateProject((await ctx.params).projectId, parsed.data));} catch (e) {- rethrowAccess(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 const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/projects/[projectId]">) => {+export async function DELETE(_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 ef380048..defccef0 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,14 +1,11 @@import { ProjectError, refreshSource } from "@/server/assist/projects";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";/** Fetch a link source again. */-export const POST = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/projects/[projectId]/sources/[sourceId]/refresh">) => {+export async function POST(_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) {- rethrowAccess(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 b2c5fc81..52e7aca2 100644--- a/src/app/api/assist/projects/[projectId]/sources/[sourceId]/route.ts+++ b/src/app/api/assist/projects/[projectId]/sources/[sourceId]/route.ts@@ -1,7 +1,6 @@import { deleteSource } from "@/server/assist/projects";-import { handler } from "@/server/access/route";-export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/projects/[projectId]/sources/[sourceId]">) => {+export async function DELETE(_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 9ef86a26..1b3580b9 100644--- a/src/app/api/assist/projects/[projectId]/sources/route.ts+++ b/src/app/api/assist/projects/[projectId]/sources/route.ts@@ -1,8 +1,6 @@import { z } from "zod";import { addSource, ProjectError } from "@/server/assist/projects";import { contentTypeFor, deleteAsset, saveFile } from "@/server/storage";-import { rethrowAccess } from "@/server/access/errors";-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. */@@ -20,7 +18,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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/assist/projects/[projectId]/sources">) => {+export async function POST(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,7 +45,6 @@ export const POST = handler({ access: "signed-in" }, async (request: Request, ctif (!parsed.success) return Response.json({ error: "Add a link, a file, an element or a note" }, { status: 400 });return Response.json(await addSource(projectId, parsed.data), { status: 201 });} catch (e) {- rethrowAccess(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 7d509551..5c863ad3 100644--- a/src/app/api/assist/projects/route.ts+++ b/src/app/api/assist/projects/route.ts@@ -1,21 +1,18 @@import { connection } from "next/server";import { createProject, listProjects, ProjectError } from "@/server/assist/projects";import { ProjectBody } from "@/server/assist/schemas";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";-export const GET = handler({ access: "signed-in" }, async () => {+export async function GET() {await connection();return Response.json({ items: listProjects() });-});+}-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 {return Response.json(createProject(parsed.data), { status: 201 });} catch (e) {- rethrowAccess(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 50475918..d06ca60b 100644--- a/src/app/api/assist/route.ts+++ b/src/app/api/assist/route.ts@@ -2,8 +2,6 @@ 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 { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Create = AssistMessage.extend({engine: z.enum(["cloud", "open"]),@@ -13,17 +11,17 @@ const Create = AssistMessage.extend({});/** Chats (all, `?project=<id>`, or `?project=none` for chats outside projects; `?q=` searches), with what can run. */-export const GET = handler({ access: "signed-in" }, async (request: Request) => {+export async function GET(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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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;@@ -32,7 +30,6 @@ export const POST = handler({ access: "signed-in" }, async (request: Request) =>try {thread = createThread({ engine, autoApprove, agent: r.agent, projectId: projectId ?? null, mode: r.mode, model: r.model, effort: r.effort });} catch (e) {- rethrowAccess(e);return Response.json({ error: (e as Error).message }, { status: 404 });}const updated = addMessage(thread.id, text, attachments);@@ -40,4 +37,4 @@ export const POST = handler({ access: "signed-in" }, async (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 3f3380e4..b5857eeb 100644--- a/src/app/api/assist/schedules/[scheduleId]/route.ts+++ b/src/app/api/assist/schedules/[scheduleId]/route.ts@@ -1,31 +1,28 @@import { connection } from "next/server";import { deleteSchedule, getSchedule, ScheduleError, updateSchedule } from "@/server/assist/schedules";import { ScheduleBody } from "@/server/assist/schemas";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Patch = ScheduleBody.partial();-export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/schedules/[scheduleId]">) => {+export async function GET(_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 const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/assist/schedules/[scheduleId]">) => {+export async function PATCH(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 {const s = updateSchedule((await ctx.params).scheduleId, parsed.data);return s ? Response.json(s) : Response.json({ error: "Not found" }, { status: 404 });} catch (e) {- rethrowAccess(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 const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/schedules/[scheduleId]">) => {+export async function DELETE(_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 eb3e300f..208ac82e 100644--- a/src/app/api/assist/schedules/[scheduleId]/run/route.ts+++ b/src/app/api/assist/schedules/[scheduleId]/run/route.ts@@ -1,21 +1,18 @@import { after } from "next/server";import { ScheduleError, startSchedule } from "@/server/assist/schedules";-import { rethrowAccess } from "@/server/access/errors";-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 const POST = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/schedules/[scheduleId]/run">) => {+export async function POST(_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 });after(() => started.done);return Response.json({ threadId: started.threadId }, { status: 202 });} catch (e) {- rethrowAccess(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 26da4ce4..26c0fc07 100644--- a/src/app/api/assist/schedules/route.ts+++ b/src/app/api/assist/schedules/route.ts@@ -1,25 +1,22 @@import { connection } from "next/server";import { createSchedule, listSchedules, ScheduleError } from "@/server/assist/schedules";import { ScheduleBody } from "@/server/assist/schemas";-import { rethrowAccess } from "@/server/access/errors";-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 const GET = handler({ access: "signed-in" }, async (request: Request) => {+export async function GET(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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(request: Request) {const parsed = ScheduleBody.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: issue(parsed.error) }, { status: 400 });try {return Response.json(createSchedule(parsed.data), { status: 201 });} catch (e) {- rethrowAccess(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 fda36832..0a803b35 100644--- a/src/app/api/assist/skills/[name]/download/route.ts+++ b/src/app/api/assist/skills/[name]/download/route.ts@@ -1,12 +1,11 @@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 const GET = handler({ access: "signed-in" }, async (req: Request, ctx: RouteContext<"/api/assist/skills/[name]/download">) => {+export async function GET(req: Request, ctx: RouteContext<"/api/assist/skills/[name]/download">) {await connection();const { name } = await ctx.params;const sp = new URL(req.url).searchParams;@@ -30,4 +29,4 @@ export const GET = handler({ access: "signed-in" }, async (req: Request, ctx: Ro"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 d583af10..8fe5116b 100644--- a/src/app/api/assist/skills/[name]/duplicate/route.ts+++ b/src/app/api/assist/skills/[name]/duplicate/route.ts@@ -1,13 +1,10 @@import { duplicateSkill, SkillError } from "@/server/skills";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";/** Copy a skill into My skills (the way to change a built-in). */-export const POST = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/skills/[name]/duplicate">) => {+export async function POST(_req: Request, ctx: RouteContext<"/api/assist/skills/[name]/duplicate">) {try {return Response.json(duplicateSkill((await ctx.params).name), { status: 201 });} catch (e) {- rethrowAccess(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 eb3051d7..b9a851f9 100644--- a/src/app/api/assist/skills/[name]/estimate/route.ts+++ b/src/app/api/assist/skills/[name]/estimate/route.ts@@ -1,17 +1,14 @@import { badBody, recipeFailure, RunBody } from "@/server/recipe-routes";import { estimateRecipe } from "@/server/recipes";-import { rethrowAccess } from "@/server/access/errors";-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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/assist/skills/[name]/estimate">) => {+export async function POST(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 {const { engine, ...input } = parsed.data;return Response.json(estimateRecipe((await ctx.params).name, input, engine));} catch (e) {- rethrowAccess(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 55df898e..1dff251a 100644--- a/src/app/api/assist/skills/[name]/recipe/route.ts+++ b/src/app/api/assist/skills/[name]/recipe/route.ts@@ -1,22 +1,19 @@import { connection } from "next/server";import { recipeFailure } from "@/server/recipe-routes";import { recipeView, saveRecipe } from "@/server/recipes";-import { rethrowAccess } from "@/server/access/errors";-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 const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/skills/[name]/recipe">) => {+export async function GET(_req: Request, ctx: RouteContext<"/api/assist/skills/[name]/recipe">) {await connection();try {return Response.json(recipeView((await ctx.params).name));} catch (e) {- rethrowAccess(e);return recipeFailure(e);}-});+}/** Save a user skill's recipe.json (it starts unchecked); every problem is named. */-export const PUT = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/assist/skills/[name]/recipe">) => {+export async function PUT(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 {@@ -24,7 +21,6 @@ export const PUT = handler({ access: "signed-in" }, async (request: Request, ctxsaveRecipe(name, body);return Response.json(recipeView(name));} catch (e) {- rethrowAccess(e);return recipeFailure(e);}-});+}diff --git a/src/app/api/assist/skills/[name]/route.ts b/src/app/api/assist/skills/[name]/route.tsindex c3ca19bf..252200dc 100644--- a/src/app/api/assist/skills/[name]/route.ts+++ b/src/app/api/assist/skills/[name]/route.ts@@ -1,8 +1,6 @@import { connection } from "next/server";import { z } from "zod";import { deleteSkill, getSkill, setSkillEnabled, SkillError, updateSkill } from "@/server/skills";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Patch = z.object({enabled: z.boolean().optional(),@@ -16,14 +14,14 @@ const Patch = z.object({const fail = (e: unknown) => Response.json({ error: (e as Error).message }, { status: e instanceof SkillError ? e.status : 500 });-export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/skills/[name]">) => {+export async function GET(_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 const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/assist/skills/[name]">) => {+export async function PATCH(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,17 +32,15 @@ export const PATCH = handler({ access: "signed-in" }, async (request: Request, cif (enabled !== undefined) s = setSkillEnabled(s.name, enabled);return Response.json(s);} catch (e) {- rethrowAccess(e);return fail(e);}-});+}-export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/assist/skills/[name]">) => {+export async function DELETE(_req: Request, ctx: RouteContext<"/api/assist/skills/[name]">) {try {deleteSkill((await ctx.params).name);return new Response(null, { status: 204 });} catch (e) {- rethrowAccess(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 43deba93..23447463 100644--- a/src/app/api/assist/skills/[name]/run/route.ts+++ b/src/app/api/assist/skills/[name]/run/route.ts@@ -1,17 +1,14 @@import { badBody, recipeFailure, RunBody } from "@/server/recipe-routes";import { runRecipe } from "@/server/recipes";-import { rethrowAccess } from "@/server/access/errors";-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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/assist/skills/[name]/run">) => {+export async function POST(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 {const { engine, ...input } = parsed.data;return Response.json(await runRecipe((await ctx.params).name, input, engine), { status: 201 });} catch (e) {- rethrowAccess(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 484a3076..cecb4fa8 100644--- a/src/app/api/assist/skills/[name]/verify/route.ts+++ b/src/app/api/assist/skills/[name]/verify/route.ts@@ -1,8 +1,6 @@import { z } from "zod";import { badBody, recipeFailure } from "@/server/recipe-routes";import { verifyRecipe } from "@/server/recipes";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Body = z.object({level: z.enum(["plan", "demo", "real"]).default("demo"),@@ -12,14 +10,13 @@ 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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/assist/skills/[name]/verify">) => {+export async function POST(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 {const { level, engine, confirm } = parsed.data;return Response.json(await verifyRecipe((await ctx.params).name, level, engine, { confirm }));} catch (e) {- rethrowAccess(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 de8cc252..1389f737 100644--- a/src/app/api/assist/skills/draft/check/route.ts+++ b/src/app/api/assist/skills/draft/check/route.ts@@ -1,8 +1,6 @@import { z } from "zod";import { badBody, recipeFailure } from "@/server/recipe-routes";import { checkDraft } from "@/server/recipes";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Body = z.object({recipe: z.unknown(),@@ -12,13 +10,12 @@ 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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(request: Request) {const parsed = Body.safeParse(await request.json().catch(() => ({})));if (!parsed.success) return badBody(parsed.error.issues);try {return Response.json(await checkDraft(parsed.data.recipe, parsed.data.level, parsed.data.title || undefined));} catch (e) {- rethrowAccess(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 b4cd696e..3881b2ab 100644--- a/src/app/api/assist/skills/draft/name/route.ts+++ b/src/app/api/assist/skills/draft/name/route.ts@@ -1,8 +1,6 @@import { z } from "zod";import { badBody, recipeFailure } from "@/server/recipe-routes";import { draftFromGenerations, nameDraft } from "@/server/recipe-builder";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Body = z.object({ generations: z.array(z.string().min(1).max(40)).min(1).max(200) });@@ -10,14 +8,13 @@ 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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(request: Request) {const parsed = Body.safeParse(await request.json().catch(() => ({})));if (!parsed.success) return badBody(parsed.error.issues);try {const { draft } = draftFromGenerations(parsed.data.generations);return Response.json({ naming: draft ? await nameDraft(draft) : null });} catch (e) {- rethrowAccess(e);return recipeFailure(e);}-});+}diff --git a/src/app/api/assist/skills/draft/route.ts b/src/app/api/assist/skills/draft/route.tsindex edadea0d..85db57d6 100644--- a/src/app/api/assist/skills/draft/route.ts+++ b/src/app/api/assist/skills/draft/route.ts@@ -1,8 +1,6 @@import { z } from "zod";import { badBody, recipeFailure } from "@/server/recipe-routes";import { draftFromGenerations } from "@/server/recipe-builder";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Body = z.object({ generations: z.array(z.string().min(1).max(40)).min(1).max(200) });@@ -10,13 +8,12 @@ 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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(request: Request) {const parsed = Body.safeParse(await request.json().catch(() => ({})));if (!parsed.success) return badBody(parsed.error.issues);try {return Response.json(draftFromGenerations(parsed.data.generations));} catch (e) {- rethrowAccess(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 4c204ae8..d2835d89 100644--- a/src/app/api/assist/skills/draft/save/route.ts+++ b/src/app/api/assist/skills/draft/save/route.ts@@ -2,19 +2,16 @@ import { z } from "zod";import { SkillBody } from "@/server/assist/schemas";import { badBody, recipeFailure } from "@/server/recipe-routes";import { saveDraft } from "@/server/recipes";-import { rethrowAccess } from "@/server/access/errors";-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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(request: Request) {const parsed = Body.safeParse(await request.json().catch(() => ({})));if (!parsed.success) return badBody(parsed.error.issues);try {return Response.json(await saveDraft(parsed.data), { status: 201 });} catch (e) {- rethrowAccess(e);return recipeFailure(e);}-});+}diff --git a/src/app/api/assist/skills/route.ts b/src/app/api/assist/skills/route.tsindex 9a7a01b9..48e34368 100644--- a/src/app/api/assist/skills/route.ts+++ b/src/app/api/assist/skills/route.ts@@ -1,23 +1,20 @@import { connection } from "next/server";import { SkillBody } from "@/server/assist/schemas";import { createSkill, listSkills, SkillError } from "@/server/skills";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";/** Every skill: built-in (from skills/) and the user's own. */-export const GET = handler({ access: "signed-in" }, async () => {+export async function GET() {await connection();return Response.json({ items: listSkills() });-});+}/** Create a skill from the form (name, title, description, when to use, instructions). */-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 {return Response.json(createSkill(parsed.data), { status: 201 });} catch (e) {- rethrowAccess(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 a9e8d98f..796ce3e4 100644--- a/src/app/api/assist/skills/upload/route.ts+++ b/src/app/api/assist/skills/upload/route.ts@@ -1,11 +1,9 @@import { importSkill, SkillError } from "@/server/skills";-import { rethrowAccess } from "@/server/access/errors";-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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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,7 +13,6 @@ export const POST = handler({ access: "signed-in" }, async (request: Request) =>const r = importSkill({ name: file.name, data: Buffer.from(await file.arrayBuffer()) }, { replace });return Response.json(r, { status: r.replaced ? 200 : 201 });} catch (e) {- rethrowAccess(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 fd31c233..6ea5a9b3 100644--- a/src/app/api/audio-tools/export/route.ts+++ b/src/app/api/audio-tools/export/route.ts@@ -1,12 +1,10 @@import { MixExportError, PART_MAX, receiveMixPart } from "@/server/mix-export";-import { rethrowAccess } from "@/server/access/errors";-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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 });@@ -16,9 +14,8 @@ export const POST = handler({ access: "signed-in" }, async (request: Request) =>const r = receiveMixPart({ id: q.get("id"), offset, data, last: q.get("last") === "1", name: q.get("name") });return Response.json(r, { status: "relPath" in r ? 201 : 200 });} catch (e) {- rethrowAccess(e);if (e instanceof MixExportError) return Response.json({ error: e.message }, { status: e.status });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 ac6441b4..37eb1a09 100644--- a/src/app/api/audio-tools/route.ts+++ b/src/app/api/audio-tools/route.ts@@ -1,6 +1,4 @@import { AudioToolBody, AudioToolError, previewAudioTool, runAudioTool } from "@/server/audio-tools";-import { rethrowAccess } from "@/server/access/errors";-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> = {@@ -12,7 +10,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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(request: Request) {const raw: unknown = await request.json().catch(() => null);const parsed = AudioToolBody.safeParse(raw);if (!parsed.success) {@@ -25,9 +23,8 @@ export const POST = handler({ access: "signed-in" }, async (request: Request) =>if (new URL(request.url).searchParams.get("preview") === "1") return Response.json(await previewAudioTool(parsed.data));return Response.json(await runAudioTool(parsed.data), { status: 201 });} catch (e) {- rethrowAccess(e);if (e instanceof AudioToolError) return Response.json({ error: e.message }, { status: 422 });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 b07f2609..03bc2ace 100644--- a/src/app/api/auth/login/route.ts+++ b/src/app/api/auth/login/route.ts@@ -5,7 +5,6 @@ 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@@ -23,7 +22,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 const POST = handler({ access: "public" }, async (request: Request) => {+export async function POST(request: Request) {if (!signInRequired()) return Response.json({ ok: true });const key = LoginGuard.clientKey(request.headers);const wait = guard.blockedFor(key);@@ -52,4 +51,4 @@ export const POST = handler({ access: "public" }, async (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 3ed5324b..e1fda938 100644--- a/src/app/api/auth/logout/route.ts+++ b/src/app/api/auth/logout/route.ts@@ -1,15 +1,14 @@+import { appendAudit } from "@/server/identity/audit-log";import { signOut } from "@/server/identity/owner";-import { maybeActor } from "@/server/access/actor";-import { audit } from "@/server/access/audit";-import { handler } from "@/server/access/route";+import { resolvePrincipal } from "@/server/identity/principal";/** Sign out: Better Auth deletes the session (so the cookie is dead everywhere) and expires the cookie. */-export const POST = handler({ access: "public" }, async (request: Request) => {- const actor = maybeActor();+export async function POST(request: Request) {+ const { actor } = await resolvePrincipal(request);const cookies = await signOut(request.headers);- if (actor?.via === "session") audit("auth.sign_out", { kind: "session", id: actor.sessionId ?? null });+ if (actor?.via === "session") appendAudit({ action: "auth.sign_out", actorId: actor.userId, via: "session", targetKind: "session", targetId: 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 51860c11..bb6bd631 100644--- a/src/app/api/auth/password/route.ts+++ b/src/app/api/auth/password/route.ts@@ -2,11 +2,9 @@ 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 { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";/*** Settings → Security in Personal: whether a password is required, and setting, changing or removing it (removing@@ -16,30 +14,30 @@ import { handler } from "@/server/access/route";const Body = z.object({ current: z.string().max(PASSWORD_SIGN_IN_MAX).optional(), password: z.string().max(PASSWORD_SIGN_IN_MAX).nullable() });-function status() {- return { enabled: signInRequired(), ...ownerPasswordStatus(), tokens: listTokens(currentActor().userId) };+async function status(request: Request) {+ const { actor } = await resolvePrincipal(request);+ return { enabled: signInRequired(), ...ownerPasswordStatus(), tokens: actor ? listTokens(actor.userId) : [] };}-export const GET = handler({ access: "signed-in" }, async () => {+export async function GET(request: Request) {await connection();- return Response.json(status());-});+ return Response.json(await status(request));+}-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 = currentActor();+ const { actor } = await resolvePrincipal(request);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 {await changeOwnerPassword(password, { actorId: actor.userId, via: actor.via });} catch (e) {- rethrowAccess(e);return Response.json({ error: (e as Error).message }, { status: 400 });}const headers = new Headers({ "Cache-Control": "no-store" });@@ -49,5 +47,5 @@ export const POST = handler({ access: "signed-in" }, async (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(status(), { headers });-});+ return Response.json(await status(request), { headers });+}diff --git a/src/app/api/auth/tokens/route.ts b/src/app/api/auth/tokens/route.tsindex 51d36b77..8c7e6591 100644--- a/src/app/api/auth/tokens/route.ts+++ b/src/app/api/auth/tokens/route.ts@@ -1,35 +1,39 @@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 (access "browser" answers it 403). Each person sees and revokes their own (admins revoking anyone's arrives- * with the admin console).+ * tokens. 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 const GET = handler({ access: "browser" }, async () => {+export async function GET(request: Request) {await connection();- const actor = currentActor();+ const actor = await browserActor(request);+ if (actor instanceof Response) return actor;return Response.json({ tokens: listTokens(actor.userId) });-});+}/** Create a token; the full value is in this response only. */-export const POST = handler({ access: "browser" }, async (request: Request) => {- const actor = currentActor();- gate("token.create", actor);+export async function POST(request: Request) {+ const actor = await browserActor(request);+ if (actor instanceof Response) return 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 const DELETE = handler({ access: "browser" }, async (request: Request) => {- const actor = currentActor();+export async function DELETE(request: Request) {+ const actor = await browserActor(request);+ if (actor instanceof Response) return actor;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 27780cd3..24a9ddf2 100644--- a/src/app/api/brands/[id]/chat/confirm/route.ts+++ b/src/app/api/brands/[id]/chat/confirm/route.ts@@ -2,13 +2,11 @@ import { after } from "next/server";import { z } from "zod";import { confirmProposal } from "@/server/ads";import { failure, readBody } from "@/server/marketing";-import { rethrowAccess } from "@/server/access/errors";-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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/brands/[id]/chat/confirm">) => {+export async function POST(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,7 +15,6 @@ export const POST = handler({ access: "signed-in" }, async (request: Request, ctafter(() => r.run);return Response.json({ batchId: r.batchId, messages: r.chat }, { status: 201 });} catch (e) {- rethrowAccess(e);return failure(e);}-});+}diff --git a/src/app/api/brands/[id]/chat/route.ts b/src/app/api/brands/[id]/chat/route.tsindex aa9c6b9e..8b55583b 100644--- a/src/app/api/brands/[id]/chat/route.ts+++ b/src/app/api/brands/[id]/chat/route.ts@@ -3,33 +3,30 @@ import { z } from "zod";import { chat, clearChat, getChat } from "@/server/ads";import { getBrand } from "@/server/brand";import { failure, readBody } from "@/server/marketing";-import { rethrowAccess } from "@/server/access/errors";-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 const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/brands/[id]/chat">) => {+export async function GET(_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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/brands/[id]/chat">) => {+export async function POST(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;try {return Response.json({ messages: await chat(id, body.text) });} catch (e) {- rethrowAccess(e);return failure(e);}-});+}-export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/brands/[id]/chat">) => {+export async function DELETE(_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 3f1d167d..07b0883d 100644--- a/src/app/api/brands/[id]/research/route.ts+++ b/src/app/api/brands/[id]/research/route.ts@@ -1,25 +1,22 @@import { after } from "next/server";import { cancelResearch, retryResearch } from "@/server/brand";import { failure } from "@/server/marketing";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";/** Run the website research again (Retry research). */-export const POST = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/brands/[id]/research">) => {+export async function POST(_req: Request, ctx: RouteContext<"/api/brands/[id]/research">) {const { id } = await ctx.params;try {const { brand, run } = retryResearch(id);after(() => run);return Response.json(brand, { status: 202 });} catch (e) {- rethrowAccess(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 const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/brands/[id]/research">) => {+export async function DELETE(_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 023f3f60..1442f796 100644--- a/src/app/api/brands/[id]/route.ts+++ b/src/app/api/brands/[id]/route.ts@@ -2,8 +2,6 @@ import { connection } from "next/server";import { z } from "zod";import { deleteBrand, getBrand, listProducts, updateBrand } from "@/server/brand";import { failure, readBody } from "@/server/marketing";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const list = (max: number, len: number) => z.array(z.string().max(len)).max(max);@@ -28,15 +26,15 @@ const Patch = z.object({});/** One brand kit with its products. */-export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/brands/[id]">) => {+export async function GET(_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 const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/brands/[id]">) => {+export async function PATCH(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,13 +42,12 @@ export const PATCH = handler({ access: "signed-in" }, async (request: Request, cconst brand = updateBrand(id, body);return brand ? Response.json(brand) : Response.json({ error: "Not found" }, { status: 404 });} catch (e) {- rethrowAccess(e);return failure(e);}-});+}/** The kit and its products leave the shelf; ads already made stay in the Library. */-export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/brands/[id]">) => {+export async function DELETE(_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 49a3bdc2..553a65e7 100644--- a/src/app/api/brands/route.ts+++ b/src/app/api/brands/route.ts@@ -2,8 +2,6 @@ import { after, connection } from "next/server";import { z } from "zod";import { createBrandFromWebsite, createManualBrand, listBrands } from "@/server/brand";import { failure, readBody } from "@/server/marketing";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Body = z.union([z.object({ website: z.string().trim().min(1).max(300) }),@@ -16,16 +14,16 @@ const Body = z.union([]);/** Brand kits, newest activity first (with product and ad counts). */-export const GET = handler({ access: "signed-in" }, async () => {+export async function GET() {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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(request: Request) {const body = await readBody(request, Body, "Add a website, or describe your business");if (body instanceof Response) return body;try {@@ -36,7 +34,6 @@ export const POST = handler({ access: "signed-in" }, async (request: Request) =>}return Response.json(await createManualBrand(body), { status: 201 });} catch (e) {- rethrowAccess(e);return failure(e);}-});+}diff --git a/src/app/api/canvases/[id]/duplicate/route.ts b/src/app/api/canvases/[id]/duplicate/route.tsindex 0101c942..b9700fdc 100644--- a/src/app/api/canvases/[id]/duplicate/route.ts+++ b/src/app/api/canvases/[id]/duplicate/route.ts@@ -1,9 +1,8 @@import { duplicateCanvas } from "@/server/canvas";-import { handler } from "@/server/access/route";/** "Copy of {name}", with the same nodes and results. */-export const POST = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/canvases/[id]/duplicate">) => {+export async function POST(_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 88796fb1..fd4346b9 100644--- a/src/app/api/canvases/[id]/route.ts+++ b/src/app/api/canvases/[id]/route.ts@@ -1,7 +1,6 @@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(),@@ -13,15 +12,15 @@ const Patch = z.object({});/** The board, its nodes' last runs and the generations they made. */-export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/canvases/[id]">) => {+export async function GET(_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 const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/canvases/[id]">) => {+export async function PATCH(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 });@@ -36,9 +35,9 @@ export const PATCH = handler({ access: "signed-in" }, async (request: Request, cif (e instanceof CanvasConflict) return Response.json({ error: e.message }, { status: e.status });throw e;}-});+}-export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/canvases/[id]">) => {+export async function DELETE(_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 53eca11a..8857bb32 100644--- a/src/app/api/canvases/[id]/run/route.ts+++ b/src/app/api/canvases/[id]/run/route.ts@@ -1,6 +1,5 @@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). */@@ -21,7 +20,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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/canvases/[id]/run">) => {+export async function POST(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 });@@ -42,4 +41,4 @@ export const POST = handler({ access: "signed-in" }, async (request: Request, ctreturn 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 06bf4e5f..a6c37953 100644--- a/src/app/api/canvases/route.ts+++ b/src/app/api/canvases/route.ts@@ -1,8 +1,6 @@import { connection } from "next/server";import { z } from "zod";import { createCanvas, listCanvases, parseGraph, parsePages } from "@/server/canvas";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Body = z.object({name: z.string().max(80).optional(),@@ -12,12 +10,12 @@ const Body = z.object({pages: z.unknown().optional(),});-export const GET = handler({ access: "signed-in" }, async () => {+export async function GET() {await connection();return Response.json({ items: listCanvases() });-});+}-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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,7 +25,6 @@ export const POST = handler({ access: "signed-in" }, async (request: Request) =>try {return Response.json(createCanvas({ ...rest, graph, pages }), { status: 201 });} catch (e) {- rethrowAccess(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 ab8e692e..c80c7118 100644--- a/src/app/api/cinema/projects/[id]/director/route.ts+++ b/src/app/api/cinema/projects/[id]/director/route.ts@@ -2,18 +2,17 @@ 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 const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/cinema/projects/[id]/director">) => {+export async function GET(_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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/director">) => {+export async function POST(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");@@ -22,12 +21,12 @@ export const POST = handler({ access: "signed-in" }, async (request: Request, ctafter(() => reply.catch(() => {}));return Response.json({ messages: await reply });});-});+}-export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/cinema/projects/[id]/director">) => {+export async function DELETE(_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 e11d6de4..b28ef54f 100644--- a/src/app/api/cinema/projects/[id]/folders/[folderId]/route.ts+++ b/src/app/api/cinema/projects/[id]/folders/[folderId]/route.ts@@ -1,20 +1,19 @@import { deleteFolder, updateFolder } from "@/server/cinema";import { FolderPatch, body, handle } from "@/server/cinema-schemas";-import { handler } from "@/server/access/route";-export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/folders/[folderId]">) => {+export async function PATCH(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 const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/cinema/projects/[id]/folders/[folderId]">) => {+export async function DELETE(_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 38a121b8..6347527c 100644--- a/src/app/api/cinema/projects/[id]/folders/route.ts+++ b/src/app/api/cinema/projects/[id]/folders/route.ts@@ -1,11 +1,10 @@import { createFolder } from "@/server/cinema";import { FolderCreate, body, handle } from "@/server/cinema-schemas";-import { handler } from "@/server/access/route";-export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/folders">) => {+export async function POST(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 3d369a1e..aa618ca6 100644--- a/src/app/api/cinema/projects/[id]/generate/route.ts+++ b/src/app/api/cinema/projects/[id]/generate/route.ts@@ -1,15 +1,14 @@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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/generate">) => {+export async function POST(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 ee1bcdd4..a32f81a8 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,11 +1,10 @@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 const POST = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/cinema/projects/[id]/items/[generationId]/retry">) => {+export async function POST(_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 534576c3..903e9c3f 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,12 +1,11 @@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 const PUT = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/items/[generationId]/tiles">) => {+export async function PUT(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 337b7969..231293cf 100644--- a/src/app/api/cinema/projects/[id]/items/route.ts+++ b/src/app/api/cinema/projects/[id]/items/route.ts@@ -1,14 +1,13 @@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 const GET = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/items">) => {+export async function GET(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/items">) {await connection();return handle(async () => {const { id } = await ctx.params;@@ -22,10 +21,10 @@ export const GET = handler({ access: "signed-in" }, async (request: Request, ctx});return Response.json({ items });});-});+}/** Bulk: move to a folder (`folderId`, null = project root) and/or like / unlike. */-export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/items">) => {+export async function PATCH(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");@@ -34,13 +33,13 @@ export const PATCH = handler({ access: "signed-in" }, async (request: Request, cconst 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 const DELETE = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/items">) => {+export async function DELETE(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 bbcc45ed..a364cea8 100644--- a/src/app/api/cinema/projects/[id]/route.ts+++ b/src/app/api/cinema/projects/[id]/route.ts@@ -2,10 +2,9 @@ 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 const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/cinema/projects/[id]">) => {+export async function GET(_req: Request, ctx: RouteContext<"/api/cinema/projects/[id]">) {await connection();return handle(async () => {const { id } = await ctx.params;@@ -14,20 +13,20 @@ export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: Rconst { cloudAllowed, civitai } = cinemaContext();return Response.json({ project, folders: listFolders(id), spentUsd: spentUsd(id), context: { cloudAllowed, civitai } });});-});+}-export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/cinema/projects/[id]">) => {+export async function PATCH(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 const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/cinema/projects/[id]">) => {+export async function DELETE(_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 81de5c63..051abb94 100644--- a/src/app/api/cinema/projects/route.ts+++ b/src/app/api/cinema/projects/route.ts@@ -1,16 +1,15 @@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 const GET = handler({ access: "signed-in" }, async () => {+export async function GET() {await connection();return handle(() => Response.json({ items: listProjects() }));-});+}-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 b3efbcc4..8facd2f1 100644--- a/src/app/api/comfyui/route.ts+++ b/src/app/api/comfyui/route.ts@@ -1,9 +1,8 @@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 const GET = handler({ access: "signed-in" }, async () => {+export async function GET() {await connection();const manifest = loadManifest();const reachable = await probeComfy(true);@@ -18,4 +17,4 @@ export const GET = handler({ access: "signed-in" }, async () => {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 04faafc5..789827f4 100644--- a/src/app/api/content-factory/claude/route.ts+++ b/src/app/api/content-factory/claude/route.ts@@ -1,7 +1,6 @@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),@@ -10,6 +9,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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 5e91ec45..e27435c2 100644--- a/src/app/api/content-factory/estimate/route.ts+++ b/src/app/api/content-factory/estimate/route.ts@@ -1,7 +1,6 @@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(),@@ -10,6 +9,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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 34172f87..546fc6d9 100644--- a/src/app/api/content-factory/series/[id]/episodes/route.ts+++ b/src/app/api/content-factory/series/[id]/episodes/route.ts@@ -2,7 +2,6 @@ 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`),@@ -11,9 +10,9 @@ const More = z.object({});/** "Next episode": plan and start more episodes after the ones already made. */-export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/content-factory/series/[id]/episodes">) => {+export async function POST(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 a99d6f99..e6d0e8db 100644--- a/src/app/api/content-factory/series/[id]/generate/route.ts+++ b/src/app/api/content-factory/series/[id]/generate/route.ts@@ -1,14 +1,13 @@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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/content-factory/series/[id]/generate">) => {+export async function POST(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 65848570..17132b58 100644--- a/src/app/api/content-factory/series/[id]/read/route.ts+++ b/src/app/api/content-factory/series/[id]/read/route.ts@@ -1,14 +1,13 @@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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/content-factory/series/[id]/read">) => {+export async function POST(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 5a9a3198..2f57b7ed 100644--- a/src/app/api/content-factory/series/[id]/route.ts+++ b/src/app/api/content-factory/series/[id]/route.ts@@ -2,31 +2,30 @@ 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 const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/content-factory/series/[id]">) => {+export async function GET(_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 const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/content-factory/series/[id]">) => {+export async function PATCH(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 const DELETE = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/content-factory/series/[id]">) => {+export async function DELETE(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 d7219867..198cf1d2 100644--- a/src/app/api/content-factory/series/route.ts+++ b/src/app/api/content-factory/series/route.ts@@ -2,7 +2,6 @@ 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(),@@ -11,18 +10,18 @@ const Create = z.object({});/** Series that have been made, newest first. */-export const GET = handler({ access: "signed-in" }, async () => {+export async function GET() {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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 0f0ccbb1..448a9df5 100644--- a/src/app/api/dub/[id]/route.ts+++ b/src/app/api/dub/[id]/route.ts@@ -1,33 +1,30 @@import { connection } from "next/server";import { z } from "zod";import { CueSchema, deleteDubSession, dubView, getDubSession, saveDubDraft } from "@/server/dub";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Patch = z.object({ lang: z.string().min(2).max(12), cues: z.array(CueSchema).max(3000) });-export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/dub/[id]">) => {+export async function GET(_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 const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/dub/[id]">) => {+export async function PATCH(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 });try {return Response.json(saveDubDraft(id, parsed.data.lang, parsed.data.cues));} catch (e) {- rethrowAccess(e);return Response.json({ error: (e as Error).message }, { status: getDubSession(id) ? 422 : 404 });}-});+}/** Forget the dub (its results stay in the Library). */-export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/dub/[id]">) => {+export async function DELETE(_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 32f64d2d..88efd6d9 100644--- a/src/app/api/dub/[id]/voice/route.ts+++ b/src/app/api/dub/[id]/voice/route.ts@@ -1,7 +1,5 @@import { z } from "zod";import { CueSchema, getDubSession, previewVoiceDub, voiceDub } from "@/server/dub";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Body = z.object({lang: z.string().min(2).max(12),@@ -11,7 +9,7 @@ const Body = z.object({});/** Speak one language's reviewed lines in the cloned voice: the voice pipeline; `?preview=1` only prices it. */-export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/dub/[id]/voice">) => {+export async function POST(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,7 +19,6 @@ export const POST = handler({ access: "signed-in" }, async (request: Request, ctif (new URL(request.url).searchParams.get("preview") === "1") return Response.json(previewVoiceDub(id, parsed.data.lang, opts));return Response.json(voiceDub(id, parsed.data.lang, opts), { status: 201 });} catch (e) {- rethrowAccess(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 ea9d7821..d0ed2bdb 100644--- a/src/app/api/dub/route.ts+++ b/src/app/api/dub/route.ts@@ -2,8 +2,6 @@ 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 { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Body = z.object({engine: z.enum(["cloud", "open"]),@@ -18,14 +16,14 @@ const Body = z.object({});/** Recent dubs with the state of every step. */-export const GET = handler({ access: "signed-in" }, async (request: Request) => {+export async function GET(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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(request: Request) {const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) {const first = parsed.error.issues[0];@@ -36,7 +34,6 @@ export const POST = handler({ access: "signed-in" }, async (request: Request) =>if (new URL(request.url).searchParams.get("preview") === "1") return Response.json(previewDub(parsed.data));return Response.json(createDubSession(parsed.data), { status: 201 });} catch (e) {- rethrowAccess(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 65928472..e155df48 100644--- a/src/app/api/elements/[id]/lora/route.ts+++ b/src/app/api/elements/[id]/lora/route.ts@@ -2,8 +2,6 @@ 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 { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Body = z.object({file: z.string().min(1).max(300),@@ -12,7 +10,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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/elements/[id]/lora">) => {+export async function POST(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,7 +19,6 @@ export const POST = handler({ access: "signed-in" }, async (request: Request, ctawait attachLora(id, parsed.data);return Response.json(getElement(id));} catch (e) {- rethrowAccess(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 1e500419..4f8555ad 100644--- a/src/app/api/elements/[id]/route.ts+++ b/src/app/api/elements/[id]/route.ts@@ -3,7 +3,6 @@ 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(),@@ -13,14 +12,14 @@ const Patch = z.object({removeIdentities: z.array(z.string()).optional(),});-export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/elements/[id]">) => {+export async function GET(_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 const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/elements/[id]">) => {+export async function PATCH(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 });@@ -29,10 +28,10 @@ export const PATCH = handler({ access: "signed-in" }, async (request: Request, cconst 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 const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/elements/[id]">) => {+export async function DELETE(_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 2e6b8a2e..ccc0f0b5 100644--- a/src/app/api/elements/[id]/training-kit/route.ts+++ b/src/app/api/elements/[id]/training-kit/route.ts@@ -1,10 +1,8 @@import { AITK_FAMILIES, type TrainingFamily } from "@/lib/catalog/training";import { trainingKit } from "@/server/training";-import { rethrowAccess } from "@/server/access/errors";-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 const GET = handler({ access: "signed-in" }, async (req: Request, ctx: RouteContext<"/api/elements/[id]/training-kit">) => {+export async function GET(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,7 +12,6 @@ export const GET = handler({ access: "signed-in" }, async (req: Request, ctx: Roheaders: { "Content-Type": "application/zip", "Content-Disposition": `attachment; filename="${kit.name}"` },});} catch (e) {- rethrowAccess(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 3973d650..5abbcf10 100644--- a/src/app/api/elements/[id]/trainings/route.ts+++ b/src/app/api/elements/[id]/trainings/route.ts@@ -4,11 +4,9 @@ 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 { rethrowAccess } from "@/server/access/errors";-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 const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/elements/[id]/trainings">) => {+export async function GET(_req: Request, ctx: RouteContext<"/api/elements/[id]/trainings">) {await connection();const { id } = await ctx.params;ensureRunner(); // the background poller also checks training jobs@@ -17,12 +15,12 @@ export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: Rtargets: 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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/elements/[id]/trainings">) => {+export async function POST(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,7 +28,6 @@ export const POST = handler({ access: "signed-in" }, async (request: Request, ctensureRunner();return Response.json(startTraining(id, parsed.data.target, { consent: parsed.data.consent }), { status: 201 });} catch (e) {- rethrowAccess(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 942b81f4..38a77b51 100644--- a/src/app/api/elements/route.ts+++ b/src/app/api/elements/route.ts@@ -2,7 +2,6 @@ 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"]);@@ -13,17 +12,17 @@ const Body = z.object({references: z.array(z.string().startsWith("/api/files/")).max(MAX_ELEMENT_PHOTOS),});-export const GET = handler({ access: "signed-in" }, async (request: Request) => {+export async function GET(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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 e28a2a8b..0e350cab 100644--- a/src/app/api/enhance/route.ts+++ b/src/app/api/enhance/route.ts@@ -1,15 +1,12 @@import { enhancePrompt } from "@/server/enhance";import type { MediaKind, Operation } from "@/lib/catalog/types";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 {return Response.json({ prompt: await enhancePrompt(prompt, kind ?? "image", op ?? "t2i") });} catch (e) {- rethrowAccess(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 77170f73..72ad5c17 100644--- a/src/app/api/evolution/direction/route.ts+++ b/src/app/api/evolution/direction/route.ts@@ -1,11 +1,10 @@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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 fad06c24..2dabbcb7 100644--- a/src/app/api/evolution/estimate/route.ts+++ b/src/app/api/evolution/estimate/route.ts@@ -1,11 +1,10 @@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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 05ccbe46..b6911fbe 100644--- a/src/app/api/evolution/route.ts+++ b/src/app/api/evolution/route.ts@@ -1,13 +1,12 @@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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 d1813956..76dd637a 100644--- a/src/app/api/explainer/document/route.ts+++ b/src/app/api/explainer/document/route.ts@@ -1,11 +1,10 @@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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(request: Request) {return handle(async () => {const form = await request.formData().catch(() => null);const file = form?.get("file");@@ -14,4 +13,4 @@ export const POST = handler({ access: "signed-in" }, async (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 1667d7d4..fad633f4 100644--- a/src/app/api/explainer/link/route.ts+++ b/src/app/api/explainer/link/route.ts@@ -1,13 +1,12 @@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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 e13cd3af..aad9ea88 100644--- a/src/app/api/explainer/route.ts+++ b/src/app/api/explainer/route.ts@@ -2,7 +2,6 @@ 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)"),@@ -13,19 +12,19 @@ const Create = z.object({});/** History: your explainers, newest first (`?q=` search, `?liked=1`). */-export const GET = handler({ access: "signed-in" }, async (request: Request) => {+export async function GET(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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 14d196a5..44f09c6d 100644--- a/src/app/api/faceless/channels/[id]/avatar/route.ts+++ b/src/app/api/faceless/channels/[id]/avatar/route.ts@@ -1,10 +1,9 @@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 const POST = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/faceless/channels/[id]/avatar">) => {+export async function POST(_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 db6b6df0..2a435c70 100644--- a/src/app/api/faceless/channels/[id]/route.ts+++ b/src/app/api/faceless/channels/[id]/route.ts@@ -1,7 +1,6 @@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(),@@ -13,7 +12,7 @@ const Patch = z.object({});/** The channel with its episodes. */-export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/faceless/channels/[id]">) => {+export async function GET(_req: Request, ctx: RouteContext<"/api/faceless/channels/[id]">) {await connection();return handle(async () => {const { id } = await ctx.params;@@ -21,21 +20,21 @@ export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: Rif (!channel) throw new FacelessError("Channel not found", 404);return Response.json({ channel, episodes: listEpisodes({ channelId: id, limit: 200 }) });});-});+}-export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/faceless/channels/[id]">) => {+export async function PATCH(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 const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/faceless/channels/[id]">) => {+export async function DELETE(_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 f7e0c5c4..84522075 100644--- a/src/app/api/faceless/channels/route.ts+++ b/src/app/api/faceless/channels/route.ts@@ -1,7 +1,6 @@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"),@@ -12,15 +11,15 @@ const Create = z.object({});/** Your channels, newest first, with episode counts and the latest finished episode. */-export const GET = handler({ access: "signed-in" }, async () => {+export async function GET() {await connection();return handle(() => Response.json({ items: listChannels() }));-});+}/** Create a channel (its name is written for you when you don't give one). */-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 11b4fd46..908c0468 100644--- a/src/app/api/faceless/episodes/[id]/[action]/route.ts+++ b/src/app/api/faceless/episodes/[id]/[action]/route.ts@@ -1,5 +1,4 @@import { episodeView, handle, renderEpisode, retryEpisode, rewriteEpisode, undoChange, upscaleEpisode } from "@/server/faceless";-import { handler } from "@/server/access/route";const ACTIONS = {/** Render the reviewed script. */@@ -14,7 +13,7 @@ const ACTIONS = {upscale: upscaleEpisode,} as const;-export const POST = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/faceless/episodes/[id]/[action]">) => {+export async function POST(_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];@@ -22,4 +21,4 @@ export const POST = handler({ access: "signed-in" }, async (_req: Request, ctx:run(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 95353dc9..6a9307c4 100644--- a/src/app/api/faceless/episodes/[id]/change/route.ts+++ b/src/app/api/faceless/episodes/[id]/change/route.ts@@ -1,12 +1,11 @@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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/faceless/episodes/[id]/change">) => {+export async function POST(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");@@ -14,4 +13,4 @@ export const POST = handler({ access: "signed-in" }, async (request: Request, ctapplyChange(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 cde244b5..3a075834 100644--- a/src/app/api/faceless/episodes/[id]/route.ts+++ b/src/app/api/faceless/episodes/[id]/route.ts@@ -1,7 +1,6 @@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(),@@ -11,29 +10,29 @@ const Patch = z.object({});/** The episode with every step's generation, its progress, spend and estimate. */-export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/faceless/episodes/[id]">) => {+export async function GET(_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 const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/faceless/episodes/[id]">) => {+export async function PATCH(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 const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/faceless/episodes/[id]">) => {+export async function DELETE(_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 b962bdb7..5120a4c0 100644--- a/src/app/api/faceless/episodes/route.ts+++ b/src/app/api/faceless/episodes/route.ts@@ -3,7 +3,6 @@ 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),@@ -15,16 +14,16 @@ const Create = z.object({});/** Episodes, newest first (`?channel=` for one channel). */-export const GET = handler({ access: "signed-in" }, async (request: Request) => {+export async function GET(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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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.@@ -32,4 +31,4 @@ export const POST = handler({ access: "signed-in" }, async (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 0504a9ab..d69688fa 100644--- a/src/app/api/faceless/estimate/route.ts+++ b/src/app/api/faceless/estimate/route.ts@@ -1,6 +1,5 @@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"]),@@ -10,6 +9,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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 a3db904f..0111dd4c 100644--- a/src/app/api/faceless/topics/route.ts+++ b/src/app/api/faceless/topics/route.ts@@ -1,6 +1,5 @@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(),@@ -12,7 +11,7 @@ const Ask = z.object({});/** 4–6 episode topics for a channel (the install's LLM, or templates offline). */-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(request: Request) {return handle(async () => {const q = await body(request, Ask, "Describe the channel first");const channel = q.channelId ? getChannel(q.channelId) : null;@@ -21,4 +20,4 @@ export const POST = handler({ access: "signed-in" }, async (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 3672cf75..e1a101e2 100644--- a/src/app/api/faceless/voices/preview/route.ts+++ b/src/app/api/faceless/voices/preview/route.ts@@ -1,13 +1,12 @@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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 4700f911..f6a7e920 100644--- a/src/app/api/files/[...path]/route.ts+++ b/src/app/api/files/[...path]/route.ts@@ -1,7 +1,6 @@import { fileResponse } from "@/server/file-response";-import { handler } from "@/server/access/route";-export const GET = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/files/[...path]">) => {+export async function GET(request: Request, ctx: RouteContext<"/api/files/[...path]">) {const { path: parts } = await ctx.params;let rel: string;try {@@ -10,4 +9,4 @@ export const GET = handler({ access: "signed-in" }, async (request: Request, ctxreturn 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 f606f70e..a0f0d235 100644--- a/src/app/api/folders/[id]/route.ts+++ b/src/app/api/folders/[id]/route.ts@@ -1,8 +1,6 @@import { connection } from "next/server";import { z } from "zod";import { deleteFolder, getFolder, LibraryError, updateFolder } from "@/server/library";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Patch = z.object({name: z.string().trim().min(1).max(60).optional(),@@ -12,15 +10,15 @@ const Patch = z.object({pinned: z.boolean().optional(),});-export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/folders/[id]">) => {+export async function GET(_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 const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/folders/[id]">) => {+export async function PATCH(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,13 +26,12 @@ export const PATCH = handler({ access: "signed-in" }, async (request: Request, cconst f = updateFolder(id, parsed.data);return f ? Response.json(f) : Response.json({ error: "Not found" }, { status: 404 });} catch (e) {- rethrowAccess(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 const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/folders/[id]">) => {+export async function DELETE(_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 0d206104..03bae3e7 100644--- a/src/app/api/folders/[id]/zip/route.ts+++ b/src/app/api/folders/[id]/zip/route.ts@@ -1,15 +1,13 @@import { connection } from "next/server";import { folderZipEntries, LibraryError, ZIP_MAX_BYTES } from "@/server/library";import { zipSize, zipStream } from "@/server/zip";-import { rethrowAccess } from "@/server/access/errors";-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 const GET = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/folders/[id]/zip">) => {+export async function GET(request: Request, ctx: RouteContext<"/api/folders/[id]/zip">) {await connection();const { id } = await ctx.params;const sp = new URL(request.url).searchParams;@@ -17,7 +15,6 @@ export const GET = handler({ access: "signed-in" }, async (request: Request, ctxtry {zip = folderZipEntries(id, { steps: sp.get("steps") === "1" });} catch (e) {- rethrowAccess(e);return Response.json({ error: (e as Error).message }, { status: e instanceof LibraryError ? e.status : 500 });}if (!zip) return Response.json({ error: "That folder doesn't exist anymore" }, { status: 404 });@@ -34,4 +31,4 @@ export const GET = handler({ access: "signed-in" }, async (request: Request, ctx"Cache-Control": "no-store",},});-});+}diff --git a/src/app/api/folders/route.ts b/src/app/api/folders/route.tsindex 38138a12..02c01a80 100644--- a/src/app/api/folders/route.ts+++ b/src/app/api/folders/route.ts@@ -1,26 +1,23 @@import { connection } from "next/server";import { z } from "zod";import { createFolder, LibraryError, listFolders } from "@/server/library";-import { rethrowAccess } from "@/server/access/errors";-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 const GET = handler({ access: "signed-in" }, async () => {+export async function GET() {await connection();return Response.json({ items: listFolders() });-});+}/** A new folder; `parentId` makes it a subfolder. */-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 {return Response.json(createFolder(parsed.data), { status: 201 });} catch (e) {- rethrowAccess(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 f4aeff35..e8618143 100644--- a/src/app/api/generations/[id]/cancel/route.ts+++ b/src/app/api/generations/[id]/cancel/route.ts@@ -1,8 +1,7 @@import { cancelGeneration, getGeneration } from "@/server/generations";-import { handler } from "@/server/access/route";-export const POST = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/generations/[id]/cancel">) => {+export async function POST(_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 5e314168..6aecfc51 100644--- a/src/app/api/generations/[id]/finish/route.ts+++ b/src/app/api/generations/[id]/finish/route.ts@@ -1,5 +1,4 @@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]);@@ -8,7 +7,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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/generations/[id]/finish">) => {+export async function POST(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");@@ -23,4 +22,4 @@ export const POST = handler({ access: "signed-in" }, async (request: Request, ctif (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 ad896871..e27de293 100644--- a/src/app/api/generations/[id]/route.ts+++ b/src/app/api/generations/[id]/route.ts@@ -2,17 +2,16 @@ 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 const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/generations/[id]">) => {+export async function GET(_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 const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/generations/[id]">) => {+export async function PATCH(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 });@@ -21,12 +20,12 @@ export const PATCH = handler({ access: "signed-in" }, async (request: Request, cif (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 const DELETE = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/generations/[id]">) => {+export async function DELETE(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 0dca611c..1478d64c 100644--- a/src/app/api/generations/bulk/route.ts+++ b/src/app/api/generations/bulk/route.ts@@ -1,7 +1,5 @@import { z } from "zod";import { deleteForever, moveToFolder, restoreGenerations, setFavorites, setPinned, setReview, trashGenerations } from "@/server/library";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Body = z.object({action: z.enum(["trash", "restore", "delete", "favorite", "unfavorite", "move", "pin", "unpin", "review"]),@@ -13,7 +11,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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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,7 +32,6 @@ export const POST = handler({ access: "signed-in" }, async (request: Request) =>: setFavorites(ids, action === "favorite");return Response.json({ count });} catch (e) {- rethrowAccess(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 771e66fb..3d81521f 100644--- a/src/app/api/generations/facets/route.ts+++ b/src/app/api/generations/facets/route.ts@@ -1,9 +1,8 @@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 const GET = handler({ access: "signed-in" }, async (request: Request) => {+export async function GET(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 a2e1e159..4387fa3e 100644--- a/src/app/api/generations/local/route.ts+++ b/src/app/api/generations/local/route.ts@@ -1,7 +1,5 @@import { z } from "zod";import { recordLocalGeneration } from "@/server/generations";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Body = z.object({feature: z.string().min(1).max(80),@@ -14,13 +12,12 @@ const Body = z.object({});/** Record a result rendered in the browser (e.g. a colour grade) so it shows up in the library. */-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(request: Request) {const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Invalid result" }, { status: 400 });try {return Response.json(recordLocalGeneration(parsed.data), { status: 201 });} catch (e) {- rethrowAccess(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 bb24fd77..f6da8919 100644--- a/src/app/api/generations/route.ts+++ b/src/app/api/generations/route.ts@@ -3,8 +3,6 @@ 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 { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";/*** List generations, newest first. Filters: kind / kinds, features (`x*` = prefix), models, statuses,@@ -12,14 +10,14 @@ import { handler } from "@/server/access/route";* paging with before=<createdAt>:<id> of the last row (<deletedAt>:<id> in the Trash; a bare* timestamp still works) and limit (≤ 200).*/-export const GET = handler({ access: "signed-in" }, async (request: Request) => {+export async function GET(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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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,7 +35,6 @@ export const POST = handler({ access: "signed-in" }, async (request: Request) =>const notes = [...new Set(items.flatMap((g) => g.notes ?? []))];return Response.json({ items, ...(notes.length && { notes }) }, { status: 201 });} catch (e) {- rethrowAccess(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 f27fab4c..ae67c849 100644--- a/src/app/api/generations/stream/route.ts+++ b/src/app/api/generations/stream/route.ts@@ -1,7 +1,6 @@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):@@ -10,9 +9,9 @@ import { handler } from "@/server/access/route";* : ping every 15 s* Sent on every insert or update of a generation row (status, progress, outputs…).*/-export const GET = handler({ access: "signed-in" }, async (request: Request) => {+export async function GET(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 16b0400d..13f95375 100644--- a/src/app/api/generations/trash/route.ts+++ b/src/app/api/generations/trash/route.ts@@ -1,16 +1,15 @@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 const GET = handler({ access: "signed-in" }, async (request: Request) => {+export async function GET(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 const DELETE = handler({ access: "signed-in" }, async () => {+export async function DELETE() {return Response.json({ count: await emptyTrash() });-});+}diff --git a/src/app/api/generations/zip/route.ts b/src/app/api/generations/zip/route.tsindex eb58343f..85e9b67d 100644--- a/src/app/api/generations/zip/route.ts+++ b/src/app/api/generations/zip/route.ts@@ -1,10 +1,9 @@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 const GET = handler({ access: "signed-in" }, async (request: Request) => {+export async function GET(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 });@@ -21,4 +20,4 @@ export const GET = handler({ access: "signed-in" }, async (request: Request) =>"Cache-Control": "no-store",},});-});+}diff --git a/src/app/api/genjutsu/describe/route.ts b/src/app/api/genjutsu/describe/route.tsindex 5cdbc61c..9586b694 100644--- a/src/app/api/genjutsu/describe/route.ts+++ b/src/app/api/genjutsu/describe/route.ts@@ -1,11 +1,10 @@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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 4b101538..fdab6c41 100644--- a/src/app/api/genjutsu/estimate/route.ts+++ b/src/app/api/genjutsu/estimate/route.ts@@ -1,11 +1,10 @@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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 810c6a8a..1c79d6f7 100644--- a/src/app/api/genjutsu/route.ts+++ b/src/app/api/genjutsu/route.ts@@ -1,13 +1,12 @@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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 7893e22f..544b963e 100644--- a/src/app/api/genjutsu/transcribe/route.ts+++ b/src/app/api/genjutsu/transcribe/route.ts@@ -1,11 +1,10 @@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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 bc714082..b853e61f 100644--- a/src/app/api/identity/[...all]/route.ts+++ b/src/app/api/identity/[...all]/route.ts@@ -1,6 +1,5 @@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@@ -13,6 +12,5 @@ async function handle(request: Request): Promise<Response> {return getAuth().handler(request);}-// 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);+export const GET = handle;+export const POST = handle;diff --git a/src/app/api/influencer/estimate/route.ts b/src/app/api/influencer/estimate/route.tsindex cf897b63..09326e16 100644--- a/src/app/api/influencer/estimate/route.ts+++ b/src/app/api/influencer/estimate/route.ts@@ -1,12 +1,11 @@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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 5ebc9651..1ce51dc8 100644--- a/src/app/api/influencer/route.ts+++ b/src/app/api/influencer/route.ts@@ -1,8 +1,6 @@import { z } from "zod";import { MAX_CLOTHING, MAX_DIRECTION } from "@/lib/influencer";import { createInfluencer, previewInfluencer, type InfluencerBody } from "@/server/influencer";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const File = z.string().startsWith("/api/files/").max(500);@@ -32,7 +30,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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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,7 +38,6 @@ export const POST = handler({ access: "signed-in" }, async (request: Request) =>try {return Response.json(createInfluencer(body), { status: 201 });} catch (e) {- rethrowAccess(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 bdc740dd..57aad703 100644--- a/src/app/api/katana/[id]/retry/route.ts+++ b/src/app/api/katana/[id]/retry/route.ts@@ -1,16 +1,13 @@import { getKatana, rerunKatana, retryKatana } from "@/server/katana";-import { rethrowAccess } from "@/server/access/errors";-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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/katana/[id]/retry">) => {+export async function POST(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 {const all = new URL(request.url).searchParams.get("all") === "1";return Response.json(all ? rerunKatana(id) : retryKatana(id), { status: 201 });} catch (e) {- rethrowAccess(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 f492efdc..88fad2dc 100644--- a/src/app/api/katana/[id]/route.ts+++ b/src/app/api/katana/[id]/route.ts@@ -1,16 +1,15 @@import { connection } from "next/server";import { deleteKatana, getKatana } from "@/server/katana";-import { handler } from "@/server/access/route";-export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/katana/[id]">) => {+export async function GET(_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 const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/katana/[id]">) => {+export async function DELETE(_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 2d2f42a8..ddf27759 100644--- a/src/app/api/katana/route.ts+++ b/src/app/api/katana/route.ts@@ -1,17 +1,15 @@import { connection } from "next/server";import { createKatana, KatanaBody, listKatana, previewKatana } from "@/server/katana";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";/** Recent Katana runs with the state of every step. */-export const GET = handler({ access: "signed-in" }, async (request: Request) => {+export async function GET(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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(request: Request) {const parsed = KatanaBody.safeParse(await request.json().catch(() => null));if (!parsed.success) {const path = String(parsed.error.issues[0]?.path[0] ?? "");@@ -22,7 +20,6 @@ export const POST = handler({ access: "signed-in" }, async (request: Request) =>if (new URL(request.url).searchParams.get("preview") === "1") return Response.json(previewKatana(parsed.data));return Response.json(createKatana(parsed.data), { status: 201 });} catch (e) {- rethrowAccess(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 31b2b02a..807c428f 100644--- a/src/app/api/layers/[id]/jobs/[jobId]/route.ts+++ b/src/app/api/layers/[id]/jobs/[jobId]/route.ts@@ -1,21 +1,20 @@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 const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/layers/[id]/jobs/[jobId]">) => {+export async function PATCH(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 const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/layers/[id]/jobs/[jobId]">) => {+export async function DELETE(_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 2676b637..5bb43b4b 100644--- a/src/app/api/layers/[id]/jobs/route.ts+++ b/src/app/api/layers/[id]/jobs/route.ts@@ -1,20 +1,17 @@import { JobInputSchema, LayersError, startJob } from "@/server/layers";-import { rethrowAccess } from "@/server/access/errors";-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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/layers/[id]/jobs">) => {+export async function POST(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 });try {return Response.json(startJob(id, parsed.data), { status: 201 });} catch (e) {- rethrowAccess(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 c9a51e57..8a9007ee 100644--- a/src/app/api/layers/[id]/route.ts+++ b/src/app/api/layers/[id]/route.ts@@ -1,8 +1,6 @@import { connection } from "next/server";import { z } from "zod";import { deleteProject, LayersError, parseDoc, projectView, updateProject } from "@/server/layers";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Patch = z.object({name: z.string().max(200).optional(),@@ -15,14 +13,14 @@ const Patch = z.object({});/** The project, its versions, the head document and its tools' jobs (with their results). */-export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/layers/[id]">) => {+export async function GET(_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 const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/layers/[id]">) => {+export async function PATCH(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,13 +30,12 @@ export const PATCH = handler({ access: "signed-in" }, async (request: Request, cconst p = updateProject(id, { name: parsed.data.name, doc, versionId: parsed.data.versionId, cover: parsed.data.cover });return p ? Response.json(p) : Response.json({ error: "Not found" }, { status: 404 });} catch (e) {- rethrowAccess(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 const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/layers/[id]">) => {+export async function DELETE(_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 81ff5d15..2824f60f 100644--- a/src/app/api/layers/[id]/versions/route.ts+++ b/src/app/api/layers/[id]/versions/route.ts@@ -1,7 +1,5 @@import { z } from "zod";import { createVersion, LayersError, parseDoc } from "@/server/layers";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Body = z.object({doc: z.unknown().optional(),@@ -13,7 +11,7 @@ const Body = z.object({});/** Save a version (a tool's result, or a restored older version); it becomes the head. */-export const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/layers/[id]/versions">) => {+export async function POST(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,7 +20,6 @@ export const POST = handler({ access: "signed-in" }, async (request: Request, cttry {return Response.json(createVersion(id, { ...parsed.data, doc }), { status: 201 });} catch (e) {- rethrowAccess(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 8e5526ae..84fa6f31 100644--- a/src/app/api/layers/renders/route.ts+++ b/src/app/api/layers/renders/route.ts@@ -1,5 +1,4 @@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]);@@ -9,7 +8,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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 });@@ -18,4 +17,4 @@ export const POST = handler({ access: "signed-in" }, async (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 2dd54cf5..ce00b3f4 100644--- a/src/app/api/layers/route.ts+++ b/src/app/api/layers/route.ts@@ -1,8 +1,6 @@import { connection } from "next/server";import { z } from "zod";import { createProject, FileUrl, LayersError, listProjects } from "@/server/layers";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Body = z.object({/** The image to open: an upload or a result (an /api/files/ URL). */@@ -16,20 +14,19 @@ const Body = z.object({});/** Your Layers projects, most recently edited first. */-export const GET = handler({ access: "signed-in" }, async () => {+export async function GET() {await connection();return Response.json({ items: listProjects() });-});+}/** Open an image in Layers: a new project with the image as its only layer. */-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 {return Response.json(createProject(parsed.data), { status: 201 });} catch (e) {- rethrowAccess(e);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 f09ba400..57754a4e 100644--- a/src/app/api/loras/route.ts+++ b/src/app/api/loras/route.ts@@ -3,14 +3,12 @@ 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 { rethrowAccess } from "@/server/access/errors";-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 const GET = handler({ access: "signed-in" }, async () => {+export async function GET() {await connection();const folder = getSetting("comfyLorasDir");// A folder setting that can't be read (a file, no permission) is said, not a 500.@@ -39,17 +37,16 @@ export const GET = handler({ access: "signed-in" }, async () => {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 const POST = handler({ access: "perm:install.settings" }, async (request: Request) => {+export async function POST(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 {const copy = await downloadToComfy(body.file);return Response.json({ file: copy.file, sizeBytes: copy.sizeBytes, sha256: copy.sha256 });} catch (e) {- rethrowAccess(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 630f3fb5..f62da1b4 100644--- a/src/app/api/marketing/click-to-ad/estimate/route.ts+++ b/src/app/api/marketing/click-to-ad/estimate/route.ts@@ -1,14 +1,11 @@import { ClickToAdBody, estimateClickToAd, readBody } from "@/server/marketing";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(request: Request) {const body = await readBody(request, ClickToAdBody, "Select a product or enter a product URL");if (body instanceof Response) return body;try {return Response.json(estimateClickToAd(body));} catch (e) {- rethrowAccess(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 7c990637..59106e0d 100644--- a/src/app/api/marketing/click-to-ad/route.ts+++ b/src/app/api/marketing/click-to-ad/route.ts@@ -1,15 +1,12 @@import { ClickToAdBody, failure, readBody, runClickToAd } from "@/server/marketing";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";/** Click to Ad: a 9:16 voiced ad with captions from a product kit and a style. */-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(request: Request) {const body = await readBody(request, ClickToAdBody, "Select a product or enter a product URL");if (body instanceof Response) return body;try {return Response.json(await runClickToAd(body), { status: 201 });} catch (e) {- rethrowAccess(e);return failure(e);}-});+}diff --git a/src/app/api/marketing/estimate/route.ts b/src/app/api/marketing/estimate/route.tsindex f0690a44..eb50509b 100644--- a/src/app/api/marketing/estimate/route.ts+++ b/src/app/api/marketing/estimate/route.ts@@ -1,15 +1,12 @@import { estimateMarketing, MarketingBody, readBody } from "@/server/marketing";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";/** Price and check a Marketing Studio run before it starts; what's missing comes back as `blocker`. */-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(request: Request) {const body = await readBody(request, MarketingBody);if (body instanceof Response) return body;try {return Response.json(estimateMarketing(body));} catch (e) {- rethrowAccess(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 83d42d87..d2966ea7 100644--- a/src/app/api/marketing/runs/[id]/again/route.ts+++ b/src/app/api/marketing/runs/[id]/again/route.ts@@ -1,14 +1,11 @@import { failure, rerun } from "@/server/marketing";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";/** Run again: the same template, product and settings as a new run. */-export const POST = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/marketing/runs/[id]/again">) => {+export async function POST(_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) {- rethrowAccess(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 51f371d9..252a7c5c 100644--- a/src/app/api/marketing/runs/[id]/compose/route.ts+++ b/src/app/api/marketing/runs/[id]/compose/route.ts@@ -1,7 +1,5 @@import { z } from "zod";import { failure, readBody, saveRunComposite } from "@/server/marketing";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Body = z.object({url: z.string().startsWith("/api/files/"),@@ -14,14 +12,13 @@ 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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/marketing/runs/[id]/compose">) => {+export async function POST(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;try {return Response.json(saveRunComposite(id, body), { status: 201 });} catch (e) {- rethrowAccess(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 bbacef14..bac88f6b 100644--- a/src/app/api/marketing/runs/[id]/route.ts+++ b/src/app/api/marketing/runs/[id]/route.ts@@ -1,16 +1,15 @@import { connection } from "next/server";import { deleteRun, getRun } from "@/server/marketing";-import { handler } from "@/server/access/route";-export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/marketing/runs/[id]">) => {+export async function GET(_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 const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/marketing/runs/[id]">) => {+export async function DELETE(_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 5ce1deae..22f5d092 100644--- a/src/app/api/marketing/runs/route.ts+++ b/src/app/api/marketing/runs/route.ts@@ -1,28 +1,25 @@import { connection } from "next/server";import { z } from "zod";import { failure, listRuns, MarketingBody, readBody, runMarketing } from "@/server/marketing";-import { rethrowAccess } from "@/server/access/errors";-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 const GET = handler({ access: "signed-in" }, async (request: Request) => {+export async function GET(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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(request: Request) {const body = await readBody(request, MarketingBody);if (body instanceof Response) return body;try {return Response.json(await runMarketing(body), { status: 201 });} catch (e) {- rethrowAccess(e);return failure(e);}-});+}diff --git a/src/app/api/marketing/script/route.ts b/src/app/api/marketing/script/route.tsindex 153c7723..031195ef 100644--- a/src/app/api/marketing/script/route.ts+++ b/src/app/api/marketing/script/route.ts@@ -1,7 +1,5 @@import { z } from "zod";import { clickToAdScript, failure, readBody } from "@/server/marketing";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Body = z.object({engine: z.enum(["cloud", "open"]),@@ -12,13 +10,12 @@ const Body = z.object({});/** Write a Click to Ad voiceover script to review (Auto, or with custom instructions). */-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(request: Request) {const body = await readBody(request, Body, "Pick a product and a style");if (body instanceof Response) return body;try {return Response.json(await clickToAdScript(body));} catch (e) {- rethrowAccess(e);return failure(e);}-});+}diff --git a/src/app/api/mcp/route.ts b/src/app/api/mcp/route.tsindex d4afceac..08ce06cf 100644--- a/src/app/api/mcp/route.ts+++ b/src/app/api/mcp/route.ts@@ -1,15 +1,10 @@import { handleMcp } from "@/server/mcp";-import { currentActor } from "@/server/access/actor";-import { handler, type TokenScope } 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_…`.- * Every token scope may call it: a Read-only token is offered the read tools only (handleMcp).*/-const READ_AND_UP: TokenScope[] = ["read", "generate", "admin"];--export const POST = handler({ access: "signed-in", scopes: READ_AND_UP }, async (request: Request) => {+export async function POST(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");@@ -19,16 +14,15 @@ export const POST = handler({ access: "signed-in", scopes: READ_AND_UP }, asyncconst 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 });- // Tools run as the token's (or session's) person.- const res = await handleMcp(body, currentActor());+ const res = await handleMcp(body);return res ? Response.json(res) : new Response(null, { status: 202 });-});+}/** No server-initiated stream: this server only answers requests. */-export const GET = handler({ access: "signed-in", scopes: READ_AND_UP }, () => {+export function GET() {return new Response("Method Not Allowed", { status: 405, headers: { Allow: "POST" } });-});+}-export const DELETE = handler({ access: "signed-in", scopes: READ_AND_UP }, () => {+export function DELETE() {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 fdddc8f4..7899918b 100644--- a/src/app/api/media/probe/route.ts+++ b/src/app/api/media/probe/route.ts@@ -1,15 +1,14 @@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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(request: Request) {return handle(async () => {const { url } = await body(request, z.object({ url: z.string().startsWith("/api/files/").max(500) }), "Upload the clip first");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 c4d55c13..3f2dc7f1 100644--- a/src/app/api/mixed-media/estimate/route.ts+++ b/src/app/api/mixed-media/estimate/route.ts@@ -1,11 +1,10 @@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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 1e06d2e6..39a4381d 100644--- a/src/app/api/mixed-media/preview/route.ts+++ b/src/app/api/mixed-media/preview/route.ts@@ -1,11 +1,10 @@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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 4a7734e4..4a11a714 100644--- a/src/app/api/mixed-media/progress/route.ts+++ b/src/app/api/mixed-media/progress/route.ts@@ -1,13 +1,12 @@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 const GET = handler({ access: "signed-in" }, async (request: Request) => {+export async function GET(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 4d0da24a..329d66e5 100644--- a/src/app/api/mixed-media/retry/route.ts+++ b/src/app/api/mixed-media/retry/route.ts@@ -1,12 +1,11 @@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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 c1e6e071..1b02db46 100644--- a/src/app/api/mixed-media/route.ts+++ b/src/app/api/mixed-media/route.ts@@ -1,13 +1,12 @@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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 4b108e3a..d3349ba3 100644--- a/src/app/api/models/route.ts+++ b/src/app/api/models/route.ts@@ -10,7 +10,6 @@ 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()));@@ -52,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 const GET = handler({ access: "signed-in" }, async (request: Request) => {+export async function GET(request: Request) {await connection();const p = new URL(request.url).searchParams;const kind = p.get("kind") || undefined;@@ -83,4 +82,4 @@ export const GET = handler({ access: "signed-in" }, async (request: Request) =>return { ...info, price: rowPrice(info, now), connected: connected(m), runs: runsAs(m, demoMode) };});return Response.json({ engineMode: mode, demoMode, defaults, items });-});+}diff --git a/src/app/api/moodboards/[id]/retry/route.ts b/src/app/api/moodboards/[id]/retry/route.tsindex 78778db8..414670be 100644--- a/src/app/api/moodboards/[id]/retry/route.ts+++ b/src/app/api/moodboards/[id]/retry/route.ts@@ -1,18 +1,15 @@import { z } from "zod";import { retryMoodboard } from "@/server/moodboards";-import { rethrowAccess } from "@/server/access/errors";-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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/moodboards/[id]/retry">) => {+export async function POST(request: Request, ctx: RouteContext<"/api/moodboards/[id]/retry">) {const { id } = await ctx.params;const parsed = Body.safeParse(await request.json().catch(() => ({})));try {return Response.json(retryMoodboard(id, parsed.success ? parsed.data.engine : undefined));} catch (e) {- rethrowAccess(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 8497a298..a20a8950 100644--- a/src/app/api/moodboards/[id]/route.ts+++ b/src/app/api/moodboards/[id]/route.ts@@ -1,31 +1,28 @@import { connection } from "next/server";import { z } from "zod";import { deleteMoodboard, getMoodboard, renameMoodboard } from "@/server/moodboards";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Patch = z.object({ name: z.string().max(200) });-export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/moodboards/[id]">) => {+export async function GET(_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 const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/moodboards/[id]">) => {+export async function PATCH(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 });try {return Response.json(renameMoodboard(id, parsed.data.name));} catch (e) {- rethrowAccess(e);return Response.json({ error: (e as Error).message }, { status: /not found/i.test((e as Error).message) ? 404 : 400 });}-});+}-export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/moodboards/[id]">) => {+export async function DELETE(_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 1ab3fd94..12e4da7e 100644--- a/src/app/api/moodboards/[id]/train/route.ts+++ b/src/app/api/moodboards/[id]/train/route.ts@@ -1,25 +1,22 @@import { connection } from "next/server";import { z } from "zod";import { moodboardTrainingTargets, trainMoodboard } from "@/server/moodboards";-import { rethrowAccess } from "@/server/access/errors";-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 const GET = handler({ access: "signed-in" }, async () => {+export async function GET() {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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/moodboards/[id]/train">) => {+export async function POST(request: Request, ctx: RouteContext<"/api/moodboards/[id]/train">) {const { id } = await ctx.params;const parsed = Body.safeParse(await request.json().catch(() => null));try {return Response.json(trainMoodboard(id, parsed.success ? parsed.data?.target : undefined), { status: 202 });} catch (e) {- rethrowAccess(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 a5e6497b..f9d03769 100644--- a/src/app/api/moodboards/route.ts+++ b/src/app/api/moodboards/route.ts@@ -1,8 +1,6 @@import { connection } from "next/server";import { z } from "zod";import { createMoodboard, curatedMoodboards, listMoodboards } from "@/server/moodboards";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Body = z.object({name: z.string().max(200),@@ -12,18 +10,17 @@ const Body = z.object({});/** Your moodboards (each one's status follows its cover job) and Soul 2.0's curated looks. */-export const GET = handler({ access: "signed-in" }, async () => {+export async function GET() {await connection();return Response.json({ items: listMoodboards(), curated: curatedMoodboards() });-});+}-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 {return Response.json(createMoodboard(parsed.data), { status: 201 });} catch (e) {- rethrowAccess(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 0dbf8965..141b1b03 100644--- a/src/app/api/palettes/[id]/route.ts+++ b/src/app/api/palettes/[id]/route.ts@@ -1,28 +1,24 @@import { z } from "zod";import { deletePalette, renamePalette } from "@/server/palettes";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Patch = z.object({ name: z.string().trim().min(1).max(60) });-export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/palettes/[id]">) => {+export async function PATCH(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 });try {return Response.json(renamePalette(id, parsed.data.name));} catch (e) {- rethrowAccess(e);return Response.json({ error: (e as Error).message }, { status: /not found/i.test((e as Error).message) ? 404 : 400 });}-});+}-export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/palettes/[id]">) => {+export async function DELETE(_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) {- rethrowAccess(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 b39b2a53..53931544 100644--- a/src/app/api/palettes/lock/route.ts+++ b/src/app/api/palettes/lock/route.ts@@ -1,7 +1,5 @@import { z } from "zod";import { createLockedRun, SignatureSchema } from "@/server/palettes";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Hex = z.string().regex(/^#?[0-9a-fA-F]{6}$/);@@ -35,14 +33,13 @@ 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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 {const { items } = createLockedRun(parsed.data.request as Parameters<typeof createLockedRun>[0], parsed.data.colors, parsed.data.strength);return Response.json({ items }, { status: 201 });} catch (e) {- rethrowAccess(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 c2234e6c..d647574e 100644--- a/src/app/api/palettes/route.ts+++ b/src/app/api/palettes/route.ts@@ -1,8 +1,6 @@import { connection } from "next/server";import { z } from "zod";import { createPalette, listPalettes, signatureCaps } from "@/server/palettes";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Body = z.object({name: z.string().trim().min(1).max(60),@@ -13,18 +11,17 @@ const Body = z.object({});/** Your colour signatures and the 50 built-in palettes, plus which models take a palette natively. */-export const GET = handler({ access: "signed-in" }, async () => {+export async function GET() {await connection();return Response.json({ items: listPalettes(), caps: signatureCaps() });-});+}-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 {return Response.json(createPalette(parsed.data), { status: 201 });} catch (e) {- rethrowAccess(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 f0d66e14..339a659b 100644--- a/src/app/api/photodump/character/route.ts+++ b/src/app/api/photodump/character/route.ts@@ -1,7 +1,5 @@import { z } from "zod";import { createSheet, previewSheet, type SheetRun } from "@/server/photodump";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Engine = z.enum(["cloud", "open"]);@@ -34,7 +32,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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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,7 +41,6 @@ export const POST = handler({ access: "signed-in" }, async (request: Request) =>try {return Response.json(createSheet(input), { status: 201 });} catch (e) {- rethrowAccess(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 ca56a97b..ebeebd7d 100644--- a/src/app/api/photodump/fashion/route.ts+++ b/src/app/api/photodump/fashion/route.ts@@ -1,7 +1,5 @@import { z } from "zod";import { createFashion, previewFashion, type FashionRun } from "@/server/photodump";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const File = z.string().startsWith("/api/files/");const Engine = z.enum(["cloud", "open"]);@@ -16,7 +14,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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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,7 +22,6 @@ export const POST = handler({ access: "signed-in" }, async (request: Request) =>try {return Response.json(createFashion(input), { status: 201 });} catch (e) {- rethrowAccess(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 0f768fbf..3df0c708 100644--- a/src/app/api/photodump/packs/[id]/route.ts+++ b/src/app/api/photodump/packs/[id]/route.ts@@ -1,7 +1,6 @@import { deleteUserPack } from "@/server/photodump";-import { handler } from "@/server/access/route";-export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/photodump/packs/[id]">) => {+export async function DELETE(_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 4a6a8930..b37fcde7 100644--- a/src/app/api/photodump/packs/route.ts+++ b/src/app/api/photodump/packs/route.ts@@ -1,24 +1,21 @@import { connection } from "next/server";import { z } from "zod";import { createUserPack, listUserPacks } from "@/server/photodump";-import { rethrowAccess } from "@/server/access/errors";-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 const GET = handler({ access: "signed-in" }, async () => {+export async function GET() {await connection();return Response.json({ packs: listUserPacks() });-});+}/** Create a pack from up to 15 reference photos: each becomes one photo of the dump. */-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 {return Response.json(createUserPack(parsed.data), { status: 201 });} catch (e) {- rethrowAccess(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 19217314..a375ecac 100644--- a/src/app/api/photodump/retry/route.ts+++ b/src/app/api/photodump/retry/route.ts@@ -1,7 +1,5 @@import { z } from "zod";import { retryPhoto } from "@/server/photodump";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Body = z.object({ id: z.string().min(1).max(40) });@@ -9,13 +7,12 @@ 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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 {return Response.json({ items: retryPhoto(parsed.data.id) }, { status: 201 });} catch (e) {- rethrowAccess(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 417c39b3..5ca3d5a9 100644--- a/src/app/api/photodump/route.ts+++ b/src/app/api/photodump/route.ts@@ -1,8 +1,6 @@import { connection } from "next/server";import { z } from "zod";import { createPhotodump, listUserPacks, previewPhotodump } from "@/server/photodump";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Body = z.object({@@ -16,23 +14,22 @@ 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 const GET = handler({ access: "signed-in" }, async () => {+export async function GET() {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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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));try {return Response.json(createPhotodump(parsed.data), { status: 201 });} catch (e) {- rethrowAccess(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 e526169d..a6764d03 100644--- a/src/app/api/products/[id]/route.ts+++ b/src/app/api/products/[id]/route.ts@@ -1,17 +1,15 @@import { connection } from "next/server";import { deleteProduct, getProduct, ProductFields, updateProduct } from "@/server/brand";import { failure, readBody } from "@/server/marketing";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";-export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/products/[id]">) => {+export async function GET(_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 const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/products/[id]">) => {+export async function PATCH(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,12 +17,11 @@ export const PATCH = handler({ access: "signed-in" }, async (request: Request, cconst p = updateProduct(id, body);return p ? Response.json(p) : Response.json({ error: "Not found" }, { status: 404 });} catch (e) {- rethrowAccess(e);return failure(e);}-});+}-export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/products/[id]">) => {+export async function DELETE(_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 44e8551e..daceff9f 100644--- a/src/app/api/products/read/route.ts+++ b/src/app/api/products/read/route.ts@@ -1,8 +1,6 @@import { z } from "zod";import { readProductLink } from "@/server/brand";import { failure, readBody } from "@/server/marketing";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";const Body = z.object({url: z.string().trim().min(1).max(600),@@ -14,14 +12,13 @@ const Body = z.object({});/** Add product(s) from a link: names, descriptions, prices and pictures read from the page. */-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(request: Request) {const body = await readBody(request, Body, "Use a valid product link.");if (body instanceof Response) return body;try {const r = await readProductLink(body);return Response.json(r, { status: r.products.length ? 201 : 200 });} catch (e) {- rethrowAccess(e);return failure(e);}-});+}diff --git a/src/app/api/products/route.ts b/src/app/api/products/route.tsindex 17432d44..b21c518e 100644--- a/src/app/api/products/route.ts+++ b/src/app/api/products/route.ts@@ -2,25 +2,22 @@ import { connection } from "next/server";import { z } from "zod";import { createProduct, listProducts, ProductFields } from "@/server/brand";import { failure, readBody } from "@/server/marketing";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";/** Products: all, a brand's (`?brand=<id>`) or the unassigned ones (`?brand=none`). */-export const GET = handler({ access: "signed-in" }, async (request: Request) => {+export async function GET(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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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;try {return Response.json(createProduct({ ...input, price: input.price ?? null }, { force }), { status: 201 });} catch (e) {- rethrowAccess(e);return failure(e);}-});+}diff --git a/src/app/api/providers/test/route.ts b/src/app/api/providers/test/route.tsindex affc3d2d..59206797 100644--- a/src/app/api/providers/test/route.ts+++ b/src/app/api/providers/test/route.ts@@ -3,8 +3,6 @@ import { testCivitaiKey } from "@/server/loras";import { testAiToolkit } from "@/server/training";import { PROVIDERS } from "@/server/providers";import { validateSetting, withCandidates, type SettingName } from "@/server/settings";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";/*** Test a provider's connection. With `value` (the provider's main setting) or `values` (by setting@@ -13,7 +11,7 @@ import { handler } from "@/server/access/route";* 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 const POST = handler({ access: "perm:install.settings" }, async (request: Request) => {+export async function POST(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).@@ -24,7 +22,6 @@ export const POST = handler({ access: "perm:install.settings" }, async (request:try {for (const [name, v] of Object.entries(values)) validateSetting(name as SettingName, v);} catch (e) {- rethrowAccess(e);return Response.json({ ok: false, detail: (e as Error).message }, { status: 400 });}const settings: readonly string[] = PROVIDER_SETTINGS[provider];@@ -37,7 +34,6 @@ export const POST = handler({ access: "perm:install.settings" }, async (request:const hint = !res.ok && Object.entries(values).map(([n, v]) => settingProblem(n, v ?? "")).find(Boolean);return Response.json(hint && !res.detail.includes(hint) ? { ...res, detail: `${res.detail} — ${hint}` } : res);} catch (e) {- rethrowAccess(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 e181d598..57e638d1 100644--- a/src/app/api/remove-object/estimate/route.ts+++ b/src/app/api/remove-object/estimate/route.ts@@ -1,11 +1,10 @@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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 2ac3bb4b..d85dc9b0 100644--- a/src/app/api/remove-object/preview/route.ts+++ b/src/app/api/remove-object/preview/route.ts@@ -1,12 +1,11 @@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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 509d116e..d172ad22 100644--- a/src/app/api/remove-object/route.ts+++ b/src/app/api/remove-object/route.ts@@ -1,13 +1,12 @@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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 d212ebb8..85bab563 100644--- a/src/app/api/search-index/route.ts+++ b/src/app/api/search-index/route.ts@@ -1,10 +1,9 @@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 const GET = handler({ access: "signed-in" }, async () => {+export async function GET() {return Response.json(paletteIndex());-});+}diff --git a/src/app/api/settings/models/route.ts b/src/app/api/settings/models/route.tsindex 2f6663a4..cdf1ee3c 100644--- a/src/app/api/settings/models/route.ts+++ b/src/app/api/settings/models/route.ts@@ -2,17 +2,16 @@ 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 const GET = handler({ access: "signed-in" }, async () => {+export async function GET() {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;@@ -35,7 +34,7 @@ function readChange(v: unknown): AccessChange | string {return { kind, id, on: c.on };}-export const PUT = handler({ access: "perm:install.settings" }, async (request: Request) => {+export async function PUT(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);@@ -43,4 +42,4 @@ export const PUT = handler({ access: "perm:install.settings" }, async (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 91fd6ac1..bf5ff8f5 100644--- a/src/app/api/settings/route.ts+++ b/src/app/api/settings/route.ts@@ -1,22 +1,19 @@import { connection } from "next/server";import { publicSettings, setSetting, SETTINGS, validateSetting, type SettingName } from "@/server/settings";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";-export const GET = handler({ access: "signed-in" }, async () => {+export async function GET() {await connection();return Response.json({ settings: publicSettings() });-});+}-export const PUT = handler({ access: "perm:install.settings" }, async (request: Request) => {+export async function PUT(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 {entries.forEach(([name, value]) => validateSetting(name, value.trim()));} catch (e) {- rethrowAccess(e);return Response.json({ error: (e as Error).message }, { status: 400 });}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 7190966a..9b34879e 100644--- a/src/app/api/shares/[id]/route.ts+++ b/src/app/api/shares/[id]/route.ts@@ -2,7 +2,6 @@ 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(),@@ -16,15 +15,15 @@ const Patch = z.object({newLink: z.literal(true).optional(),});-export const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/shares/[id]">) => {+export async function GET(_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 const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/shares/[id]">) => {+export async function PATCH(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 });@@ -35,10 +34,10 @@ export const PATCH = handler({ access: "signed-in" }, async (request: Request, cif (e instanceof ShareError) return Response.json({ error: e.message }, { status: e.status });throw e;}-});+}/** Revoke: the link stops working at once. */-export const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/shares/[id]">) => {+export async function DELETE(_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 5257e4ff..89ddc55e 100644--- a/src/app/api/shares/route.ts+++ b/src/app/api/shares/route.ts@@ -3,7 +3,6 @@ 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[]]),@@ -19,16 +18,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 const GET = handler({ access: "signed-in" }, async () => {+export async function GET() {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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 {@@ -38,4 +37,4 @@ export const POST = handler({ access: "signed-in" }, async (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 595cac19..e9937d52 100644--- a/src/app/api/shorts/estimate/route.ts+++ b/src/app/api/shorts/estimate/route.ts@@ -1,11 +1,10 @@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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 acc46cac..374cde8b 100644--- a/src/app/api/shorts/presets/[id]/route.ts+++ b/src/app/api/shorts/presets/[id]/route.ts@@ -1,19 +1,18 @@import { deleteCustomPreset, ShortsError, updateCustomPreset } from "@/server/shorts";import { PresetPatchSchema, body, handle } from "@/server/shorts-schemas";-import { handler } from "@/server/access/route";-export const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/shorts/presets/[id]">) => {+export async function PATCH(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 const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/shorts/presets/[id]">) => {+export async function DELETE(_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 76c53578..1461326f 100644--- a/src/app/api/shorts/presets/route.ts+++ b/src/app/api/shorts/presets/route.ts@@ -1,18 +1,17 @@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 const GET = handler({ access: "signed-in" }, async () => {+export async function GET() {await connection();return handle(() => Response.json({ items: listCustomPresets() }));-});+}/** Create a preset from up to 10 reference images. */-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 466a7950..2c10ced2 100644--- a/src/app/api/shorts/probe/route.ts+++ b/src/app/api/shorts/probe/route.ts@@ -1,12 +1,11 @@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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(request: Request) {return handle(async () => {const { url } = await body(request, z.object({ url: z.string().startsWith("/api/files/").max(500) }), "Upload the clip first");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 3e6be8c1..1cda7a0d 100644--- a/src/app/api/shorts/sessions/[id]/route.ts+++ b/src/app/api/shorts/sessions/[id]/route.ts@@ -2,31 +2,30 @@ 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 const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/shorts/sessions/[id]">) => {+export async function GET(_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 const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]">) => {+export async function PATCH(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 const DELETE = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]">) => {+export async function DELETE(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 32af5059..7515b42f 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,10 +1,9 @@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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]/segments/[index]/primary">) => {+export async function POST(request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]/segments/[index]/primary">) {return handle(async () => {const { id, index } = await ctx.params;const i = Number(index);@@ -12,4 +11,4 @@ export const POST = handler({ access: "signed-in" }, async (request: Request, ctconst { 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 866f3e1f..8f22022f 100644--- a/src/app/api/shorts/sessions/[id]/segments/[index]/route.ts+++ b/src/app/api/shorts/sessions/[id]/segments/[index]/route.ts@@ -1,9 +1,8 @@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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]/segments/[index]">) => {+export async function POST(request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]/segments/[index]">) {return handle(async () => {const { id, index } = await ctx.params;const i = Number(index);@@ -11,4 +10,4 @@ export const POST = handler({ access: "signed-in" }, async (request: Request, ctconst { 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 8f0a1a28..cb2861f3 100644--- a/src/app/api/shorts/sessions/[id]/stitch/route.ts+++ b/src/app/api/shorts/sessions/[id]/stitch/route.ts@@ -1,12 +1,11 @@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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]/stitch">) => {+export async function POST(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 99ff5468..35ce9261 100644--- a/src/app/api/shorts/sessions/route.ts+++ b/src/app/api/shorts/sessions/route.ts@@ -1,19 +1,18 @@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 const GET = handler({ access: "signed-in" }, async () => {+export async function GET() {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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 9f32acd4..5e51ffb4 100644--- a/src/app/api/status/route.ts+++ b/src/app/api/status/route.ts@@ -4,10 +4,9 @@ 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 const GET = handler({ access: "signed-in" }, async () => {+export async function GET() {await connection();const comfy = await probeComfy(true);const ram = comfy ? comfyRam() : undefined;@@ -36,4 +35,4 @@ export const GET = handler({ access: "signed-in" }, async () => {// 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 9a22eb3b..d1d659a0 100644--- a/src/app/api/storyboards/[id]/film/route.ts+++ b/src/app/api/storyboards/[id]/film/route.ts@@ -1,18 +1,15 @@import { z } from "zod";import { createStoryboardFilm } from "@/server/storyboard";-import { rethrowAccess } from "@/server/access/errors";-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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/storyboards/[id]/film">) => {+export async function POST(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 {return Response.json(createStoryboardFilm((await ctx.params).id, parsed.data), { status: 201 });} catch (e) {- rethrowAccess(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 6637fa41..d5ebde86 100644--- a/src/app/api/storyboards/estimate/route.ts+++ b/src/app/api/storyboards/estimate/route.ts@@ -1,15 +1,12 @@import { estimateStoryboard, StoryboardBodySchema } from "@/server/storyboard";-import { rethrowAccess } from "@/server/access/errors";-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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 {return Response.json(estimateStoryboard(parsed.data));} catch (e) {- rethrowAccess(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 2cefe884..016e7185 100644--- a/src/app/api/storyboards/route.ts+++ b/src/app/api/storyboards/route.ts@@ -1,15 +1,12 @@import { createStoryboard, StoryboardBodySchema } from "@/server/storyboard";-import { rethrowAccess } from "@/server/access/errors";-import { handler } from "@/server/access/route";/** Popcorn-style storyboard: consecutive frames, each made from the previous one. */-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 {return Response.json(await createStoryboard(parsed.data), { status: 201 });} catch (e) {- rethrowAccess(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 081adf5f..0c2a888f 100644--- a/src/app/api/swap-studio/projects/[id]/anchors/route.ts+++ b/src/app/api/swap-studio/projects/[id]/anchors/route.ts@@ -1,11 +1,10 @@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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/anchors">) => {+export async function POST(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 3f82f3f5..772dd456 100644--- a/src/app/api/swap-studio/projects/[id]/assemble/route.ts+++ b/src/app/api/swap-studio/projects/[id]/assemble/route.ts@@ -1,14 +1,13 @@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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/assemble">) => {+export async function POST(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 58075198..5405e038 100644--- a/src/app/api/swap-studio/projects/[id]/clips/route.ts+++ b/src/app/api/swap-studio/projects/[id]/clips/route.ts@@ -1,11 +1,10 @@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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/clips">) => {+export async function POST(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 67bac14d..7fafdabf 100644--- a/src/app/api/swap-studio/projects/[id]/decisions/route.ts+++ b/src/app/api/swap-studio/projects/[id]/decisions/route.ts@@ -1,14 +1,13 @@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 const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/decisions">) => {+export async function GET(_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 ee3e7286..143df68c 100644--- a/src/app/api/swap-studio/projects/[id]/estimate/route.ts+++ b/src/app/api/swap-studio/projects/[id]/estimate/route.ts@@ -1,10 +1,9 @@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 const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/estimate">) => {+export async function GET(_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 dba925ee..af0d49ee 100644--- a/src/app/api/swap-studio/projects/[id]/masks/route.ts+++ b/src/app/api/swap-studio/projects/[id]/masks/route.ts@@ -1,11 +1,10 @@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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/masks">) => {+export async function POST(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 a27159c1..edc21ba2 100644--- a/src/app/api/swap-studio/projects/[id]/prepare/route.ts+++ b/src/app/api/swap-studio/projects/[id]/prepare/route.ts@@ -1,14 +1,13 @@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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/prepare">) => {+export async function POST(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 c4018311..52b12b12 100644--- a/src/app/api/swap-studio/projects/[id]/queue/route.ts+++ b/src/app/api/swap-studio/projects/[id]/queue/route.ts@@ -1,11 +1,10 @@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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/queue">) => {+export async function POST(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 504d8147..c3c39f5f 100644--- a/src/app/api/swap-studio/projects/[id]/route.ts+++ b/src/app/api/swap-studio/projects/[id]/route.ts@@ -1,26 +1,25 @@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 const GET = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]">) => {+export async function GET(_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 const PATCH = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]">) => {+export async function PATCH(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 const DELETE = handler({ access: "signed-in" }, async (_req: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]">) => {+export async function DELETE(_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 752c5f55..190a02fe 100644--- a/src/app/api/swap-studio/projects/[id]/stop/route.ts+++ b/src/app/api/swap-studio/projects/[id]/stop/route.ts@@ -1,11 +1,10 @@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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/stop">) => {+export async function POST(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 3bec1cb3..0036cada 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,11 +1,10 @@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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/takes/stop">) => {+export async function POST(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 7d33e536..c8820b0e 100644--- a/src/app/api/swap-studio/projects/[id]/transcribe/route.ts+++ b/src/app/api/swap-studio/projects/[id]/transcribe/route.ts@@ -1,14 +1,13 @@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 const POST = handler({ access: "signed-in" }, async (request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/transcribe">) => {+export async function POST(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 41860840..deedcc01 100644--- a/src/app/api/swap-studio/projects/route.ts+++ b/src/app/api/swap-studio/projects/route.ts@@ -1,15 +1,14 @@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 const GET = handler({ access: "signed-in" }, async () => {+export async function GET() {await connection();return handle(() => Response.json({ items: listProjects() }));-});+}/** A new project: a name, the engine, and (optionally) the character. */-export const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 b8784837..851e7978 100644--- a/src/app/api/uploads/route.ts+++ b/src/app/api/uploads/route.ts@@ -1,12 +1,11 @@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 const POST = handler({ access: "signed-in" }, async (request: Request) => {+export async function POST(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 });@@ -22,4 +21,4 @@ export const POST = handler({ access: "signed-in" }, async (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 619b6d83..4ac2b0f0 100644--- a/src/app/s/[token]/f/[...path]/route.ts+++ b/src/app/s/[token]/f/[...path]/route.ts@@ -2,7 +2,6 @@ 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" };@@ -12,11 +11,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 const GET = handler({ access: "public" }, async (request: Request, ctx: RouteContext<"/s/[token]/f/[...path]">) => {+export async function GET(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/src/proxy.ts b/src/proxy.tsindex 78d0e81f..dba67ef8 100644--- a/src/proxy.ts+++ b/src/proxy.ts@@ -3,7 +3,7 @@ import { APPS } from "@/lib/catalog/apps";import { recordForPath, unknownHubMode } from "@/lib/record-pages";import { countsAsView, SHARE_VIEW_HEADER, shareRoute } from "@/lib/share";import { clientIp, crossSite, hostAllowed, LoginGuard } from "@/server/auth";-import { CLIENT_IP_HEADER, refreshSession, resolvePrincipal } from "@/server/identity/principal";+import { refreshSession, resolvePrincipal } from "@/server/identity/principal";import { refusal } from "@/server/identity/refusals";import { signInRequired } from "@/server/mode";import { recordExists } from "@/server/records";@@ -37,7 +37,7 @@ const crossSiteExempt = (pathname: string) => CROSS_SITE_EXEMPT.some((r) => ruleconst noStore = (pathname: string) => NO_STORE.some((r) => ruleMatches(r, pathname));/** The header Better Auth reads the client's address from; only this proxy may write it. */-export { CLIENT_IP_HEADER };+export const CLIENT_IP_HEADER = "x-fuobe-client-ip";/*** The request headers handed on: any x-fuobe-client-ip a client sent is dropped, and one is written only when adiff --git a/src/server/access/actor.ts b/src/server/access/actor.tsdeleted file mode 100644index ab948abc..00000000--- a/src/server/access/actor.ts+++ /dev/null@@ -1,96 +0,0 @@-import "server-only";-import { AsyncLocalStorage } from "node:async_hooks";-import type { Actor } from "../identity/principal";--/**- * Who is acting, wherever the code runs (docs/research/accounts-8.md §7.1, §7.11). A request scope rides on- * AsyncLocalStorage: route handlers open one through handler() (src/server/access/route.ts), runners open one per row- * with runAs(row owner), and housekeeping runs asSystem. Server modules ask currentActor(), which throws when nothing- * opened a scope: code that acts for nobody is a bug, never a silent "the owner".- *- * This module imports nothing that touches the database, so the test setup (tests/setup/actor.ts) can load it before- * a test file has chosen its data folder.- */--export type { Actor };--/** What a request (or a runner's turn) knows about who is acting and from where. */-export interface RequestScope {- /** Null on a public route answered for nobody (a share file, the sign-in form). */- actor: Actor | null;- ip?: string | null;- userAgent?: string | null;- method?: string;- path?: string;- /** The route's pattern (`/api/generations/[id]`): the path with each dynamic segment named, for rate-limited denials. */- route?: string;-}--declare global {- var __fuobeAccessScope: AsyncLocalStorage<RequestScope> | undefined;-}--/** One store per process, shared by every bundle that loads this module (instrumentation and route handlers). */-const store = (): AsyncLocalStorage<RequestScope> => (globalThis.__fuobeAccessScope ??= new AsyncLocalStorage<RequestScope>());--/** The local owner: "Just me on this computer", and the person every test acts as unless it says otherwise. */-export const LOCAL_OWNER: Actor = Object.freeze({ userId: "u_owner", role: "owner", via: "local", scopes: ["full"] }) as Actor;--/** The server itself: housekeeping, sweeps and boot work that belong to no one. */-export const SYSTEM: Actor = Object.freeze({ userId: "system", role: "system", via: "system", scopes: ["full"] }) as Actor;--export class NoActorError extends Error {- constructor() {- super("No one is acting here: wrap this in handler(), runAs() or asSystem()");- this.name = "NoActorError";- }-}--/** The scope this code runs in, if any. */-export function requestScope(): RequestScope | undefined {- return store().getStore();-}--/** Who is acting, or null (no scope, or a public route answered for nobody). */-export function maybeActor(): Actor | null {- return store().getStore()?.actor ?? null;-}--/** Who is acting. Throws when no one is: every route, runner and sweep opens a scope first. */-export function currentActor(): Actor {- const actor = maybeActor();- if (!actor) throw new NoActorError();- return actor;-}--/** Run `fn` inside a scope (handler() opens one per request). */-export function withScope<T>(scope: RequestScope, fn: () => T): T {- return store().run(scope, fn);-}--/**- * Run `fn` as `actor`: a runner working on a row its owner started, an after() continuation, Assist acting for the- * chat's author. Timers and promises started inside keep the actor (AsyncLocalStorage follows them).- */-export function runAs<T>(actor: Actor, fn: () => T): T {- return store().run({ actor }, fn);-}--/** Run `fn` as the server itself: timers that sweep everyone's rows start here, then act per row with runAs. */-export function asSystem<T>(fn: () => T): T {- return store().run({ actor: SYSTEM }, fn);-}--/**- * The actor now, as a function that runs later work as them: `const resume = captureActor(); after(() => resume(work))`.- * Explicit, so a continuation never depends on where the work happens to be scheduled from.- */-export function captureActor(): <T>(fn: () => T) => T {- const actor = currentActor();- return (fn) => runAs(actor, fn);-}--/** For the test harness only: make the rest of this synchronous run (and what it starts) act as `actor`. */-export function enterAs(actor: Actor | null): void {- store().enterWith({ actor });-}diff --git a/src/server/access/audit.ts b/src/server/access/audit.tsdeleted file mode 100644index c8930ad8..00000000--- a/src/server/access/audit.ts+++ /dev/null@@ -1,181 +0,0 @@-import "server-only";-import { appendAudit, verifyAuditChain, type AuditChainCheck } from "../identity/audit-log";-import { SETTINGS, type SettingDef } from "../settings";-import { requestScope } from "./actor";--/**- * The audit log as the rest of Fuobe writes it (docs/research/accounts-8.md §7.14): `audit(action, target, meta)`- * takes who acted, from which address and with which browser from the request scope, and appends a row to the- * hash-chained, append-only `audit_log` (src/server/identity/audit-log.ts). Core events: auth.*, token.*, people.*,- * team.*, install.*, keys.* (setting names and masked prefixes only), limits.*, content.share|move|grant, `denied`- * (every 403) and `denied.hidden` (404s for records the actor may not see).- *- * Denials nobody signed in can cause (a public route's 403, a turned-off person's credentials) and hidden-record 404s- * are written at most once a minute per person (or address) and route; the next entry says how many more there were- * (`more`), so a script can't grow the log as fast as it can send requests.- *- * Secrets never reach the log: meta fields named like one (password, secret, token, a key: apiKey, falKey, "fal.key"…),- * values shaped like one (an API key, a bearer token), and the value of a secret setting are replaced before the row- * is written, whatever the caller passed, in nested objects and lists too.- */--export interface AuditTarget {- kind: string;- id?: string | null;-}--// ----------------------------------------------------------------------------// Redaction--const REDACTED = "[redacted]";-const SECRET_NAME = /(pass(word)?|passphrase|secret|token|key|authorization|cookie|credentials?)$/i;-/** Names that look like a secret's but only describe one (a prefix, an id, a count, where it is kept). */-const DESCRIBES = /(prefix|id|ids|name|names|kind|count|at|tokens|mode|source|scope|scopes|set|masked|hint|last4|length)$/i;-/** Values shaped like a credential: Fuobe tokens, provider keys (sk-, r8_, hf_, AIza…), fal's id:secret, a bearer header. */-const SECRET_VALUE = [- /^(fuobe_|sk-|sk_|rk_|pk_live_|r8_|hf_|ghp_|gho_|ghs_|github_pat_|glpat-|xox[abpr]-|AIza|AKIA)[A-Za-z0-9_\-.]{12,}$/,- /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}:[0-9a-f]{20,}$/i,- /^(Bearer|Basic)\s+\S{8,}$/i,-];-/** A masked value ("sk-l••••abcd", "fuobe_ab…") is what the log may keep. */-const MASKED = /••••|…/;--const SETTING_DEFS = Object.entries(SETTINGS) as [string, SettingDef][];-/** Every secret setting, by its name in code and its stored key (falKey, "fal.key"). */-const SECRET_SETTINGS = new Set(SETTING_DEFS.filter(([, d]) => d.secret).flatMap(([name, d]) => [name, d.key]));-/** Every setting's name, which is a name and not a secret even in a field called `key`. */-const SETTING_NAMES = new Set(SETTING_DEFS.flatMap(([name, d]) => [name, d.key]));-/** The fields that carry a setting's value next to its name. */-const VALUE_FIELDS = new Set(["value", "from", "to", "old", "new", "previous", "next", "before", "after"]);--const secretName = (k: string) => SECRET_NAME.test(k) && !DESCRIBES.test(k);-const secretValue = (v: string) => !MASKED.test(v) && SECRET_VALUE.some((re) => re.test(v.trim()));--/** Whether this object (or the entry's target) names a secret setting, so its value fields are secrets too. */-function namesSecretSetting(o: Record<string, unknown>, target?: AuditTarget | null): boolean {- if (target?.kind === "setting" && target.id && SECRET_SETTINGS.has(target.id)) return true;- return ["key", "setting", "name"].some((k) => typeof o[k] === "string" && (SECRET_SETTINGS.has(o[k] as string) || (SECRET_NAME.test(o[k] as string) && !SETTING_NAMES.has(o[k] as string) && !DESCRIBES.test(o[k] as string))));-}--function redactValue(v: unknown, target?: AuditTarget | null): unknown {- if (typeof v === "string") return secretValue(v) ? REDACTED : v;- if (Array.isArray(v)) return v.map((x) => redactValue(x));- if (v && typeof v === "object") return redact(v as Record<string, unknown>, target);- return v;-}--function redact(meta: Record<string, unknown>, target?: AuditTarget | null): Record<string, unknown> {- const secretSetting = namesSecretSetting(meta, target);- const out: Record<string, unknown> = {};- for (const [k, v] of Object.entries(meta)) {- const isString = typeof v === "string" && v !== "";- // A field named like a secret keeps a value that is only a setting's name ("key": "fal.key") or already masked.- if (secretName(k) && isString && !SETTING_NAMES.has(v as string) && !MASKED.test(v as string)) out[k] = REDACTED;- else if (secretName(k) && v && typeof v === "object") out[k] = REDACTED;- else if (secretSetting && VALUE_FIELDS.has(k) && isString && !MASKED.test(v as string)) out[k] = REDACTED;- else out[k] = redactValue(v);- }- return out;-}--// ----------------------------------------------------------------------------// Writing--interface Who {- actorId: string | null;- via: string | null;- meta: Record<string, unknown>;-}--function write(action: string, target: AuditTarget | null | undefined, meta: Record<string, unknown>, who?: Who): void {- const scope = requestScope();- const actor = scope?.actor ?? null;- const by: Who = who ?? {- actorId: actor?.userId ?? null,- via: actor?.via ?? null,- meta: { ...(actor?.impersonatorId && { impersonator: actor.impersonatorId }), ...(actor?.tokenId && { tokenId: actor.tokenId }) },- };- appendAudit({- action,- actorId: by.actorId,- via: by.via,- targetKind: target?.kind ?? null,- targetId: target?.id ?? null,- meta: redact({ ...by.meta, ...meta }, target),- ip: scope?.ip ?? null,- userAgent: scope?.userAgent ?? null,- });-}--/** Append an entry for whoever is acting now (the request's person, a runner's row owner, or the server). */-export function audit(action: string, target?: AuditTarget | null, meta: Record<string, unknown> = {}): void {- write(action, target, meta);-}--// ----------------------------------------------------------------------------// Denials--declare global {- var __fuobeAuditThrottle: Map<string, { at: number; more: number }> | undefined;-}--const THROTTLE_MS = 60_000;--/**- * Whether an entry under `key` may be written now (at most one a minute), and how many were held back since the last- * one. The map forgets keys a minute old once it grows, so it stays small whatever is probed.- */-function throttle(key: string): { write: boolean; more: number } {- const seen = (globalThis.__fuobeAuditThrottle ??= new Map());- const now = Date.now();- const last = seen.get(key);- if (last && now - last.at < THROTTLE_MS) {- last.more++;- return { write: false, more: 0 };- }- if (seen.size > 5000) for (const [k, t] of seen) if (now - t.at >= THROTTLE_MS) seen.delete(k);- seen.set(key, { at: now, more: 0 });- return { write: true, more: last?.more ?? 0 };-}--/** The route a request reached: its path with each dynamic segment named (handler() fills it in), else the path. */-const routeOf = () => {- const scope = requestScope();- return scope?.route ?? scope?.path ?? "";-};--/**- * A 403: what was refused and why (a permission, a token's scope, a code like REAUTH). Every one is written for a- * signed-in person; for nobody (a public route's own 403), at most one a minute per address and route.- */-export function auditDenied(reason: string, meta: Record<string, unknown> = {}): void {- const scope = requestScope();- const base = { method: scope?.method, path: scope?.path, reason, ...meta };- if (scope?.actor) return write("denied", null, base);- const t = throttle(`denied nobody ${scope?.ip ?? "-"} ${scope?.method ?? ""} ${routeOf()}`);- if (t.write) write("denied", null, { ...base, ...(t.more && { more: t.more }) });-}--/**- * A 403 for a person who may not act right now (pending, turned off, dormant) and showed their credentials anyway: who- * they are and why, at most one a minute per person and route.- */-export function auditRefused(userId: string, via: string, code: string): void {- const scope = requestScope();- const t = throttle(`denied ${userId} ${scope?.method ?? ""} ${routeOf()}`);- if (t.write) write("denied", null, { method: scope?.method, path: scope?.path, reason: code, ...(t.more && { more: t.more }) }, { actorId: userId, via, meta: {} });-}--/**- * A 404 for a record that exists but isn't the actor's to see. Logged at most once a minute per person and route (the- * route's pattern, so probing ids can't flood the log); the scoping package calls it through- * NotFoundError({ hidden: true }).- */-export function auditHidden(target?: AuditTarget | null): void {- const scope = requestScope();- const who = scope?.actor?.userId ?? `nobody ${scope?.ip ?? "-"}`;- const t = throttle(`hidden ${who} ${scope?.method ?? ""} ${routeOf()}`);- if (t.write) write("denied.hidden", target, { method: scope?.method, path: scope?.path, ...(t.more && { more: t.more }) });-}--export { verifyAuditChain, type AuditChainCheck };diff --git a/src/server/access/errors.ts b/src/server/access/errors.tsdeleted file mode 100644index d1570327..00000000--- a/src/server/access/errors.ts+++ /dev/null@@ -1,65 +0,0 @@-import "server-only";--/**- * The refusals a route handler answers for (docs/research/accounts-8.md §7.1, §7.4, §7.12): server code throws one and- * handler() turns it into the JSON answer, `{ error, code? }` with its status. Every 403 is audited as `denied`; a- * hidden record (a 404 for something that exists but isn't the actor's to see) as `denied.hidden`, at most once a- * minute per person and route.- */--export class AccessError extends Error {- constructor(- message: string,- readonly status: number,- readonly code?: string,- ) {- super(message);- this.name = new.target.name;- }-}--/** 404: no such thing — or one the actor may not know exists (`hidden`, which is audited). */-export class NotFoundError extends AccessError {- constructor(- message = "Not found",- readonly hidden = false,- ) {- super(message, 404);- }-}--/** 403: the actor is known and may not do this. */-export class ForbiddenError extends AccessError {- constructor(message = "You don't have access to this.", code?: string) {- super(message, 403, code);- }-}--/** 401: nobody (or an invalid token) asking for something that needs a person. */-export class UnauthenticatedError extends AccessError {- constructor(message = "Sign in, or send an API token as Authorization: Bearer fuobe_…", code?: string) {- super(message, 401, code);- }-}--/** 402: a limit or a credit balance stops this run (the meter and plans packages throw it with their line). */-export class PaymentRequiredError extends AccessError {- constructor(message = "This would go over your limit.", code = "LIMIT_REACHED") {- super(message, 402, code);- }-}--/** 403 REAUTH: a sensitive action needs the session confirmed in the last 10 minutes ("Confirm it's you", §7.2). */-export class ReauthRequiredError extends AccessError {- constructor(message = "Confirm it's you to continue.") {- super(message, 403, "REAUTH");- }-}--/**- * For code that catches errors to answer them itself (a route's `catch (e)`, a studio's `handle()`): pass a refusal on- * to handler(), which answers it with its status and audits it. Call it first in the catch block.- */-export function rethrowAccess(e: unknown): void {- if (e instanceof AccessError) throw e;-}diff --git a/src/server/access/gates.ts b/src/server/access/gates.tsdeleted file mode 100644index d036df4c..00000000--- a/src/server/access/gates.ts+++ /dev/null@@ -1,40 +0,0 @@-import "server-only";-import type { Actor } from "./actor";-import { ForbiddenError } from "./errors";--/**- * Gates for actions that cost nothing but still have limits (docs/research/accounts-8.md §7.12): creating an API- * token, a share link, an upload, a team, adding one's own keys. The core registers no checks, so every gate is open- * (a no-op); the entitlements and plans packages register theirs ("Your plan doesn't include share links."). A check- * returns a refusal or null.- */--export type GateKind = "token.create" | "share.create" | "upload" | "team.create" | "keys.own" | (string & {});--export interface GateRefusal {- code: string;- message: string;-}--type GateCheck = (actor: Actor) => GateRefusal | null;--const CHECKS = new Map<string, GateCheck[]>();--export function registerGate(kind: GateKind, check: GateCheck): void {- CHECKS.set(kind, [...(CHECKS.get(kind) ?? []), check]);-}--/** The first refusal for this action, or null when it may go ahead. */-export function gateRefusal(kind: GateKind, actor: Actor): GateRefusal | null {- for (const check of CHECKS.get(kind) ?? []) {- const r = check(actor);- if (r) return r;- }- return null;-}--/** Refuse (a 403 the route handler answers and audits) when a check says no. */-export function gate(kind: GateKind, actor: Actor): void {- const r = gateRefusal(kind, actor);- if (r) throw new ForbiddenError(r.message, r.code);-}diff --git a/src/server/access/permissions.ts b/src/server/access/permissions.tsdeleted file mode 100644index 9182da0e..00000000--- a/src/server/access/permissions.ts+++ /dev/null@@ -1,204 +0,0 @@-import "server-only";-import { db } from "../db";-import { runAs, type Actor } from "./actor";--/**- * Roles and permissions (docs/research/accounts-8.md §7.3). Both are registries: the core registers the install roles- * owner, admin and member and the core permissions; later packages add theirs (the audit viewer adds `auditor` and- * `audit.view` holders, the Platform admin adds `billing`, `moderator` and `support` with `billing.*` and- * `moderation.*`). Routes declare the permission they need (`handler({ access: "perm:install.settings" })`) and never- * test a role name themselves.- *- * Team roles (owner, admin, member shown as Editor, viewer) are answered by effectiveTeamRole() alone, so the clamps- * that come later (view-only seats, view-as) apply everywhere at once.- */--// ----------------------------------------------------------------------------// Permissions--const PERMISSIONS = new Set<string>([- "install.settings",- "install.mode",- "people.view",- "people.manage",- "people.roles",- "usage.view_all",- "limits.manage",- "keys.install",- "teams.create",- "teams.manage_all",- "audit.view",- "data.manage",- "gpu.manage",- "approvals.decide",- "support.view_as",- "credits.adjust",-]);--/** Add a permission (a package's own: `billing.refund`, `moderation.review`…). */-export function registerPermission(name: string): void {- PERMISSIONS.add(name);-}--export const permissionExists = (name: string): boolean => PERMISSIONS.has(name);--export function permissions(): string[] {- return [...PERMISSIONS];-}--// ----------------------------------------------------------------------------// Install roles--export interface RoleDef {- /** Shown in people lists and pickers. */- label: string;- /** Higher outranks lower: who may act on whom (§7.3 target matrix) compares ranks. */- rank: number;- /** Permissions held: exact names, a family (`billing.*`) or everything (`*`). */- grants: string[];-}--const ROLES = new Map<string, RoleDef>([- ["owner", { label: "Owner", rank: 100, grants: ["*"] }],- [- "admin",- {- label: "Admin",- rank: 50,- // Everything an install needs run day to day; the mode, roles, view-as and credit adjustments stay with the owner.- grants: [- "install.settings",- "people.view",- "people.manage",- "usage.view_all",- "limits.manage",- "keys.install",- "teams.create",- "teams.manage_all",- "audit.view",- "data.manage",- "gpu.manage",- "approvals.decide",- ],- },- ],- // Whether members may create teams is an install setting (teams.create), refined by the teams package.- ["member", { label: "Member", rank: 10, grants: [] }],-]);--/** Add or replace an install role (`auditor`, `billing`, `moderator`, `support`). `owner` is fixed. */-export function registerRole(name: string, def: RoleDef): void {- if (name === "owner") throw new Error("The owner role is fixed");- ROLES.set(name, def);-}--export const roleExists = (name: string): boolean => ROLES.has(name);-export const roleDef = (name: string): RoleDef | undefined => ROLES.get(name);--export function roles(): { name: string; def: RoleDef }[] {- return [...ROLES].map(([name, def]) => ({ name, def })).sort((a, b) => b.def.rank - a.def.rank);-}--const grantCovers = (grant: string, permission: string) =>- grant === "*" || grant === permission || (grant.endsWith(".*") && permission.startsWith(grant.slice(0, -1)));--/** Whether an install role holds a permission. Unknown roles hold nothing. */-export function roleCan(role: string, permission: string): boolean {- return (ROLES.get(role)?.grants ?? []).some((g) => grantCovers(g, permission));-}--/**- * Whether the actor may do something that needs `permission`. The server itself (asSystem) may; a view-as session- * may not (it is read-only, §9.5 E5b); a token needs the admin or full scope for any install permission.- */-export function can(actor: Actor | null | undefined, permission: string): boolean {- if (!actor) return false;- if (actor.via === "system") return true;- if (actor.impersonatorId) return false;- if (actor.via === "token" && !actor.scopes.some((s) => s === "full" || s === "admin")) return false;- return roleCan(actor.role, permission);-}--// ----------------------------------------------------------------------------// Team roles--export type TeamRole = "owner" | "admin" | "member" | "viewer";--/** Strongest first. `member` is shown as "Editor". */-export const TEAM_ROLES: readonly TeamRole[] = ["owner", "admin", "member", "viewer"];-export const TEAM_ROLE_LABEL: Record<TeamRole, string> = { owner: "Owner", admin: "Admin", member: "Editor", viewer: "Viewer" };--const teamRank = (r: TeamRole) => TEAM_ROLES.length - TEAM_ROLES.indexOf(r);--/** Whether `role` is at least `min` (an Editor action needs "member"). */-export function teamRoleAtLeast(role: TeamRole | null | undefined, min: TeamRole): boolean {- return !!role && teamRank(role) >= teamRank(min);-}--/**- * Clamps applied after the stored membership, in order: each may lower the role (a view-only seat is a Viewer,- * §9.5 E6), never raise it. Packages register theirs.- */-export type TeamRoleClamp = (actor: Actor, workspaceId: string, role: TeamRole) => TeamRole;-const CLAMPS: TeamRoleClamp[] = [- // View-as is read-only (§9.5 E5b): whoever is looking can't change anything.- (actor, _w, role) => (actor.impersonatorId ? "viewer" : role),-];--export function registerTeamRoleClamp(clamp: TeamRoleClamp): void {- CLAMPS.push(clamp);-}--/**- * The actor's role in a workspace (their personal one, a team, or the install catalog), or null when they aren't a- * member. The only function that answers a team role.- */-export function effectiveTeamRole(actor: Actor, workspaceId: string): TeamRole | null {- if (actor.via === "system") return "owner";- const row = db().prepare("SELECT role FROM workspace_members WHERE workspace_id = ? AND user_id = ?").get(workspaceId, actor.userId) as { role: string } | undefined;- if (!row || !(TEAM_ROLES as readonly string[]).includes(row.role)) return null;- let role = row.role as TeamRole;- for (const clamp of CLAMPS) {- const next = clamp(actor, workspaceId, role);- // A clamp only ever lowers.- if (teamRank(next) < teamRank(role)) role = next;- }- return role;-}--// ----------------------------------------------------------------------------// Acting for a row's owner--/** The words a runner fails a row with when the person who started it was turned off (§7.11). */-export const ACCOUNT_OFF_MESSAGE = "Paused: the account that started this is off.";--export class AccountOffError extends Error {- constructor() {- super(ACCOUNT_OFF_MESSAGE);- this.name = "AccountOffError";- }-}--/** The person every row belongs to until rows record who made them (the scoping package adds created_by). */-export const INSTALL_OWNER_ID = "u_owner";--/** Who started a stored row: its created_by once rows have one, else the install owner (everything is theirs today). */-export function rowOwner(row: object): string {- return (row as { created_by?: string | null }).created_by || INSTALL_OWNER_ID;-}--/**- * The actor a runner works as for a row started by `userId` (the install owner when the row names nobody yet). Throws- * AccountOffError when that person is pending, turned off, deleted or dormant.- */-export function ownerActor(userId?: string | null): Actor {- const id = userId || INSTALL_OWNER_ID;- const p = db().prepare("SELECT id, role, status, dormant FROM users WHERE id = ?").get(id) as { id: string; role: string; status: string; dormant: number } | undefined;- if (!p || p.status !== "active" || p.dormant) throw new AccountOffError();- return { userId: p.id, role: p.role, via: "runner", scopes: ["full"] };-}--/** Run `fn` as the row's owner (see ownerActor). */-export function runAsOwner<T>(userId: string | null | undefined, fn: () => T): T {- return runAs(ownerActor(userId), fn);-}diff --git a/src/server/access/route.ts b/src/server/access/route.tsdeleted file mode 100644index 0e36619f..00000000--- a/src/server/access/route.ts+++ /dev/null@@ -1,216 +0,0 @@-import "server-only";-import { CLIENT_IP_HEADER, type Principal, resolvePrincipal } from "../identity/principal";-import { refusal } from "../identity/refusals";-import { withScope, type Actor } from "./actor";-import { auditDenied, auditHidden, auditRefused } from "./audit";-import { AccessError, ForbiddenError, NotFoundError, UnauthenticatedError } from "./errors";-import { can, permissionExists } from "./permissions";--/**- * Every route handler goes through handler() (docs/research/accounts-8.md §7.1, §7.3, §7.18): it resolves who is- * asking (the principal: a token, a session, or Just me on this computer), checks what the route declares, and runs- * the route inside a request scope, so server code can ask currentActor() and audit() knows who acted. Next 16 rule:- * the proxy is optimistic; this is where authorization is checked again, for every request.- *- * export const POST = handler({ access: "perm:install.settings" }, async (request) => { … });- *- * Access kinds:- * - "signed-in" (the default): any person — a session, a token, or the local owner.- * - "browser": a session or the local owner, never an API token (tokens are managed from a browser, §7.10).- * - "perm:<name>": a person whose install role holds that permission (src/server/access/permissions.ts).- * - "public": anyone; the route answers for nobody when no one is signed in (sign-in, share files, the identity- * router). A known person is still the actor.- *- * Token scopes: a bearer token may call a route only when one of its scopes is listed (Full always may). By default- * reads (GET, HEAD) take any scope, writes take Generate or Admin, and permission routes take Admin.- *- * Refusals thrown inside (src/server/access/errors.ts) become their answers: 404, 403, 401, 402 and 403 REAUTH. A route- * (or a studio's error helper) that catches errors to answer them itself passes these on with rethrowAccess(e). Every- * 403 is audited as `denied`, including one the route answers itself and a turned-off person's refused credentials;- * the ones nobody signed in can cause are written at most once a minute per address and route (src/server/access/audit.ts).- */--export type Access = "public" | "signed-in" | "browser" | `perm:${string}`;-export type TokenScope = "full" | "read" | "generate" | "admin";--export interface HandlerOptions {- access?: Access;- /** The token scopes allowed besides Full (see above for the defaults). */- scopes?: TokenScope[];-}--// ----------------------------------------------------------------------------// Registries--/**- * Restricted session kinds (§7.1): a session that may only finish one step — enrolling two-step (`enroll-2fa`),- * proving it (`verify-2fa`), looking at someone's library (`view-as`), restoring a deleted account- * (`restore-account`), accepting new terms (`accept-terms`). Each kind's packages register the paths it may reach;- * anywhere else the session counts as signed out.- */-const RESTRICTED_KINDS = new Map<string, (pathname: string, method: string) => boolean>();--export function registerRestrictedKind(kind: string, allows: (pathname: string, method: string) => boolean): void {- RESTRICTED_KINDS.set(kind, allows);-}--export function restrictedAllows(kind: string, pathname: string, method: string): boolean {- return RESTRICTED_KINDS.get(kind)?.(pathname, method) ?? false;-}--/**- * The substituteActor seam (§9.5 E5b view-as): given the real actor and the request, a registered substitution- * returns who the request acts as, or null to leave it. The first that answers wins, and the real person is kept as- * `impersonatorId` (audit entries name them; permissions and team roles treat the request as read-only). None in the- * core.- */-type Substitute = (actor: Actor, request: Request) => Actor | null;-const SUBSTITUTES: Substitute[] = [];--export function registerActorSubstitute(fn: Substitute): void {- SUBSTITUTES.push(fn);-}--export function substituteActor(actor: Actor, request: Request): Actor {- for (const fn of SUBSTITUTES) {- const next = fn(actor, request);- if (next) return { ...next, impersonatorId: next.impersonatorId ?? actor.userId };- }- return actor;-}--// ----------------------------------------------------------------------------// The wrapper--/** Every route file's handlers, by file, for the route sweep (tests/route-sweep.test.ts). */-const WRAPPED = new WeakSet<object>();-export const isWrapped = (fn: unknown): boolean => typeof fn === "function" && WRAPPED.has(fn);--const READS = new Set(["GET", "HEAD", "OPTIONS"]);--function allowedScopes(opts: HandlerOptions, method: string): TokenScope[] {- if (opts.scopes) return opts.scopes;- if (opts.access?.startsWith("perm:")) return ["admin"];- return READS.has(method) ? ["read", "generate", "admin"] : ["generate", "admin"];-}--const json = (status: number, error: string, code?: string, headers?: HeadersInit) => Response.json({ error, ...(code && { code }) }, { status, headers });--/** Nobody (or a refused person) asking for a route that needs someone: the same answers the proxy gives. */-function signedOut(principal: Principal): Response {- if (principal.code && principal.code !== "INVALID_TOKEN") {- const r = refusal(principal.code);- // A pending, turned-off or dormant person's own credentials: a denial, audited under their name.- if (r.status === 403 && principal.refused) auditRefused(principal.refused.userId, principal.refused.via, r.code ?? principal.code);- return json(r.status, r.message, r.code);- }- const error = principal.code === "INVALID_TOKEN" ? "That API token isn't valid. Create a new one in Settings → Security." : new UnauthenticatedError().message;- return json(401, error, undefined, { "WWW-Authenticate": 'Bearer realm="fuobe"' });-}--/** Why this actor may not call this route, or null. */-function refusedFor(actor: Actor, opts: HandlerOptions, method: string): ForbiddenError | null {- const access = opts.access ?? "signed-in";- if (actor.via === "token" && !actor.scopes.includes("full") && !actor.scopes.some((s) => (allowedScopes(opts, method) as string[]).includes(s))) {- return new ForbiddenError("This API token's scope doesn't allow that.", "TOKEN_SCOPE");- }- if (access === "browser" && actor.via !== "session" && actor.via !== "local") {- return new ForbiddenError("Do this from a signed-in browser: an API token can't.", "BROWSER_ONLY");- }- if (access.startsWith("perm:")) {- const permission = access.slice(5);- if (!permissionExists(permission)) throw new Error(`Unknown permission ${permission}`);- if (!can(actor, permission)) return new ForbiddenError("You don't have access to this. Ask an admin.", "FORBIDDEN");- }- return null;-}--/** Turn a thrown refusal into its answer (others are rethrown: a 500, as before). */-function answer(e: unknown): Response {- if (!(e instanceof AccessError)) throw e;- if (e instanceof NotFoundError && e.hidden) auditHidden();- if (e.status === 403) auditDenied(e.code ?? "forbidden", { message: e.message });- return json(e.status, e.message, e.code);-}--const decode = (s: string) => {- try {- return decodeURIComponent(s);- } catch {- return s;- }-};--/**- * The route's pattern from the params Next matched: `/api/generations/g_123` with `{ id: "g_123" }` is- * `/api/generations/[id]`, and a catch-all's run of segments is `[...path]`. Rate-limited denials are counted per- * route, so probing ids or paths doesn't make each one new.- */-export async function routePattern(pathname: string, ctx: unknown): Promise<string> {- const raw = ctx && typeof ctx === "object" && "params" in ctx ? (ctx as { params: unknown }).params : undefined;- const params = raw ? await Promise.resolve(raw).catch(() => null) : null;- if (!params || typeof params !== "object") return pathname;- let segs = pathname.split("/");- for (const [name, value] of Object.entries(params as Record<string, unknown>)) {- if (Array.isArray(value)) {- const n = value.length;- for (let i = segs.length - n; n && i >= 1; i--) {- if (value.every((v, j) => decode(segs[i + j]) === String(v))) {- segs = [...segs.slice(0, i), `[...${name}]`, ...segs.slice(i + n)];- break;- }- }- } else if (typeof value === "string" && value) {- segs = segs.map((s) => (s && decode(s) === value ? `[${name}]` : s));- }- }- return segs.join("/");-}--/**- * Wrap a route handler. The request scope it opens carries the actor (null on a public route answered for nobody), the- * client's address (only when a trusted proxy reported it) and user agent, the method, the path and the route.- */-export function handler<Req extends Request = Request, C = unknown>(- opts: HandlerOptions,- fn: (request: Req, ctx: C) => Response | Promise<Response>,-): (request: Req, ctx?: C) => Promise<Response> {- const access = opts.access ?? "signed-in";- if (access.startsWith("perm:") && !permissionExists(access.slice(5))) throw new Error(`Unknown permission ${access.slice(5)}`);- // Next always passes the context; a route without params (or a test calling one) may leave it out.- const wrapped = async (request: Req, ctx?: C): Promise<Response> => {- const url = new URL(request.url);- const method = request.method.toUpperCase();- const principal = await resolvePrincipal(request);- let actor = principal.actor;- // A restricted session (finishing two-step, accepting terms…) outside its own routes is signed out.- if (actor?.restricted && !restrictedAllows(actor.restricted, url.pathname, method)) actor = null;- if (actor) actor = substituteActor(actor, request);- const scope = {- actor,- ip: request.headers.get(CLIENT_IP_HEADER),- userAgent: request.headers.get("user-agent"),- method,- path: url.pathname,- route: await routePattern(url.pathname, ctx),- };- return withScope(scope, async () => {- if (!actor && access !== "public") return signedOut(principal);- if (actor) {- const refused = refusedFor(actor, opts, method);- if (refused) return answer(refused);- }- let res: Response;- try {- res = await fn(request, ctx as C);- } catch (e) {- return answer(e);- }- // A 403 the route answered itself (a wrong current password, MCP's Origin check) is a denial too.- if (res.status === 403) auditDenied("route");- return res;- });- };- WRAPPED.add(wrapped);- return wrapped;-}diff --git a/src/server/ads.ts b/src/server/ads.tsindex 2a1f5350..c19e89be 100644--- a/src/server/ads.ts+++ b/src/server/ads.ts@@ -18,7 +18,6 @@ import {import type { Engine, Generation, GenerationRequest, OutputFile } from "@/lib/catalog/types";import { getModel } from "@/lib/catalog";import { getBrand, getProduct, listProducts, parseJsonObject } from "./brand";-import { currentActor, runAs } from "./access/actor";import { db } from "./db";import { llmText } from "./enhance";import { createGenerations, getGeneration, previewGeneration, recordLocalGeneration } from "./generations";@@ -295,8 +294,7 @@ export function createBatch(input: BatchInput, fixed: FixedCopy = {}): { batchId}})();running().add(batchId);- // Copy and pictures follow after the response (the route keeps it going with after()), for the person who asked.- const run = runAs(currentActor(), () => fillBatch(batchId, brand, ids, input, fixed)).finally(() => running().delete(batchId));+ const run = fillBatch(batchId, brand, ids, input, fixed).finally(() => running().delete(batchId));return { batchId, creatives: listCreatives({ brandId: brand.id, batchId }), run };}diff --git a/src/server/assist/agent.ts b/src/server/assist/agent.tsindex 1ece204d..799c0d8e 100644--- a/src/server/assist/agent.ts+++ b/src/server/assist/agent.ts@@ -26,8 +26,6 @@ import {type SkillMeta,} from "@/lib/assist";import type { Engine, Generation, MediaKind } from "@/lib/catalog/types";-import { currentActor, runAs, type Actor } from "../access/actor";-import { AccountOffError, ownerActor, rowOwner } from "../access/permissions";import { db } from "../db";import { getGeneration } from "../generations";import { offeredDefault } from "../model-access";@@ -1112,7 +1110,6 @@ function animateTake(still: { url: string; g: Generation }, take: number, preferfunction toolCtx(s: State): ToolContext {return {engine: s.thread.engine,- actor: currentActor(),thread: {id: s.thread.id,projectId: s.ext.projectId,@@ -1288,31 +1285,8 @@ const MODELS: Record<AssistThread["agent"], ModelCall> = { claude, ollama, offli/*** Run the agent until it ends its turn or waits for approval. Call it right after addMessage or* answerApproval: it claims the thread synchronously, so the "running" status they saved stays valid.- * The turn acts for the chat's author (docs/research/accounts-8.md §7.11), whoever's request or schedule carried it- * on: the tools it runs, the generations it starts and what they spend are theirs.*/export async function run(id: string, model?: ModelCall): Promise<void> {- if (runs.has(id)) return;- const row = db().prepare("SELECT * FROM assist_threads WHERE id = ?").get(id) as Row | undefined;- if (!row) return;- let owner: Actor;- try {- owner = ownerActor(rowOwner(row));- } catch (e) {- if (!(e instanceof AccountOffError)) throw e;- // The chat's author was turned off: say so in the chat instead of leaving it "running".- const s = load(id);- if (s) {- push(s, { role: "notice", tone: "error", text: e.message });- s.thread.status = "idle";- save(s);- }- return;- }- return runAs(owner, () => turn(id, model));-}--async function turn(id: string, model?: ModelCall): Promise<void> {if (runs.has(id)) return;runs.add(id);try {diff --git a/src/server/assist/define.ts b/src/server/assist/define.tsindex 5da0cb14..f1513631 100644--- a/src/server/assist/define.ts+++ b/src/server/assist/define.ts@@ -2,7 +2,6 @@ import "server-only";import type Anthropic from "@anthropic-ai/sdk";import type { z } from "zod";import type { AssistItem, PlannedJob } from "@/lib/assist";-import type { Actor } from "../access/actor";/** Shared shape of Assist's tools (also served over MCP). */@@ -10,8 +9,6 @@ export type ResultContent = Anthropic.Beta.BetaToolResultBlockParam["content"];export interface ToolContext {engine: "cloud" | "open";- /** Who the tool acts for: the MCP token's or session's person, or the chat's author (the scoping package narrows by it). */- actor?: Actor;/** The Assist chat running the tool; absent over MCP. */thread?: {id: string;diff --git a/src/server/assist/schedules.ts b/src/server/assist/schedules.tsindex 4e5156c0..d5ae19ed 100644--- a/src/server/assist/schedules.ts+++ b/src/server/assist/schedules.ts@@ -14,8 +14,6 @@ import {type ScheduleView,} from "@/lib/assist-schedule";import { formatCost } from "@/lib/format";-import { asSystem } from "../access/actor";-import { rowOwner, runAsOwner } from "../access/permissions";import { db } from "../db";import { addMessage, createThread, getThread, resolveMode, run, type ModelCall } from "./agent";import { getProject } from "./projects";@@ -356,13 +354,10 @@ export async function sweepSchedules(now = Date.now(), o: { model?: ModelCall }const next = nextRun(JSON.parse(r.rule_json) as ScheduleRule, r.tz, now);const claimed = db().prepare("UPDATE assist_schedules SET next_run_at = ? WHERE id = ? AND next_run_at = ? AND paused = 0").run(next, r.id, r.next_run_at).changes;if (!claimed) continue;- // A task runs as the person who owns it, never as whoever the sweep's timer started under.- const begun = await Promise.resolve()- .then(() => runAsOwner(rowOwner(r), () => startSchedule(r.id, { now, model: o.model })))- .catch((e: Error) => {- record(r.id, { last_run_at: now, last_thread_id: null, last_status: "failed", last_text: e.message });- return null;- });+ const begun = await startSchedule(r.id, { now, model: o.model }).catch((e: Error) => {+ record(r.id, { last_run_at: now, last_thread_id: null, last_status: "failed", last_text: e.message });+ return null;+ });if (begun?.threadId) started.push(begun.threadId);if (begun) runs.push(begun.done);}@@ -388,11 +383,8 @@ export function ensureScheduleRunner(o: { soon?: boolean } = {}): void {cur.tick = tick;return;}- // The server's timers, whichever request started them (creating a task does): each task runs as its owner.- asSystem(() => {- const state = { tick, timer: setInterval(() => globalThis.__fuobeScheduleRunner?.tick(), SWEEP_MS) };- state.timer.unref?.();- globalThis.__fuobeScheduleRunner = state;- if (o.soon) setTimeout(() => globalThis.__fuobeScheduleRunner?.tick(), BOOT_SWEEP_MS).unref?.();- });+ const state = { tick, timer: setInterval(() => globalThis.__fuobeScheduleRunner?.tick(), SWEEP_MS) };+ state.timer.unref?.();+ globalThis.__fuobeScheduleRunner = state;+ if (o.soon) setTimeout(() => globalThis.__fuobeScheduleRunner?.tick(), BOOT_SWEEP_MS).unref?.();}diff --git a/src/server/brand.ts b/src/server/brand.tsindex 3b12797a..dd530131 100644--- a/src/server/brand.ts+++ b/src/server/brand.ts@@ -15,7 +15,6 @@ import {type BrandStatus,type Product,} from "@/lib/catalog/marketing";-import { currentActor, runAs } from "./access/actor";import { db } from "./db";import { llmText } from "./enhance";import { fetchRemote } from "./remote-fetch";@@ -969,8 +968,7 @@ const progressAt = (index: number): BrandProgress => ({ index, total: RESEARCH_Lfunction startResearch(id: string): Promise<void> {const ac = new AbortController();runs().set(id, ac);- // It outlives the request (the route keeps it going with after()): it acts for the person who asked for it.- return runAs(currentActor(), () => research(id, ac.signal))+ return research(id, ac.signal).catch((e) => {if (ac.signal.aborted) return;const kit = storedKit(id);diff --git a/src/server/cinema-schemas.ts b/src/server/cinema-schemas.tsindex f695e08e..fe1968fe 100644--- a/src/server/cinema-schemas.ts+++ b/src/server/cinema-schemas.ts@@ -2,7 +2,6 @@ import "server-only";import { z } from "zod";import { DISTANCE, MAX_KEYS } from "@/lib/camera-path";import { APERTURE, LENS } from "@/lib/scene3d";-import { rethrowAccess } from "./access/errors";import { CinemaError } from "./cinema";import { TurnaroundSchema } from "./turnaround";@@ -159,7 +158,6 @@ export async function handle(fn: () => Promise<Response> | Response): Promise<Retry {return await fn();} catch (e) {- rethrowAccess(e);if (e instanceof CinemaError) return Response.json({ error: e.message }, { status: e.status });console.error("[cinema]", e);return Response.json({ error: (e as Error).message || "Something went wrong" }, { status: 500 });diff --git a/src/server/content-factory.ts b/src/server/content-factory.tsindex 4962d668..544adb34 100644--- a/src/server/content-factory.ts+++ b/src/server/content-factory.ts@@ -43,8 +43,6 @@ import {import { genreInfo, pickerData, type ChannelSettings, type EpisodeSettings, type NarratorVoice, type TimedText } from "@/lib/catalog/faceless";import type { Engine, Generation, GenerationRequest } from "@/lib/catalog/types";import { probeMedia } from "@/lib/media-probe";-import { rethrowAccess } from "./access/errors";-import { rowOwner, runAsOwner } from "./access/permissions";import { authEnabled } from "./auth";import { db } from "./db";import { llmText, llmTextBackend, type LlmImage } from "./enhance";@@ -460,11 +458,8 @@ async function writeBrief(id: string): Promise<void> {});}-/**- * Moves a reading series on: the steps' progress, then the brief once they're all done. The brief is written as the- * person who started the series (`owner`), whoever's read happened to notice the steps had finished.- */-function advance(id: string, d: SeriesData, owner: string): SeriesData {+/** Moves a reading series on: the steps' progress, then the brief once they're all done. */+function advance(id: string, d: SeriesData): SeriesData {const a = d.analysis;if (!a || a.status !== "reading") return d;const gens = Object.values(a.steps).map((g) => getGeneration(g, { includeDeleted: true }));@@ -473,8 +468,7 @@ function advance(id: string, d: SeriesData, owner: string): SeriesData {return { ...d, analysis: { ...a, stage: running?.status === "queued" ? "Waiting for its turn…" : a.stage } };}if (!writing().has(id)) {- const job = Promise.resolve()- .then(() => runAsOwner(owner, () => writeBrief(id)))+ const job = writeBrief(id).catch((e: Error) => {patch(id, (cur) => {if (cur.analysis?.status === "reading") cur.analysis = { ...cur.analysis, status: "failed", stage: undefined, error: e.message || "Couldn't write the brief" };@@ -517,7 +511,7 @@ function toView(r: SeriesRow, d: SeriesData): SeriesView {export function seriesView(id: string): SeriesView {const r = mustRow(id);- return toView(r, advance(id, dataOf(r), rowOwner(r)));+ return toView(r, advance(id, dataOf(r)));}/** A new series around a reference (reading starts straight away), a preset (its brief is ready), or nothing yet. */@@ -879,7 +873,6 @@ export async function handle(fn: () => Promise<Response> | Response): Promise<Retry {return await fn();} catch (e) {- rethrowAccess(e);if (e instanceof NeedsUpload) return Response.json({ error: e.message, needsUpload: true }, { status: e.status });return facelessHandle(() => {throw e;diff --git a/src/server/db.ts b/src/server/db.tsindex ec0dd919..6f90bf00 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -714,11 +714,6 @@ const MIGRATIONS: string[] = [create index "auth_session_userId_idx" on "auth_session" ("userId");create index "auth_account_userId_idx" on "auth_account" ("userId");create index "auth_verification_identifier_idx" on "auth_verification" ("identifier");`,- // originals (o/acc-2): the audit log refuses DELETE as it already refuses UPDATE (docs/research/accounts-8.md §7.14),- // so a row can only be added. Only the retention purge (acc-34) removes rows: it lifts this trigger inside its own- // transaction and writes an entry of its own.- `CREATE TRIGGER IF NOT EXISTS audit_log_no_delete BEFORE DELETE ON audit_log- BEGIN SELECT RAISE(ABORT, 'audit_log is append-only'); END;`,];/** The index of the migration whose SQL contains `fragment` (-1 when none does): tests and the bootstrap name migrations by what they do. */diff --git a/src/server/faceless.ts b/src/server/faceless.tsindex 79bf7dd3..2296ab80 100644--- a/src/server/faceless.ts+++ b/src/server/faceless.ts@@ -79,9 +79,6 @@ import { pricingAt } from "@/lib/catalog/promo";import type { Engine, Generation, GenerationRequest } from "@/lib/catalog/types";import { DocxError, docxText } from "./assist/docx";import { PdfError, pdfText } from "./assist/pdf";-import { asSystem } from "./access/actor";-import { rethrowAccess } from "./access/errors";-import { rowOwner, runAsOwner } from "./access/permissions";import { db } from "./db";import { listElements } from "./elements";import { cancelGeneration, chooseRoute, createGenerations, getGeneration, previewChained } from "./generations";@@ -1110,9 +1107,6 @@ function finalOf(ep: FacelessEpisode): Generation | null {const brokenMessage = (g: Generation | null) =>!g ? "A step was deleted — retry to make it again" : g.status === "canceled" ? "A step was cancelled — retry to make it again" : (g.error ?? "A step didn't finish — retry it");-/** Who started an episode (its row's owner). */-const episodeOwner = (id: string) => rowOwner(db().prepare("SELECT * FROM faceless_episodes WHERE id = ?").get(id) ?? {});-/*** The episode's status from its generations (saved when it changes). Once stage one has finished, the* first look starts stage two (advance).@@ -1134,9 +1128,7 @@ function settle(ep: FacelessEpisode, gens?: Map<string, Generation | null>): Facif (ep.plan.awaiting) {if (!active && !broken && ep.status !== "failed") {try {- // Stage two starts as the person who started the episode, whoever's look noticed stage one had finished; when- // they're turned off it doesn't start, and the episode fails saying so.- return settle(runAsOwner(episodeOwner(ep.id), () => advance(ep)));+ return settle(advance(ep));} catch (e) {status = "failed";error = (e as Error).message;@@ -1163,7 +1155,6 @@ function sweep(): void {const rows = db().prepare("SELECT * FROM faceless_episodes WHERE status = 'rendering' AND plan_json LIKE '%\"awaiting\":true%'").all() as EpisodeRow[];for (const r of rows) {try {- // Stage two starts as the person who started the episode (settle).settle(toEpisode(r));} catch (e) {console.warn(`[faceless] couldn't continue ${r.id}: ${(e as Error).message}`);@@ -1179,8 +1170,7 @@ export function ensureFacelessRunner(): void {cur.tick = sweep;return;}- // The server's timer, whichever request started it; each episode then continues as its owner (sweep).- const state = { tick: sweep, timer: asSystem(() => setInterval(() => globalThis.__fuobeFacelessRunner?.tick(), SWEEP_MS)) };+ const state = { tick: sweep, timer: setInterval(() => globalThis.__fuobeFacelessRunner?.tick(), SWEEP_MS) };state.timer.unref?.();globalThis.__fuobeFacelessRunner = state;}@@ -1540,7 +1530,6 @@ export async function handle(fn: () => Promise<Response> | Response): Promise<Retry {return await fn();} catch (e) {- rethrowAccess(e);if (e instanceof FacelessError) return Response.json({ error: e.message }, { status: e.status });console.error("[faceless]", e);return Response.json({ error: (e as Error).message || "Something went wrong" }, { status: 500 });diff --git a/src/server/generations.ts b/src/server/generations.tsindex 067d5fb2..cc532fe5 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -42,8 +42,6 @@ import {type Preset,type ProviderId,} from "@/lib/catalog/types";-import { asSystem, runAs, type Actor } from "./access/actor";-import { AccountOffError, ownerActor, rowOwner, runAsOwner } from "./access/permissions";import { db } from "./db";import { listElements } from "./elements";import { pollTrainings } from "./training";@@ -1052,7 +1050,8 @@ async function advanceDependents(): Promise<void> {const rows = db().prepare(READY_DEPENDENTS).all(50 + submitting().size) as Row[];// A forced look at ComfyUI, at most one a sweep, for the steps that found it not answering.let lookedAgain: Promise<boolean> | undefined;- const advance = async (r: Row): Promise<void> => {+ for (const r of rows) {+ if (submitting().has(r.id)) continue;// A step queued before its model was retired runs on what replaced it (and its row says so).const moved = currentRequest(JSON.parse(r.request_json) as GenerationRequest);const stored = moved.request;@@ -1072,12 +1071,12 @@ async function advanceDependents(): Promise<void> {const skipped = allSlots.flatMap((s, i) => (s.optional && broken(allDeps[i]) ? [i] : []));if (allDeps.some((d, i) => broken(d) && !skipped.includes(i))) {fail(waitedOnFailure(!!stored.frame));- return;+ continue;}const keep = (_: unknown, i: number) => !skipped.includes(i);const deps = allDeps.filter(keep);const slots = allSlots.filter(keep);- if (deps.some((d) => d!.status !== "succeeded")) return;+ if (deps.some((d) => d!.status !== "succeeded")) continue;const request = skipped.length ? withoutSkipped(stored, allSlots, skipped) : stored;// What changed upstream (an earlier fallback) is said on this step too, down to the finished result.const notices = [request.notice, ...deps.map((d) => (JSON.parse(d!.request_json) as GenerationRequest).notice)].filter((x): x is string => !!x);@@ -1086,7 +1085,7 @@ async function advanceDependents(): Promise<void> {const short = slots.map((s, i) => listShortfall(outputs[i], s)).find(Boolean);if (short) {fail(`${earlier} ${short}`);- return;+ continue;}submitting().add(r.id);let handedOff = false;@@ -1096,7 +1095,7 @@ async function advanceDependents(): Promise<void> {const missing = values.findIndex((u) => !u);if (missing >= 0) {fail(`${earlier} has no ${slotNoun(slots[missing])} to use`);- return;+ continue;}// Routing reads cached reachability: make sure it's fresh for local engines. An Original counts with the routes of// the engine it runs on, ComfyUI taken as answering: one on the cloud doesn't use it, so doesn't wait for it.@@ -1111,9 +1110,9 @@ async function advanceDependents(): Promise<void> {if (!back && first === undefined) {comfyWaits().set(r.id, Date.now());update(r.id, { message: "Waits for ComfyUI to answer" });- return;+ continue;}- if (!back && Date.now() - first! < COMFY_WAIT.ms) return;+ if (!back && Date.now() - first! < COMFY_WAIT.ms) continue;}comfyWaits().delete(r.id);if (model?.routes.some((x) => x.provider === "llm")) await probeOllama();@@ -1142,19 +1141,6 @@ async function advanceDependents(): Promise<void> {} finally {if (!handedOff) submitting().delete(r.id);}- };- for (const r of rows) {- if (submitting().has(r.id)) continue;- // Each step is planned and submitted as the person who started its chain.- let owner: Actor;- try {- owner = ownerActor(rowOwner(r));- } catch (e) {- if (!(e instanceof AccountOffError)) throw e;- await pauseForOwner(r, e.message);- continue;- }- await runAs(owner, () => advance(r));}}@@ -1343,45 +1329,25 @@ export function ensureRunner(): void {cur.fast = fastTick;cur.polling ??= new Set();if (!cur.fastTimer) {- cur.fastTimer = asSystem(() => setInterval(() => void globalThis.__fuobeRunner?.fast?.(), FAST_POLL_MS));+ cur.fastTimer = setInterval(() => void globalThis.__fuobeRunner?.fast?.(), FAST_POLL_MS);cur.fastTimer.unref?.();}return;}- // The timers belong to the server, not to whichever request happened to start them: each row is then worked on as- // its owner (pollGuarded, advanceDependents).- asSystem(() => {- const state: RunnerState = {- busy: false,- tick,- fast: fastTick,- polling: new Set(),- timer: setInterval(() => void globalThis.__fuobeRunner?.tick(), POLL_MS),- fastTimer: setInterval(() => void globalThis.__fuobeRunner?.fast?.(), FAST_POLL_MS),- };- state.timer.unref?.();- state.fastTimer?.unref?.();- globalThis.__fuobeRunner = state;- void probeComfy().catch(() => false);- void probeOllama().catch(() => false);- sweepInterrupted();- });-}--/**- * A job whose owner was turned off or went dormant (§7.11): the provider's job is canceled first, so it stops running- * and charging, then the row fails with the reason, and steps waiting only to feed it are dropped before they're paid- * for (as a failed or canceled step does).- */-async function pauseForOwner(r: Row, message: string): Promise<void> {- const model = getModel(r.model_id);- if (r.external_id && model && (r.status === "queued" || r.status === "running")) {- await provider(r.provider)- .cancel?.(pollContext(r, model))- .catch(() => {});- }- update(r.id, { status: "failed", error: message, message: null, completed_at: Date.now() });- dropUnused(depIds(r.depends_on));+ const state: RunnerState = {+ busy: false,+ tick,+ fast: fastTick,+ polling: new Set(),+ timer: setInterval(() => void globalThis.__fuobeRunner?.tick(), POLL_MS),+ fastTimer: setInterval(() => void globalThis.__fuobeRunner?.fast?.(), FAST_POLL_MS),+ };+ state.timer.unref?.();+ state.fastTimer?.unref?.();+ globalThis.__fuobeRunner = state;+ void probeComfy().catch(() => false);+ void probeOllama().catch(() => false);+ sweepInterrupted();}/** Jobs that never got an external id (the server died mid-submit) can't be recovered. Runs every tick. */@@ -1401,11 +1367,9 @@ async function pollGuarded(r: Row): Promise<void> {if (polling.has(r.id)) return;polling.add(r.id);try {- // Polled, downloaded and saved as the person who started it.- await runAsOwner(rowOwner(r), () => pollOne(r));+ await pollOne(r);} catch (e) {- if (e instanceof AccountOffError) await pauseForOwner(r, e.message);- else update(r.id, { message: `Poll error: ${(e as Error).message}` });+ update(r.id, { message: `Poll error: ${(e as Error).message}` });} finally {polling.delete(r.id);}diff --git a/src/server/identity/audit-log.ts b/src/server/identity/audit-log.tsindex 955bcdbe..98622d9f 100644--- a/src/server/identity/audit-log.ts+++ b/src/server/identity/audit-log.ts@@ -5,9 +5,8 @@ import { db } from "../db";/*** The append-only audit log's storage (docs/research/accounts-8.md §7.14): each row carries the hash of the row* before it, so a changed or removed row breaks the chain from there on. This is the bare writer the identity core- * needs (imports, sign-ins, admin operations); the actor-aware `audit()` (src/server/access/audit.ts) reads the- * request scope and writes through it. The table refuses UPDATE and DELETE (triggers in db.ts). Never put a secret- * in `meta` (a password, a token, a key): names and prefixes only.+ * needs (imports, sign-ins, admin operations); the actor-aware `audit()` that reads the request scope arrives with+ * acc-2 and writes through it. Never put a secret in `meta` (a password, a token, a key): names and prefixes only.*/export interface AuditEntry {@@ -70,34 +69,12 @@ export function recentAudit(limit = 50): Row[] {return db().prepare("SELECT * FROM audit_log ORDER BY seq DESC LIMIT ?").all(limit) as Row[];}-export interface AuditChainCheck {- ok: boolean;- /** Rows checked. */- rows: number;- /** The time of the last row that verified ("Records verified up to {time}"); null when none did. */- verifiedUpTo: number | null;- /** The first row that doesn't match what the row before it remembers ("The record changed after {time}"). */- brokenAt?: { seq: number; at: number };-}--/**- * Walk the chain from the first row: each row must remember the hash of the row before it and hash to its own. A row- * changed in place, removed from the middle or inserted out of order breaks it from there on.- */-export function verifyAuditChain(): AuditChainCheck {+/** Whether every row still hashes to what the next one remembers: false from the first changed row on. */+export function auditChainIntact(): boolean {let prev = "";- let rows = 0;- let verifiedUpTo: number | null = null;for (const r of db().prepare("SELECT * FROM audit_log ORDER BY seq").iterate() as Iterable<Row>) {- if (r.prev_hash !== prev || r.hash !== rowHash(prev, r)) return { ok: false, rows, verifiedUpTo, brokenAt: { seq: r.seq, at: r.at } };+ if (r.prev_hash !== prev || r.hash !== rowHash(prev, r)) return false;prev = r.hash;- rows++;- verifiedUpTo = r.at;}- return { ok: true, rows, verifiedUpTo };-}--/** Whether every row still hashes to what the next one remembers: false from the first changed row on. */-export function auditChainIntact(): boolean {- return verifyAuditChain().ok;+ return true;}diff --git a/src/server/identity/principal.ts b/src/server/identity/principal.tsindex 61bf0f8d..2557a5ad 100644--- a/src/server/identity/principal.ts+++ b/src/server/identity/principal.ts@@ -2,7 +2,6 @@ import "server-only";import { hostAllowed } from "../auth";import { db } from "../db";import { installMode, signInOn } from "../mode";-import { LOCAL_OWNER } from "../access/actor";import { ensurePendingPerson, getAuth, sessionCookieName } from "./auth";import { tokenFromHeader } from "./tokens";@@ -16,8 +15,8 @@ import { tokenFromHeader } from "./tokens";* 3. Just me (Personal, sign-in off, a local address) → the owner, via `local`.* 4. Otherwise nobody.*- * The proxy uses it optimistically; every route handler asks again through handler() (src/server/access/route.ts),- * which also holds the restricted session kinds' registry and the actor-substitution seam.+ * The proxy uses it optimistically; route handlers that need a person ask again (acc-2 puts an actor on every+ * route).*/export type ActorVia = "session" | "token" | "local" | "system" | "runner" | "scim";@@ -39,14 +38,15 @@ export interface Principal {actor: Actor | null;/** Why there is no actor: INVALID_TOKEN (401), or a refusal code (ACCOUNT_PENDING…). */code?: string;- /** The person a refusal code is about (their token or session was valid, they may not act now): for the audit log. */- refused?: { userId: string; via: "token" | "session" };/** The session is due for its daily refresh, which only a POST performs (deferSessionRefresh). */needsRefresh?: boolean;}-/** The header Better Auth and the audit log read the client's address from; only the proxy writes it. */-export const CLIENT_IP_HEADER = "x-fuobe-client-ip";+/**+ * Restricted session kinds and the routes each may reach (packages add theirs: two-step enrolment, view-as…). A+ * restricted actor outside its routes is treated as signed out.+ */+export const RESTRICTED_KINDS = new Map<string, (pathname: string) => boolean>();interface PersonRow {id: string;@@ -76,6 +76,8 @@ export function hasSessionCookie(request: Request): boolean {return (request.headers.get("cookie") ?? "").split(";").some((c) => c.trim().startsWith(`${name}=`));}+const LOCAL: Actor = { userId: "u_owner", role: "owner", via: "local", scopes: ["full"] };+async function resolve(request: Request): Promise<Principal> {const local = justMe(request);const bearer = tokenFromHeader(request.headers.get("authorization"));@@ -85,7 +87,7 @@ async function resolve(request: Request): Promise<Principal> {const p = person(bearer.userId);if (!p) return { actor: null, code: "INVALID_TOKEN" };const code = blocked(p);- if (code) return { actor: null, code, refused: { userId: p.id, via: "token" } };+ if (code) return { actor: null, code };return { actor: { userId: p.id, role: p.role, via: "token", tokenId: bearer.tokenId, scopes: bearer.scopes, workspacePin: bearer.workspacePin } };}if (hasSessionCookie(request)) {@@ -95,14 +97,14 @@ async function resolve(request: Request): Promise<Principal> {if (found) {const p = ensurePendingPerson(found.user.id);const code = blocked(p);- if (code) return { actor: null, code, refused: { userId: p.id, via: "session" } };+ if (code) return { actor: null, code };return {actor: { userId: p.id, role: p.role, via: "session", sessionId: found.session.id, scopes: ["full"] },needsRefresh: !!(found as { needsRefresh?: boolean }).needsRefresh,};}}- if (local) return { actor: LOCAL_OWNER };+ if (local) return { actor: LOCAL };return { actor: null };}@@ -117,6 +119,15 @@ export function resolvePrincipal(request: Request): Promise<Principal> {return p;}+/** Act as someone else for this request (view-as, §9.5 E5b). The real actor is kept as the impersonator. */+export function substituteActor(actor: Actor, request: Request): void {+ const real = memo.get(request);+ memo.set(+ request,+ (real ?? Promise.resolve({ actor: null } as Principal)).then((r) => ({ actor: { ...actor, impersonatorId: r.actor?.userId ?? actor.impersonatorId } })),+ );+}+/*** Refresh a session that is due (once a day), on a POST: Better Auth extends it and sends the cookie again. Returns* the Set-Cookie headers to add to the response (none when nothing was due or it failed).diff --git a/src/server/library.ts b/src/server/library.tsindex 4a0e1b67..546c9e76 100644--- a/src/server/library.ts+++ b/src/server/library.ts@@ -21,7 +21,6 @@ import {type Folder,type ReviewFilter,} from "@/lib/library";-import { asSystem } from "./access/actor";import { db } from "./db";import { assetUses, cancelGeneration, deleteGeneration, getGeneration, type ListOptions } from "./generations";import { absolutePath, deleteAsset, getAsset } from "./storage";@@ -186,13 +185,10 @@ declare global {export function ensureTrashPurge(): void {if (globalThis.__fuobeTrashPurge) return;const run = () => void purgeTrash().catch((e) => console.warn(`[fuobe] trash purge failed: ${(e as Error).message}`));- // Housekeeping for everyone's Trash: the server's work, whichever library read started it.- asSystem(() => {- const timer = setInterval(run, DAY);- timer.unref?.();- globalThis.__fuobeTrashPurge = { timer };- run();- });+ const timer = setInterval(run, DAY);+ timer.unref?.();+ globalThis.__fuobeTrashPurge = { timer };+ run();}export function trashCount(): number {diff --git a/src/server/marketing.ts b/src/server/marketing.tsindex 0331d256..e5d1b056 100644--- a/src/server/marketing.ts+++ b/src/server/marketing.ts@@ -49,7 +49,6 @@ import { routesFor } from "@/lib/catalog/plan";import { probeMedia } from "@/lib/media-probe";import { themeFrom } from "@/components/ads/layout";import type { ChainSlot, Engine, GenerationRequest, ModelDef, Operation } from "@/lib/catalog/types";-import { rethrowAccess } from "./access/errors";import { getBrand, getProduct } from "./brand";import { createPipeline, type PipelineStep } from "./chains";import { db } from "./db";@@ -1291,7 +1290,6 @@ export async function readBody<S extends z.ZodType>(request: Request, schema: S,/** A thrown error as a JSON response: 409 for duplicates, 422 for everything the user can fix. */export function failure(e: unknown): Response {- rethrowAccess(e);const err = e as Error;const status = err?.name === "DuplicateProductError" || err?.constructor?.name === "DuplicateProductError" ? 409 : 422;return Response.json({ error: err?.message || "Something went wrong" }, { status });diff --git a/src/server/mcp.ts b/src/server/mcp.tsindex 1aa41165..ebec6419 100644--- a/src/server/mcp.ts+++ b/src/server/mcp.ts@@ -3,9 +3,6 @@ import { z } from "zod";// The studio modules behind the studio tools (tools.ts imports them too; named here so MCP never runs without them).import "./assist/studio-routes";import { apiSchema, executeTool, getTool, planFor, TOOLS, type ToolContext } from "./assist/tools";-import { currentActor, requestScope, withScope, type Actor } from "./access/actor";-import { auditDenied, auditHidden } from "./access/audit";-import { AccessError, NotFoundError } from "./access/errors";import { engineMode } from "./settings";import { recipeMarkdown } from "@/lib/recipe";import { enabledSkills, getSkill, skillRecipe } from "./skills";@@ -41,18 +38,10 @@ type JsonRpcResponse = { jsonrpc: "2.0"; id: string | number | null } & ({ resulconst ok = (id: JsonRpcRequest["id"], result: unknown): JsonRpcResponse => ({ jsonrpc: "2.0", id: id ?? null, result });const fail = (id: JsonRpcRequest["id"], code: number, message: string): JsonRpcResponse => ({ jsonrpc: "2.0", id: id ?? null, error: { code, message } });-/** The tools' context: the engine, and who the tool acts for (the token's or session's person, from the scope). */-const ctx = (): ToolContext => ({ engine: engineMode() === "open" ? "open" : "cloud", actor: currentActor() });+const ctx = (): ToolContext => ({ engine: engineMode() === "open" ? "open" : "cloud" });const READ_ONLY = new Set(["search_models", "list_elements", "list_recent", "check_generations", "estimate_cost", "estimate_job", "list_skills", "load_skill", "read_source"]);-/**- * Whether the person may run tools that make or change things: a Read-only API token gets the read tools only- * (docs/research/accounts-8.md §7.10); a session, the local owner and Full, Generate or Admin tokens get them all.- */-const mayWrite = (actor: Actor) => actor.via !== "token" || actor.scopes.some((s) => s === "full" || s === "generate" || s === "admin");-const READ_ONLY_REFUSAL = "This API token is Read only: it can look things up but not run tools that make or change things. Create a Generate or Full token in Settings → Security.";-/** Gated tools other than generate and create_storyboard (priced with estimate_job). */const jobTools = () => TOOLS.filter((t) => t.gated && t.plan && !["generate", "create_storyboard", "remember"].includes(t.name)).map((t) => t.name);@@ -65,9 +54,8 @@ function describe(t: (typeof TOOLS)[number]): string {return `${base} Spends money on paid models (or GPU time on open ones): ${how} and confirm with the user first.`;}-function toolList(actor: Actor) {- const offered = mayWrite(actor) ? TOOLS : TOOLS.filter((t) => READ_ONLY.has(t.name));- const tools: { name: string; title: string; description: string; inputSchema: unknown; annotations: { readOnlyHint: boolean; openWorldHint: boolean } }[] = offered.map((t) => ({+function toolList() {+ const tools: { name: string; title: string; description: string; inputSchema: unknown; annotations: { readOnlyHint: boolean; openWorldHint: boolean } }[] = TOOLS.map((t) => ({name: t.name,title: t.name.replace(/_/g, " ").replace(/^./, (c) => c.toUpperCase()),description: describe(t),@@ -121,10 +109,6 @@ async function call(params: unknown) {const p = CallParams.safeParse(params);if (!p.success) return null;const { name, arguments: args = {} } = p.data;- if (!READ_ONLY.has(name) && getTool(name) && !mayWrite(currentActor())) {- auditDenied("TOKEN_SCOPE", { tool: name });- return { content: [{ type: "text", text: READ_ONLY_REFUSAL }], isError: true };- }if (name === "estimate_cost") {const plan = planFor("generate", getTool("generate")!.schema.parse(args), ctx());return { content: [{ type: "text", text: JSON.stringify(plan) }], structuredContent: plan, isError: plan.jobs.every((j) => j.error) };@@ -176,16 +160,8 @@ function promptGet(params: unknown) {};}-/**- * Handle one JSON-RPC message as `actor` (the person behind the bearer token or session; by default whoever the scope- * says is acting); null for notifications (no response). Everything the message runs — tool calls and what they start —- * acts for that person, in the request's scope (its address and browser stay on what the tools audit).- */-export async function handleMcp(msg: unknown, actor: Actor = currentActor()): Promise<JsonRpcResponse | null> {- return withScope({ ...requestScope(), actor }, () => answer(msg));-}--async function answer(msg: unknown): Promise<JsonRpcResponse | null> {+/** Handle one JSON-RPC message; null for notifications (no response). */+export async function handleMcp(msg: unknown): Promise<JsonRpcResponse | null> {const m = msg as JsonRpcRequest;if (!m || m.jsonrpc !== "2.0" || typeof m.method !== "string") return fail(null, -32600, "Invalid request");const isNotification = m.id === undefined;@@ -203,7 +179,7 @@ async function answer(msg: unknown): Promise<JsonRpcResponse | null> {case "ping":return ok(m.id, {});case "tools/list":- return ok(m.id, { tools: toolList(currentActor()) });+ return ok(m.id, { tools: toolList() });case "tools/call": {try {const r = await call(m.params);@@ -211,9 +187,6 @@ async function answer(msg: unknown): Promise<JsonRpcResponse | null> {if (r === undefined) return fail(m.id, -32602, `Unknown tool ${String(m.params?.name)}`);return ok(m.id, r);} catch (e) {- // A refusal (no access, over a limit) is audited as handler() would, and told to the model like any tool error.- if (e instanceof NotFoundError && e.hidden) auditHidden();- if (e instanceof AccessError && e.status === 403) auditDenied(e.code ?? "forbidden", { tool: String(m.params?.name), message: e.message });// Bad arguments for estimate_cost and the like: a tool error the model can read.return ok(m.id, { content: [{ type: "text", text: (e as Error).message }], isError: true });}diff --git a/src/server/recipe-routes.ts b/src/server/recipe-routes.tsindex 1e808b85..2008a30d 100644--- a/src/server/recipe-routes.ts+++ b/src/server/recipe-routes.ts@@ -1,6 +1,5 @@import "server-only";import { z } from "zod";-import { rethrowAccess } from "./access/errors";import { RecipeError } from "./recipes";import { SkillError } from "./skills";@@ -14,7 +13,6 @@ export const RunBody = z.object({/** A refusal as JSON: the reason, every problem of a recipe, and the status a SkillError carries. */export function recipeFailure(e: unknown): Response {- rethrowAccess(e);const status = e instanceof SkillError ? e.status : 500;return Response.json({ error: (e as Error).message, ...(e instanceof RecipeError && { problems: e.problems }) }, { status });}diff --git a/src/server/shorts-schemas.ts b/src/server/shorts-schemas.tsindex 9b0e0061..7c981d3c 100644--- a/src/server/shorts-schemas.ts+++ b/src/server/shorts-schemas.ts@@ -2,7 +2,6 @@ import "server-only";import { z } from "zod";import { MIXED } from "@/lib/catalog/mixed-media";import { SHORTS } from "@/lib/catalog/shorts";-import { rethrowAccess } from "./access/errors";import { ShortsError } from "./shorts";/** Request bodies for /api/shorts/** and /api/mixed-media/** (zod), and the shared error answer. */@@ -65,9 +64,8 @@ export const NonceSchema = z.object({ requestId }).default({});export const MixedEstimateSchema = MixedBodySchema.extend({ source: source.extend({ url: z.string().max(500).default("/api/files/placeholder.mp4") }) });-/** A user-facing error answer: ShortsError keeps its status; anything else from the planner is a 422 (a refusal goes on to handler()). */+/** A user-facing error answer: ShortsError keeps its status; anything else from the planner is a 422. */export function errorResponse(e: unknown): Response {- rethrowAccess(e);if (e instanceof ShortsError) return Response.json({ error: e.message }, { status: e.status });return Response.json({ error: (e as Error).message || "Something went wrong" }, { status: 422 });}diff --git a/src/server/swap-studio.ts b/src/server/swap-studio.tsindex eba6daa3..3601cc11 100644--- a/src/server/swap-studio.ts+++ b/src/server/swap-studio.ts@@ -46,8 +46,6 @@ import { cloudMaskCut, frozenTakePlan, planAnchor, planAssembly, planMask, planNimport type { Engine, Generation, PixelPoint } from "@/lib/catalog/types";import { ACCESS_PLACE } from "@/lib/model-access";import { createPipeline } from "./chains";-import { asSystem, runAs, type Actor } from "./access/actor";-import { AccountOffError, ownerActor, rowOwner } from "./access/permissions";import { db } from "./db";import { cancelGeneration, getGeneration, previewChained } from "./generations";import { isOffered, offeredLoras } from "./model-access";@@ -327,30 +325,9 @@ function settle(p: SwapProject, look: Look): SwapProject {return clips.some((c, i) => c !== p.clips[i]) ? { ...p, clips } : p;}-/** Every take still waiting stops, saying why: it never launches (its project's owner was turned off). */-function stopWaiting(p: SwapProject, reason: string): SwapProject {- if (!takesOf(p).some((t) => t.state === "waiting")) return p;- const stop = (t: SwapTake): SwapTake => (t.state === "waiting" ? { ...t, state: "stopped", reason, waitsOn: undefined } : t);- return { ...p, clips: p.clips.map((c) => ({ ...c, shots: c.shots.map((s) => (s.segments ? { ...s, segments: s.segments.map((g) => ({ ...g, takes: g.takes.map(stop) })) } : s)) })) };-}--/**- * Read a project and bring it up to date (saved when anything changed). Waiting takes launch as the person who started- * the project, whoever's read (the page's poll, the sweep) noticed they could; when that person is turned off they stop- * with the reason instead, so nothing launches for them and the sweep lets the project go.- */+/** Read a project and bring it up to date (saved when anything changed). */export function advanceProject(id: string): SwapProject {- const row = rowOf(id);- if (!row) return mustProject(id);- let owner: Actor;- try {- owner = ownerActor(rowOwner(row));- } catch (e) {- if (!(e instanceof AccountOffError)) throw e;- const reason = e.message;- return mutate(id, (p) => settle(stopWaiting(p, reason), lookup()));- }- return runAs(owner, () => mutate(id, (p) => settle(p, lookup())));+ return mutate(id, (p) => settle(p, lookup()));}declare global {@@ -368,7 +345,6 @@ export function ensureSwapStudioRunner(): void {const rows = db().prepare("SELECT id FROM swap_projects WHERE waiting > 0").all() as { id: string }[];for (const r of rows) {try {- // Waiting takes launch as the person who started the project (or stop, saying why, when they're off).advanceProject(r.id);} catch (e) {console.error(`[swap-studio] ${r.id}:`, (e as Error).message);@@ -378,12 +354,9 @@ export function ensureSwapStudioRunner(): void {console.error("[swap-studio] sweep:", (e as Error).message);}};- // The server's timers, whichever request started them; each project then advances as its owner.- asSystem(() => {- globalThis.__fuobeSwapStudioRunner = setInterval(tick, 3000);- globalThis.__fuobeSwapStudioRunner.unref?.();- setTimeout(tick, 500).unref?.();- });+ globalThis.__fuobeSwapStudioRunner = setInterval(tick, 3000);+ globalThis.__fuobeSwapStudioRunner.unref?.();+ setTimeout(tick, 500).unref?.();}// ---------------------------------------------------------------------------diff --git a/src/server/training.ts b/src/server/training.tsindex 78fc9c66..f92d1942 100644--- a/src/server/training.ts+++ b/src/server/training.ts@@ -28,7 +28,6 @@ import {} from "@/lib/catalog/training";import { TRAINING_REPLACED_BY } from "@/lib/catalog/replaced";import { DEFAULT_AI_TOOLKIT_URL } from "@/lib/connections";-import { AccountOffError, rowOwner, runAsOwner } from "./access/permissions";import { DATA_DIR, db } from "./db";import { getElement, updateElement } from "./elements";import { keepTrainedLora, lorasPath, ownCopy, recordTrainedMirror } from "./loras";@@ -450,25 +449,15 @@ export async function pollTrainings(): Promise<void> {const sql = `SELECT * FROM trainings WHERE status IN ('queued','running') AND target IN (${retired.map(() => "?").join(", ")})`;for (const r of db().prepare(sql).all(...retired) as Row[]) fail(r.id, r.element_id, retiredTraining(r.target)!);// Copies of hosted LoRAs a restart cut off: start them again.- // Each training is polled, and its LoRA kept, as the person who started it.- for (const r of db().prepare(`SELECT * FROM trainings WHERE status = 'succeeded' AND meta_json LIKE '%"keep":"pending"%'`).all() as Row[]) {- try {- runAsOwner(rowOwner(r), () => keepInBackground(r));- } catch (e) {- if (!(e instanceof AccountOffError)) throw e;- setKeep(r.id, "failed", e.message);- }- }+ for (const r of db().prepare(`SELECT * FROM trainings WHERE status = 'succeeded' AND meta_json LIKE '%"keep":"pending"%'`).all() as Row[]) keepInBackground(r);const rows = db().prepare("SELECT * FROM trainings WHERE status = 'running' AND external_id IS NOT NULL").all() as Row[];await Promise.all(- rows.map(async (r) => {- try {- await runAsOwner(rowOwner(r), () => pollOne(r));- } catch (e) {- if (e instanceof AccountOffError || permanent(e)) return fail(r.id, r.element_id, (e as Error).message);+ rows.map((r) =>+ pollOne(r).catch((e) => {+ if (permanent(e)) return fail(r.id, r.element_id, (e as Error).message);update(r.id, { message: `Checking status failed: ${(e as Error).message}` });- }- }),+ }),+ ),);}diff --git a/tests/access-roles.test.ts b/tests/access-roles.test.tsdeleted file mode 100644index a7506020..00000000--- a/tests/access-roles.test.ts+++ /dev/null@@ -1,427 +0,0 @@-/**- * Who may call what (docs/research/accounts-8.md §7.1, §7.3): handler() resolves an actor for every route, the four- * install-config routes need install.settings (the Personal owner and Just me on this computer pass, a member is- * refused), token scopes narrow what a token may call, typed refusals become 404 / 403 / 401 / 402 / 403 REAUTH,- * every 403 is audited, restricted sessions only reach their own routes, the substituteActor seam keeps the real- * person, and the role, permission and team-role registries answer as the plan says.- */-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";--vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));--// Real scrypt hashes (N=2^15) for the password case: slow under a parallel run.-vi.setConfig({ testTimeout: 60_000 });--const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-access-"));-process.env.FUOBE_DATA_DIR = dir;-process.env.COMFYUI_URL = "http://127.0.0.1:9";-for (const k of ["FUOBE_PASSWORD", "FUOBE_OWNER_PASSWORD", "FUOBE_SIGNIN", "FUOBE_MODE", "FUOBE_SECRET", "FUOBE_TRUST_PROXY", "FUOBE_TRUSTED_PROXIES", "FUOBE_SITE_URL"]) delete process.env[k];--const { db } = await import("@/server/db");-const { bootstrapIdentity } = await import("@/server/identity/bootstrap");-const { handler, registerActorSubstitute, registerRestrictedKind, restrictedAllows, routePattern } = await import("@/server/access/route");-const { currentActor, maybeActor, LOCAL_OWNER, runAs, SYSTEM } = await import("@/server/access/actor");-const errors = await import("@/server/access/errors");-const perms = await import("@/server/access/permissions");-const { gate, gateRefusal, registerGate } = await import("@/server/access/gates");-const { seedPerson, seedTeam, tokenFor, request, actor, asNobody, updatePerson } = await import("./helpers/actors");-const { setOwnerPassword, ownerCookie } = await import("./helpers/identity");-const settingsRoute = await import("@/app/api/settings/route");-const modelsRoute = await import("@/app/api/settings/models/route");-const providersTest = await import("@/app/api/providers/test/route");-const lorasRoute = await import("@/app/api/loras/route");-const tokensRoute = await import("@/app/api/auth/tokens/route");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));--await bootstrapIdentity();--interface AuditRow {- seq: number;- action: string;- actor_id: string | null;- actor_via: string | null;- meta_json: string;-}-const lastAudit = () => db().prepare("SELECT * FROM audit_log ORDER BY seq DESC LIMIT 1").get() as AuditRow;-const auditCount = (action: string) => (db().prepare("SELECT COUNT(*) AS n FROM audit_log WHERE action = ?").get(action) as { n: number }).n;--const member = seedPerson({ role: "member" });-const admin = seedPerson({ role: "admin" });--/** The four install-config calls, each with a body their handler answers 400 to (nothing changes, nothing is fetched). */-const CONFIG: [string, (o: { bearer?: string; cookie?: string }) => Promise<Response>][] = [- ["PUT /api/settings", (o) => settingsRoute.PUT(request("/api/settings", { method: "PUT", body: { nope: 1 }, ...o }))],- ["PUT /api/settings/models", (o) => modelsRoute.PUT(request("/api/settings/models", { method: "PUT", body: {}, ...o }))],- ["POST /api/providers/test", (o) => providersTest.POST(request("/api/providers/test", { body: { provider: "nope" }, ...o }))],- ["POST /api/loras", (o) => lorasRoute.POST(request("/api/loras", { body: {}, ...o }))],-];--describe("install-config routes need install.settings", () => {- it("lets Just me on this computer through", async () => {- for (const [name, call] of CONFIG) expect([200, 400], name).toContain((await call({})).status);- });-- it("refuses a member with 403, audited as denied with the route and the reason", async () => {- const token = tokenFor(member);- for (const [name, call] of CONFIG) {- const before = auditCount("denied");- const res = await call({ bearer: token });- expect(res.status, name).toBe(403);- expect(await res.json()).toMatchObject({ code: "FORBIDDEN" });- expect(auditCount("denied"), name).toBe(before + 1);- const row = lastAudit();- expect(row).toMatchObject({ action: "denied", actor_id: member, actor_via: "token" });- const [method, p] = name.split(" ");- expect(JSON.parse(row.meta_json)).toMatchObject({ method, path: p, reason: "FORBIDDEN" });- }- });-- it("lets an admin and the owner's Full or Admin tokens through, but not a Generate or Read token", async () => {- for (const bearer of [tokenFor(admin), tokenFor("u_owner"), tokenFor("u_owner", ["admin"])]) {- for (const [name, call] of CONFIG) expect([200, 400], name).toContain((await call({ bearer })).status);- }- for (const scopes of [["generate"], ["read"]]) {- const res = await settingsRoute.PUT(request("/api/settings", { method: "PUT", body: {}, bearer: tokenFor("u_owner", scopes) }));- expect(res.status).toBe(403);- expect(await res.json()).toMatchObject({ code: "TOKEN_SCOPE" });- }- });-- it("lets the Personal owner through when signed in, and nobody without a session or token", async () => {- await setOwnerPassword("correct horse battery");- try {- const cookie = await ownerCookie("correct horse battery");- for (const [name, call] of CONFIG) expect([200, 400], name).toContain((await call({ cookie })).status);- for (const [name, call] of CONFIG) expect((await call({})).status, name).toBe(401);- expect((await settingsRoute.PUT(request("/api/settings", { method: "PUT", body: {}, bearer: "fuobe_wrong" }))).status).toBe(401);- } finally {- await setOwnerPassword(null);- }- });-- it("keeps reads open to every signed-in person", async () => {- expect((await settingsRoute.GET(request("/api/settings", { bearer: tokenFor(member, ["read"]) }))).status).toBe(200);- });-});--describe("token scopes and browser-only routes", () => {- it("lets a Read token read but not write", async () => {- const read = tokenFor("u_owner", ["read"]);- const echo = handler({}, () => Response.json({ ok: true }));- expect((await echo(request("/x", { bearer: read }))).status).toBe(200);- const res = await echo(request("/x", { method: "POST", body: {}, bearer: read }));- expect(res.status).toBe(403);- expect(await res.json()).toMatchObject({ code: "TOKEN_SCOPE" });- });-- it("keeps API tokens out of token management", async () => {- const res = await tokensRoute.GET(request("/api/auth/tokens", { bearer: tokenFor("u_owner") }));- expect(res.status).toBe(403);- expect(await res.json()).toMatchObject({ code: "BROWSER_ONLY" });- expect((await tokensRoute.GET(request("/api/auth/tokens"))).status).toBe(200);- });-});--describe("handler()", () => {- it("runs the route as the resolved actor, with the address and browser in the scope", async () => {- let seen: unknown;- const who = handler({}, () => {- seen = currentActor();- return Response.json({});- });- await runAs(SYSTEM, () => who(request("/x")));- expect(seen).toEqual(LOCAL_OWNER);- await who(request("/x", { bearer: tokenFor(member) }));- expect(seen).toMatchObject({ userId: member, role: "member", via: "token" });- });-- it("answers a public route for nobody, and every other route 401", async () => {- await setOwnerPassword("correct horse battery");- try {- let seen: unknown = "unset";- const open = handler({ access: "public" }, () => {- seen = maybeActor();- return Response.json({});- });- expect((await open(request("/x"))).status).toBe(200);- expect(seen).toBeNull();- const closed = handler({}, () => Response.json({}));- const res = await closed(request("/x"));- expect(res.status).toBe(401);- expect(res.headers.get("www-authenticate")).toMatch(/Bearer/);- } finally {- await setOwnerPassword(null);- }- });-- it("maps typed refusals to 404, 403, 401, 402 and 403 REAUTH, auditing each 403", async () => {- const cases: [Error, number, string | undefined][] = [- [new errors.NotFoundError(), 404, undefined],- [new errors.ForbiddenError("No.", "NOPE"), 403, "NOPE"],- [new errors.UnauthenticatedError(), 401, undefined],- [new errors.PaymentRequiredError(), 402, "LIMIT_REACHED"],- [new errors.ReauthRequiredError(), 403, "REAUTH"],- ];- for (const [e, status, code] of cases) {- const before = auditCount("denied");- const res = await handler({}, () => {- throw e;- })(request("/refuse", { method: "POST", body: {} }));- expect(res.status, e.name).toBe(status);- const body = (await res.json()) as { error: string; code?: string };- expect(body.error).toBe(e.message);- expect(body.code).toBe(code);- expect(auditCount("denied"), e.name).toBe(before + (status === 403 ? 1 : 0));- if (status === 403) expect(JSON.parse(lastAudit().meta_json)).toMatchObject({ reason: code, path: "/refuse", method: "POST" });- }- });-- it("audits a 403 the route answers itself, and lets other errors through as before", async () => {- const before = auditCount("denied");- expect((await handler({}, () => Response.json({ error: "no" }, { status: 403 }))(request("/self"))).status).toBe(403);- expect(auditCount("denied")).toBe(before + 1);- await expect(- handler({}, () => {- throw new Error("boom");- })(request("/boom")),- ).rejects.toThrow("boom");- });-- it("audits a hidden record's 404 at most once a minute per person and route", async () => {- const hidden = handler({}, () => {- throw new errors.NotFoundError("Not found", true);- });- const before = auditCount("denied.hidden");- for (let i = 0; i < 3; i++) expect((await hidden(request("/hidden/1"))).status).toBe(404);- expect(auditCount("denied.hidden")).toBe(before + 1);- await hidden(request("/hidden/1", { bearer: tokenFor(member) }));- expect(auditCount("denied.hidden")).toBe(before + 2);- });-- it("refuses an unknown permission when the route is declared", () => {- expect(() => handler({ access: "perm:nope.nothing" }, () => new Response())).toThrow(/Unknown permission/);- });-- it("treats a restricted session outside its kind's routes as signed out", () => {- registerRestrictedKind("accept-terms", (p) => p.startsWith("/api/terms"));- expect(restrictedAllows("accept-terms", "/api/terms/accept", "POST")).toBe(true);- expect(restrictedAllows("accept-terms", "/api/settings", "PUT")).toBe(false);- expect(restrictedAllows("enroll-2fa", "/api/terms/accept", "POST")).toBe(false);- });-- it("acts as a substituted person (view-as), keeping the real one and making it read-only", async () => {- const viewed = seedPerson({ role: "member" });- registerActorSubstitute((a, req) => (req.headers.get("x-test-view-as") === viewed ? { ...a, userId: viewed, role: "member" } : null));- let seen: ReturnType<typeof currentActor> | undefined;- const who = handler({}, () => {- seen = currentActor();- return Response.json({});- });- await who(request("/x", { headers: { "x-test-view-as": viewed } }));- expect(seen).toMatchObject({ userId: viewed, impersonatorId: "u_owner" });- expect(perms.can(seen, "install.settings")).toBe(false);- const res = await settingsRoute.PUT(request("/api/settings", { method: "PUT", body: {}, headers: { "x-test-view-as": viewed } }));- expect(res.status).toBe(403);- expect(JSON.parse(lastAudit().meta_json)).toMatchObject({ impersonator: "u_owner" });- });-});--describe("roles and permissions", () => {- it("gives the owner everything, an admin the day-to-day permissions, a member none", () => {- for (const p of perms.permissions()) expect(perms.roleCan("owner", p), p).toBe(true);- expect(perms.roleCan("admin", "install.settings")).toBe(true);- for (const p of ["install.mode", "people.roles", "support.view_as", "credits.adjust"]) expect(perms.roleCan("admin", p), p).toBe(false);- for (const p of perms.permissions()) expect(perms.roleCan("member", p), p).toBe(false);- expect(perms.roleCan("nobody", "install.settings")).toBe(false);- });-- it("lets packages register roles and permissions (a family grant covers its names), but never replace the owner", () => {- perms.registerPermission("billing.refund");- perms.registerRole("billing", { label: "Billing", rank: 40, grants: ["billing.*"] });- expect(perms.permissionExists("billing.refund")).toBe(true);- expect(perms.roleCan("billing", "billing.refund")).toBe(true);- expect(perms.roleCan("billing", "install.settings")).toBe(false);- expect(perms.roles().map((r) => r.name)).toEqual(["owner", "admin", "billing", "member"]);- expect(() => perms.registerRole("owner", { label: "Owner", rank: 1, grants: [] })).toThrow();- });-- it("answers can() for the server, tokens and nobody", () => {- expect(perms.can(SYSTEM, "install.mode")).toBe(true);- expect(perms.can(null, "install.settings")).toBe(false);- expect(perms.can(LOCAL_OWNER, "install.settings")).toBe(true);- expect(perms.can(actor("u_owner", "owner", { via: "token", scopes: ["generate"] }), "install.settings")).toBe(false);- expect(perms.can(actor(admin, "admin", { via: "token", scopes: ["admin"] }), "install.settings")).toBe(true);- });-- it("answers team roles through effectiveTeamRole only, with clamps that only lower", () => {- const viewer = seedPerson();- const team = seedTeam("Studio A", { [admin]: "admin", [member]: "member", [viewer]: "viewer" });- const as = (id: string, o = {}) => actor(id, "member", o);- expect(perms.effectiveTeamRole(as(admin), team)).toBe("admin");- expect(perms.effectiveTeamRole(as(member), team)).toBe("member");- expect(perms.effectiveTeamRole(as(viewer), team)).toBe("viewer");- expect(perms.effectiveTeamRole(as("u_owner"), team)).toBeNull();- expect(perms.effectiveTeamRole(LOCAL_OWNER, "w_owner")).toBe("owner");- expect(perms.effectiveTeamRole(SYSTEM, team)).toBe("owner");- // View-as is read-only.- expect(perms.effectiveTeamRole(as(admin, { impersonatorId: "u_owner" }), team)).toBe("viewer");- // A view-only seat is a Viewer; a clamp that tries to raise is ignored.- perms.registerTeamRoleClamp((a, _w, role) => (a.userId === member ? "viewer" : role));- perms.registerTeamRoleClamp((a, _w, role) => (a.userId === viewer ? "owner" : role));- expect(perms.effectiveTeamRole(as(member), team)).toBe("viewer");- expect(perms.effectiveTeamRole(as(viewer), team)).toBe("viewer");- expect(perms.teamRoleAtLeast("admin", "member")).toBe(true);- expect(perms.teamRoleAtLeast("viewer", "member")).toBe(false);- expect(perms.TEAM_ROLE_LABEL.member).toBe("Editor");- });-});--describe("gates", () => {- it("are open in the core, and refuse with a 403 once a package registers a check", () => {- expect(gateRefusal("share.create", LOCAL_OWNER)).toBeNull();- expect(() => gate("share.create", LOCAL_OWNER)).not.toThrow();- registerGate("share.create", (a) => (a.role === "member" ? { code: "PLAN", message: "Your plan doesn't include share links." } : null));- expect(() => gate("share.create", actor(member))).toThrow(errors.ForbiddenError);- expect(gateRefusal("share.create", LOCAL_OWNER)).toBeNull();- });-});--describe("the test harness", () => {- let inBeforeAll: string | undefined;- beforeAll(() => {- inBeforeAll = maybeActor()?.userId;- });-- it("runs every test as the local owner, from beforeAll on", async () => {- expect(inBeforeAll).toBe("u_owner");- await new Promise((r) => setTimeout(r, 1));- expect(currentActor()).toEqual(LOCAL_OWNER);- });-- it("acts as nobody after asNobody(): currentActor() throws", async () => {- asNobody();- await Promise.resolve();- expect(maybeActor()).toBeNull();- expect(() => currentActor()).toThrow(/No one is acting/);- });-- it("is the local owner again in the next test", () => {- expect(currentActor().userId).toBe("u_owner");- });-});--describe("denials that can't flood the log", () => {- it("writes a public route's own 403 for nobody at most once a minute per address and route, counting the rest", async () => {- await setOwnerPassword("correct horse battery");- try {- // Better Auth's router answers 403 to every endpoint it keeps closed.- const blocked = handler({ access: "public" }, () => Response.json({ error: "blocked" }, { status: 403 }));- const send = (o: { bearer?: string } = {}) => blocked(request("/api/identity/sign-up/email", { method: "POST", body: {}, ...o }));- const before = auditCount("denied");- for (let i = 0; i < 20; i++) expect((await send()).status).toBe(403);- expect(auditCount("denied")).toBe(before + 1);- expect(lastAudit()).toMatchObject({ actor_id: null });- // A signed-in person's 403s are each written.- const token = tokenFor(member);- for (let i = 0; i < 3; i++) await send({ bearer: token });- expect(auditCount("denied")).toBe(before + 4);- // A minute on, the next one is written and says how many were held back.- vi.useFakeTimers({ now: Date.now() + 61_000, toFake: ["Date"] });- try {- await send();- } finally {- vi.useRealTimers();- }- expect(auditCount("denied")).toBe(before + 5);- expect(JSON.parse(lastAudit().meta_json)).toMatchObject({ path: "/api/identity/sign-up/email", reason: "route", more: 19 });- } finally {- await setOwnerPassword(null);- }- });-- it("counts hidden-record 404s per person and route, not per id", async () => {- const hidden = handler({}, async (_req: Request, ctx: { params: Promise<{ id: string }> }) => {- await ctx.params;- throw new errors.NotFoundError("Not found", true);- });- const before = auditCount("denied.hidden");- for (let i = 0; i < 50; i++) expect((await hidden(request(`/api/generations/id-${i}`), { params: Promise.resolve({ id: `id-${i}` }) })).status).toBe(404);- expect(auditCount("denied.hidden")).toBe(before + 1);- expect(JSON.parse(lastAudit().meta_json)).toMatchObject({ path: "/api/generations/id-0" });- });-- it("names a route's dynamic segments from the params Next matched", async () => {- expect(await routePattern("/api/generations/g_1", { params: Promise.resolve({ id: "g_1" }) })).toBe("/api/generations/[id]");- expect(await routePattern("/s/tok/f/a/b%20c.png", { params: Promise.resolve({ token: "tok", path: ["a", "b c.png"] }) })).toBe("/s/[token]/f/[...path]");- expect(await routePattern("/api/settings", undefined)).toBe("/api/settings");- });-- it("audits a turned-off person's refused credentials under their name", async () => {- const off = seedPerson({ role: "member" });- const token = tokenFor(off);- updatePerson(off, { status: "disabled" });- const echo = handler({}, () => Response.json({}));- const before = auditCount("denied");- const res = await echo(request("/api/mcp", { method: "POST", body: {}, bearer: token }));- expect(res.status).toBe(403);- expect(await res.json()).toMatchObject({ code: "ACCOUNT_DISABLED" });- expect(auditCount("denied")).toBe(before + 1);- expect(lastAudit()).toMatchObject({ actor_id: off, actor_via: "token" });- expect(JSON.parse(lastAudit().meta_json)).toMatchObject({ reason: "ACCOUNT_DISABLED", path: "/api/mcp", method: "POST" });- });-});--describe("refusals the studios pass on", () => {- it("answers a refusal thrown inside a studio's error helper with its status, and audits each 403", async () => {- const cinema = await import("@/server/cinema-schemas");- const faceless = await import("@/server/faceless");- const factory = await import("@/server/content-factory");- const shorts = await import("@/server/shorts-schemas");- const { failure } = await import("@/server/marketing");- const { recipeFailure } = await import("@/server/recipe-routes");- const caught = (answer: (e: unknown) => Response) => (fn: () => never) => {- try {- return fn();- } catch (e) {- return answer(e);- }- };- const wrappers: [string, (fn: () => never) => Response | Promise<Response>][] = [- ["cinema", cinema.handle],- ["faceless", faceless.handle],- ["content factory", factory.handle],- ["shorts", shorts.handle],- ["marketing", caught(failure)],- ["recipes", caught(recipeFailure)],- ];- const refusals: [Error, number][] = [- [new errors.ForbiddenError("No.", "NOPE"), 403],- [new errors.NotFoundError(), 404],- [new errors.PaymentRequiredError(), 402],- [new errors.ReauthRequiredError(), 403],- ];- for (const [name, wrap] of wrappers) {- for (const [e, status] of refusals) {- const before = auditCount("denied");- const res = await handler({}, () =>- wrap(() => {- throw e;- }),- )(request(`/studio/${name.replace(/ /g, "-")}`, { method: "POST", body: {} }));- expect(res.status, `${name}: ${e.name}`).toBe(status);- expect(((await res.json()) as { error: string }).error, `${name}: ${e.name}`).toBe(e.message);- expect(auditCount("denied"), `${name}: ${e.name}`).toBe(before + (status === 403 ? 1 : 0));- }- // Anything else is still the studio's own answer.- const own = await handler({}, () =>- wrap(() => {- throw new Error("Pick a clip first");- }),- )(request("/studio/own", { method: "POST", body: {} }));- expect([422, 500], name).toContain(own.status);- }- });-});diff --git a/tests/assist-connectors.test.ts b/tests/assist-connectors.test.tsindex 0b51163d..a61b243d 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(new Request("http://localhost/"));+ const res = await listRoute.GET();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(new Request("http://localhost/"))).text();+ const body = await (await listRoute.GET()).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/audit-log.test.ts b/tests/audit-log.test.tsdeleted file mode 100644index 4982b0da..00000000--- a/tests/audit-log.test.ts+++ /dev/null@@ -1,191 +0,0 @@-/**- * The audit log (docs/research/accounts-8.md §7.14): audit() takes who acted, from where and with which browser from- * the request scope, never records a secret, and appends to a hash-chained table that refuses UPDATE and DELETE.- * verifyAuditChain() answers "Records verified up to {time}" or "The record changed after {time}".- */-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";--const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-audit-"));-process.env.FUOBE_DATA_DIR = dir;-const { db } = await import("@/server/db");-const { audit, auditDenied, verifyAuditChain } = await import("@/server/access/audit");-const { withScope, runAs, asSystem, LOCAL_OWNER } = await import("@/server/access/actor");-const { appendAudit } = await import("@/server/identity/audit-log");-const { actor, asNobody } = await import("./helpers/actors");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));--interface Row {- seq: number;- at: number;- actor_id: string | null;- actor_via: string | null;- action: string;- target_kind: string | null;- target_id: string | null;- meta_json: string;- ip: string | null;- user_agent: string | null;-}-const last = () => db().prepare("SELECT * FROM audit_log ORDER BY seq DESC LIMIT 1").get() as Row;--describe("audit()", () => {- it("records the acting person, their address and browser from the request scope", () => {- const person = actor("u_alex", "member", { via: "token", tokenId: "t1" });- withScope({ actor: person, ip: "203.0.113.7", userAgent: "curl/8", method: "PUT", path: "/api/settings" }, () =>- audit("install.setting_changed", { kind: "setting", id: "engine.mode" }, { from: "both", to: "open" }),- );- const row = last();- expect(row).toMatchObject({ action: "install.setting_changed", actor_id: "u_alex", actor_via: "token", target_kind: "setting", target_id: "engine.mode", ip: "203.0.113.7", user_agent: "curl/8" });- expect(JSON.parse(row.meta_json)).toEqual({ tokenId: "t1", from: "both", to: "open" });- });-- it("names the runner's row owner, the server, and the real person behind a view-as", () => {- runAs({ ...LOCAL_OWNER, via: "runner" }, () => audit("generation.settled"));- expect(last()).toMatchObject({ actor_id: "u_owner", actor_via: "runner", ip: null });- asSystem(() => audit("housekeeping.swept"));- expect(last()).toMatchObject({ actor_id: "system", actor_via: "system" });- runAs(actor("u_alex", "member", { impersonatorId: "u_owner" }), () => audit("content.viewed"));- expect(JSON.parse(last().meta_json)).toEqual({ impersonator: "u_owner" });- });-- it("records nobody when no one is acting (a public route answered for nobody)", () => {- asNobody();- audit("auth.sign_in_failed", null, { reason: "wrong password" });- expect(last()).toMatchObject({ actor_id: null, actor_via: null });- });-- it("never writes a secret, whatever the caller passed", () => {- audit("keys.changed", null, {- setting: "fal.key",- apiKey: "sk-live-123",- password: "hunter2",- nested: { client_secret: "abc", authorization: "Bearer x", tokenPrefix: "fuobe_abcd" },- tokenId: "keep-me",- prefix: "sk-li…",- });- const meta = JSON.parse(last().meta_json);- expect(meta).toEqual({- setting: "fal.key",- apiKey: "[redacted]",- password: "[redacted]",- nested: { client_secret: "[redacted]", authorization: "[redacted]", tokenPrefix: "fuobe_abcd" },- tokenId: "keep-me",- prefix: "sk-li…",- });- expect(last().meta_json).not.toMatch(/sk-live|hunter2|Bearer x/);- });-- it("knows Fuobe's own key names, plain key and value fields, values shaped like a key, and lists", () => {- audit("keys.set", null, {- falKey: "fal-SECRET-1",- anthropicKey: "sk-ant-SECRET",- "fal.key": "SECRET-dotted",- openaiKey: "sk-SECRET-openai",- replicateToken: "r8_SECRETSECRETSECRET",- key: "plain-SECRET",- list: [{ password: "SECRET-in-a-list" }, "fuobe_SECRETSECRETSECRET1234"],- note: "sk-ant-api03-SECRETSECRETSECRET",- falLike: "0f1e2d3c-4b5a-6978-8a9b-0c1d2e3f4a5b:00112233445566778899aabbccddeeff",- header: "Bearer SECRET-bearer-value",- maskedKey: "sk-a••••cret",- keyPrefix: "sk-ant-",- keyName: "anthropicKey",- });- const meta = JSON.parse(last().meta_json);- expect(meta).toEqual({- falKey: "[redacted]",- anthropicKey: "[redacted]",- "fal.key": "[redacted]",- openaiKey: "[redacted]",- replicateToken: "[redacted]",- key: "[redacted]",- list: [{ password: "[redacted]" }, "[redacted]"],- note: "[redacted]",- falLike: "[redacted]",- header: "[redacted]",- maskedKey: "sk-a••••cret",- keyPrefix: "sk-ant-",- keyName: "anthropicKey",- });- expect(last().meta_json).not.toMatch(/SECRET/);- });-- it("keeps a setting's name but not its value: a key/value pair, or from/to on a secret setting's entry", () => {- audit("keys.set", null, { key: "falKey", value: "fal-SECRET-2" });- expect(JSON.parse(last().meta_json)).toEqual({ key: "falKey", value: "[redacted]" });- audit("install.setting_changed", null, { setting: "anthropic.key", from: "", to: "sk-ant-SECRET-3" });- expect(JSON.parse(last().meta_json)).toEqual({ setting: "anthropic.key", from: "", to: "[redacted]" });- audit("install.setting_changed", { kind: "setting", id: "fal.key" }, { from: "old-SECRET", to: "new-SECRET" });- expect(JSON.parse(last().meta_json)).toEqual({ from: "[redacted]", to: "[redacted]" });- // An ordinary setting keeps its values.- audit("install.setting_changed", { kind: "setting", id: "engine.mode" }, { key: "engineMode", from: "both", to: "open" });- expect(JSON.parse(last().meta_json)).toEqual({ key: "engineMode", from: "both", to: "open" });- });-- it("records a denial with the route and the reason", () => {- withScope({ actor: actor("u_alex"), method: "POST", path: "/api/loras" }, () => auditDenied("FORBIDDEN"));- expect(last().action).toBe("denied");- expect(JSON.parse(last().meta_json)).toEqual({ method: "POST", path: "/api/loras", reason: "FORBIDDEN" });- });-});--describe("the append-only, hash-chained table", () => {- it("refuses UPDATE and DELETE", () => {- const { seq } = last();- expect(() => db().prepare("UPDATE audit_log SET action = 'x' WHERE seq = ?").run(seq)).toThrow(/append-only/);- expect(() => db().prepare("DELETE FROM audit_log WHERE seq = ?").run(seq)).toThrow(/append-only/);- expect(() => db().exec("DELETE FROM audit_log")).toThrow(/append-only/);- expect(last().seq).toBe(seq);- });-- it("verifies up to the last row", () => {- for (let i = 0; i < 5; i++) audit("test.entry", { kind: "n", id: String(i) });- const check = verifyAuditChain();- const rows = (db().prepare("SELECT COUNT(*) AS n FROM audit_log").get() as { n: number }).n;- expect(check).toEqual({ ok: true, rows, verifiedUpTo: last().at });- });-- it("chains each row to the one before it (prev_hash is the previous row's hash)", () => {- const rows = db().prepare("SELECT prev_hash, hash FROM audit_log ORDER BY seq").all() as { prev_hash: string; hash: string }[];- expect(rows[0].prev_hash).toBe("");- for (let i = 1; i < rows.length; i++) expect(rows[i].prev_hash).toBe(rows[i - 1].hash);- });-- it("keeps the bare writer and audit() on one chain", () => {- appendAudit({ action: "auth.sign_in", actorId: "u_owner", via: "session" });- audit("token.created", { kind: "token", id: "t2" });- const [a, b] = (db().prepare("SELECT prev_hash, hash FROM audit_log ORDER BY seq DESC LIMIT 2").all() as { prev_hash: string; hash: string }[]).reverse();- expect(b.prev_hash).toBe(a.hash);- expect(verifyAuditChain().ok).toBe(true);- });-- // Someone with the database file can lift a trigger; the chain still tells.- const behindTheTriggers = (trigger: "audit_log_append_only" | "audit_log_no_delete", sql: string, seq: number) => {- const create = (db().prepare("SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = ?").get(trigger) as { sql: string }).sql;- db().exec(`DROP TRIGGER ${trigger}`);- try {- db().prepare(sql).run(seq);- } finally {- db().exec(create);- }- };-- it("finds a row changed behind the triggers' back, and says from when", () => {- const rows = db().prepare("SELECT seq, at FROM audit_log ORDER BY seq").all() as { seq: number; at: number }[];- behindTheTriggers("audit_log_append_only", `UPDATE audit_log SET meta_json = '{"to":"edited"}' WHERE seq = ?`, rows[3].seq);- const check = verifyAuditChain();- expect(check).toEqual({ ok: false, rows: 3, verifiedUpTo: rows[2].at, brokenAt: { seq: rows[3].seq, at: rows[3].at } });- });-- it("finds a row removed from the middle (earlier than the change, so that is where it breaks now)", () => {- const rows = db().prepare("SELECT seq, at FROM audit_log ORDER BY seq").all() as { seq: number; at: number }[];- behindTheTriggers("audit_log_no_delete", "DELETE FROM audit_log WHERE seq = ?", rows[1].seq);- const check = verifyAuditChain();- expect(check).toEqual({ ok: false, rows: 1, verifiedUpTo: rows[0].at, brokenAt: { seq: rows[2].seq, at: rows[2].at } });- // The triggers are back.- expect(() => db().prepare("DELETE FROM audit_log WHERE seq = ?").run(rows[0].seq)).toThrow(/append-only/);- });-});diff --git a/tests/canvas-api.test.ts b/tests/canvas-api.test.tsindex 4591a15e..629830a5 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(new Request("http://localhost/"));+ res = await list.GET();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(new Request("http://localhost/"))).json()) as { items: CanvasSummary[] }).items.find((c) => c.id === id)!;+ const listed = ((await (await list.GET()).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(new Request("http://localhost/"))).json()) as { items: CanvasSummary[] }).items.find((c) => c.id === id)!;+ const card = ((await (await list.GET()).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 9f102092..484d696f 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(new Request("http://localhost/"))).json()) as { items: { id: string; pageCount: number; nodeCount: number }[] }).items.find((x) => x.id === c.id)!;+ const card = ((await (await list.GET()).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 00977042..4aa2efb6 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(new Request("http://localhost/"))).json()) as { onboarded: boolean }).onboarded;+ const onboarded = async () => ((await (await statusRoute()).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 ffdf6a80..e87b97df 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(new Request("http://localhost/"))],+ ["GET", /^\/api\/status$/, () => status.GET()],["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 afba9c7e..0449adf1 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, ctx?: unknown) => Promise<Response> } = estimateRoute) => {+ const say = async (b: Record<string, unknown>, route: { POST: (r: Request) => 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/helpers/actors.ts b/tests/helpers/actors.tsdeleted file mode 100644index 47af6bf7..00000000--- a/tests/helpers/actors.ts+++ /dev/null@@ -1,100 +0,0 @@-/**- * People, teams and requests for tests (docs/research/accounts-8.md §13). Every test acts as the local owner, "Just me- * on this computer" (tests/setup/actor.ts); these helpers seed other people, roles and teams, act as nobody or as- * someone else, and build the requests a browser or a CLI would send: from this computer, with a bearer token, or- * with a session cookie (tests/helpers/identity.ts signs the owner in). Each test file sets FUOBE_DATA_DIR before- * importing Fuobe.- */-import crypto from "node:crypto";-import { enterAs, LOCAL_OWNER, maybeActor, runAs, SYSTEM, type Actor } from "@/server/access/actor";-import type { TeamRole } from "@/server/access/permissions";-import { db } from "@/server/db";-import { createToken } from "@/server/identity/tokens";--export { LOCAL_OWNER, maybeActor, runAs, SYSTEM };--/** The rest of this test runs as nobody: server code that asks who is acting throws. */-export function asNobody(): void {- enterAs(null);-}--/** The rest of this test runs as `actor` (the local owner by default). */-export function actAs(actor: Actor = LOCAL_OWNER): void {- enterAs(actor);-}--/** An actor as handler() would resolve it (a session by default). */-export function actor(userId: string, role = "member", o: Partial<Actor> = {}): Actor {- return { userId, role, via: "session", scopes: ["full"], ...o };-}--export interface SeedPerson {- id?: string;- role?: string;- status?: "active" | "pending" | "disabled" | "deleted";- dormant?: boolean;-}--/** A person (a `users` row) with a personal workspace they own. Returns their id. */-export function seedPerson(p: SeedPerson = {}): string {- const id = p.id ?? `u_${crypto.randomBytes(6).toString("hex")}`;- const ws = `w_${id.slice(2)}`;- const now = Date.now();- db()- .prepare(- `INSERT INTO users (id, role, status, dormant, personal_workspace_id, source, created_at, updated_at)- VALUES (?, ?, ?, ?, ?, 'admin', ?, ?)`,- )- .run(id, p.role ?? "member", p.status ?? "active", p.dormant ? 1 : 0, ws, now, now);- db().prepare("INSERT INTO workspaces (id, kind, name, slug, created_by, created_at, updated_at) VALUES (?, 'personal', 'Personal', ?, ?, ?, ?)").run(ws, ws, id, now, now);- db().prepare("INSERT INTO workspace_members (workspace_id, user_id, role, source, created_at) VALUES (?, ?, 'owner', 'manual', ?)").run(ws, id, now);- return id;-}--/** Change a seeded person (turn them off, make them dormant, change their role). */-export function updatePerson(id: string, p: Omit<SeedPerson, "id">): void {- if (p.role) db().prepare("UPDATE users SET role = ? WHERE id = ?").run(p.role, id);- if (p.status) db().prepare("UPDATE users SET status = ? WHERE id = ?").run(p.status, id);- if (p.dormant !== undefined) db().prepare("UPDATE users SET dormant = ? WHERE id = ?").run(p.dormant ? 1 : 0, id);-}--/** A team workspace with these members and roles. Returns its id. */-export function seedTeam(name: string, members: Record<string, TeamRole>): string {- const id = `w_${crypto.randomBytes(6).toString("hex")}`;- const now = Date.now();- db().prepare("INSERT INTO workspaces (id, kind, name, slug, created_at, updated_at) VALUES (?, 'team', ?, ?, ?, ?)").run(id, name, id, now, now);- for (const [userId, role] of Object.entries(members)) {- db().prepare("INSERT INTO workspace_members (workspace_id, user_id, role, source, created_at) VALUES (?, ?, ?, 'manual', ?)").run(id, userId, role, now);- }- return id;-}--/** A live API token for a person, with these scopes (Full by default). Returns the token itself. */-export function tokenFor(userId: string, scopes: string[] = ["full"]): string {- const { token, info } = createToken(userId, "Test");- db().prepare("UPDATE api_tokens SET scopes = ? WHERE id = ?").run(scopes.join(","), info.id);- return token;-}--export interface RequestOptions {- method?: string;- body?: unknown;- headers?: Record<string, string>;- /** Sent as Authorization: Bearer … */- bearer?: string;- /** Sent as the Cookie header (tests/helpers/identity.ts ownerCookie). */- cookie?: string;- /** The address the request arrives at (localhost: Just me on this computer when sign-in is off). */- origin?: string;-}--/** A request the way a browser or the CLI sends it to `path`. */-export function request(path: string, o: RequestOptions = {}): Request {- const origin = o.origin ?? "http://localhost:3000";- const headers: Record<string, string> = { host: new URL(origin).host, ...o.headers };- if (o.bearer) headers.authorization = `Bearer ${o.bearer}`;- if (o.cookie) headers.cookie = o.cookie;- const method = o.method ?? (o.body === undefined ? "GET" : "POST");- if (o.body !== undefined) headers["content-type"] ??= "application/json";- return new Request(new URL(path, origin), { method, headers, ...(o.body !== undefined && { body: typeof o.body === "string" ? o.body : JSON.stringify(o.body) }) });-}diff --git a/tests/image-studios-api.test.ts b/tests/image-studios-api.test.tsindex cce333ec..196a27a2 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(new Request("http://localhost/"))).json()).targets as { id: string; price: string; blocker: string | null; demo: boolean }[];+ const targets = (await (await trainRoute.GET()).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 f08dc3cc..68c93dcc 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(new Request("http://localhost/"));+ res = await list.GET();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(new Request("http://localhost/"));+ res = await list.GET();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(new Request("http://localhost/"))).json()) as { items: LayerProject[] }).items.find((p) => p.id === v.project.id);+ const card = ((await (await list.GET()).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 6f104669..d376c9a9 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(new Request("http://localhost/"))).json()) as { items: { id: string }[] }).items.map((x) => x.id)).toContain(f.id);+ expect(((await (await folderRoutes.GET()).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(new Request("http://localhost/"))).json()) as { items: { id: string; parentId: string | null }[] }).items;+ const all = ((await (await folderRoutes.GET()).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 c9daea1d..e4addb78 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(new Request("http://localhost/"));+ const res = await route.GET();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(new Request("http://localhost/"));+ const res = await route.GET();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(new Request("http://localhost/"))).json()) as { folderProblem?: string }).folderProblem).toMatch(/doesn't exist on this machine/);+ expect(((await (await route.GET()).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 8b37572d..accf57d8 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(new Request("http://localhost/"))).json();+ const list = await (await brandsRoute.GET()).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/mcp-actor.test.ts b/tests/mcp-actor.test.tsdeleted file mode 100644index 35284e8f..00000000--- a/tests/mcp-actor.test.ts+++ /dev/null@@ -1,125 +0,0 @@-/**- * MCP receives the actor (docs/research/accounts-8.md §7.10, acc-2): /api/mcp resolves the token's (or session's)- * person through handler() and hands it to handleMcp(body, actor), and every tool the message runs acts for that- * person — in its ToolContext and as the scope's actor. The route's Origin check still refuses other sites (and the- * refusal is audited).- */-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it, vi } from "vitest";-import type { ToolContext } from "@/server/assist/define";--const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-mcp-actor-"));-process.env.FUOBE_DATA_DIR = dir;-process.env.COMFYUI_URL = "http://127.0.0.1:9";--/** What each tool call saw: the context's actor and the scope's (and the whole scope). */-const calls: { name: string; ctxActor: unknown; scopeActor: unknown }[] = [];-const scopes: unknown[] = [];-vi.mock("@/server/assist/tools", async (importOriginal) => {- const real = await importOriginal<typeof import("@/server/assist/tools")>();- const { maybeActor, requestScope } = await import("@/server/access/actor");- return {- ...real,- executeTool: async (name: string, input: unknown, ctx: ToolContext) => {- calls.push({ name, ctxActor: ctx.actor, scopeActor: maybeActor() });- scopes.push(requestScope());- return real.executeTool(name, input, ctx);- },- };-});--const { handleMcp } = await import("@/server/mcp");-const route = await import("@/app/api/mcp/route");-const { db } = await import("@/server/db");-const { runAs, withScope, SYSTEM, LOCAL_OWNER } = await import("@/server/access/actor");-const { seedPerson, tokenFor, request, actor, asNobody } = await import("./helpers/actors");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));--const call = (name: string, args: unknown = {}) => ({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } });--describe("handleMcp(body, actor)", () => {- it("runs each tool for the actor it is given, whoever is acting around it", async () => {- const alex = actor(seedPerson(), "member", { via: "token", tokenId: "t1" });- calls.length = 0;- const res = await runAs(SYSTEM, () => handleMcp(call("search_models", { query: "video" }), alex));- expect(res).toMatchObject({ result: {} });- expect(calls).toEqual([{ name: "search_models", ctxActor: alex, scopeActor: alex }]);- });-- it("acts for whoever the scope says when no actor is passed, and refuses to act for nobody", async () => {- calls.length = 0;- await handleMcp(call("list_elements"));- expect(calls[0]).toMatchObject({ ctxActor: LOCAL_OWNER, scopeActor: LOCAL_OWNER });- asNobody();- await expect(handleMcp(call("list_elements"))).rejects.toThrow(/No one is acting/);- });-});--describe("POST /api/mcp", () => {- const post = (body: unknown, o: { bearer?: string; headers?: Record<string, string> } = {}) => route.POST(request("/api/mcp", { body, ...o }));-- it("hands the bearer token's person to the tools", async () => {- const member = seedPerson();- calls.length = 0;- const res = await post(call("search_models", { query: "image" }), { bearer: tokenFor(member) });- expect(res.status).toBe(200);- expect(calls[0].ctxActor).toMatchObject({ userId: member, role: "member", via: "token" });- expect(calls[0].scopeActor).toEqual(calls[0].ctxActor);- });-- it("hands Just me on this computer the local owner", async () => {- calls.length = 0;- expect((await post(call("list_elements"))).status).toBe(200);- expect(calls[0].ctxActor).toEqual(LOCAL_OWNER);- });-- it("keeps the Origin check, and audits the refusal", async () => {- const before = (db().prepare("SELECT COUNT(*) AS n FROM audit_log WHERE action = 'denied'").get() as { n: number }).n;- const res = await post({ jsonrpc: "2.0", id: 1, method: "ping" }, { headers: { origin: "https://evil.example" } });- expect(res.status).toBe(403);- expect(await res.json()).toMatchObject({ error: { code: -32000, message: "Origin not allowed" } });- expect((db().prepare("SELECT COUNT(*) AS n FROM audit_log WHERE action = 'denied'").get() as { n: number }).n).toBe(before + 1);- expect((await post({ jsonrpc: "2.0", id: 1, method: "ping" }, { headers: { origin: "http://localhost:3000" } })).status).toBe(200);- });-- it("offers a Read-only token the read tools only, and refuses (and audits) a tool that makes things", async () => {- const member = seedPerson();- const read = tokenFor(member, ["read"]);- const init = await post({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18" } }, { bearer: read });- expect(init.status).toBe(200);- const listed = (await (await post({ jsonrpc: "2.0", id: 2, method: "tools/list" }, { bearer: read })).json()) as { result: { tools: { name: string; annotations: { readOnlyHint: boolean } }[] } };- const names = listed.result.tools.map((t) => t.name);- expect(names).toEqual(expect.arrayContaining(["search_models", "check_generations", "estimate_cost"]));- expect(names).not.toContain("generate");- expect(listed.result.tools.every((t) => t.annotations.readOnlyHint)).toBe(true);- calls.length = 0;- expect((await post(call("search_models", { query: "video" }), { bearer: read })).status).toBe(200);- expect(calls.map((c) => c.name)).toEqual(["search_models"]);- const before = (db().prepare("SELECT COUNT(*) AS n FROM audit_log WHERE action = 'denied'").get() as { n: number }).n;- calls.length = 0;- const refused = (await (await post(call("generate", { prompt: "a lighthouse", modelId: "nano-banana-pro" }), { bearer: read })).json()) as { result: { isError: boolean; content: { text: string }[] } };- expect(refused.result.isError).toBe(true);- expect(refused.result.content[0].text).toMatch(/Read only/);- expect(calls).toEqual([]);- const row = db().prepare("SELECT * FROM audit_log ORDER BY seq DESC LIMIT 1").get() as { action: string; actor_id: string; meta_json: string };- expect((db().prepare("SELECT COUNT(*) AS n FROM audit_log WHERE action = 'denied'").get() as { n: number }).n).toBe(before + 1);- expect(row).toMatchObject({ action: "denied", actor_id: member });- expect(JSON.parse(row.meta_json)).toMatchObject({ reason: "TOKEN_SCOPE", tool: "generate", path: "/api/mcp" });- // A Generate token gets them all.- const all = (await (await post({ jsonrpc: "2.0", id: 3, method: "tools/list" }, { bearer: tokenFor(member, ["generate"]) })).json()) as { result: { tools: { name: string }[] } };- expect(all.result.tools.map((t) => t.name)).toContain("generate");- });-- it("keeps the request's address and browser in the scope the tools run in", async () => {- const alex = actor(seedPerson(), "member", { via: "token", tokenId: "t9" });- scopes.length = 0;- await withScope({ actor: LOCAL_OWNER, ip: "203.0.113.9", userAgent: "mcp-client/1", method: "POST", path: "/api/mcp" }, () => handleMcp(call("list_elements"), alex));- expect(scopes.at(-1)).toMatchObject({ actor: alex, ip: "203.0.113.9", userAgent: "mcp-client/1", method: "POST", path: "/api/mcp" });- });-- it("ignores an invalid token in Just me on this computer, as the proxy does", async () => {- expect((await post({ jsonrpc: "2.0", id: 1, method: "ping" }, { bearer: "fuobe_wrong" })).status).toBe(200);- });-});diff --git a/tests/model-access-listings.test.ts b/tests/model-access-listings.test.tsindex 9922764d..907d0d2e 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(new Request("http://localhost/"))).json()) as { access?: unknown }).access).toBeUndefined();+ expect(((await (await status()).json()) as { access?: unknown }).access).toBeUndefined();changeAccess([{ kind: "provider", id: "replicate", on: false }, { kind: "class", id: "research", on: false }]);- const body = (await (await status(new Request("http://localhost/"))).json()) as { access: { off: string[] } };+ const body = (await (await status()).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(new Request("http://localhost/"))).json()) as import("@/lib/model-access").AccessList;+ const list = (await (await settingsRoute.GET()).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/route-sweep.test.ts b/tests/route-sweep.test.tsdeleted file mode 100644index 554fec64..00000000--- a/tests/route-sweep.test.ts+++ /dev/null@@ -1,111 +0,0 @@-/**- * The route sweep (docs/research/accounts-8.md §13): every route handler under src/app goes through handler()- * (src/server/access/route.ts), so each request resolves who is asking and checks what the route declares. A new- * route.ts that exports a bare function fails here, by file and method.- */-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it, vi } from "vitest";--// Importing every route module once is slow under a parallel run.-vi.setConfig({ testTimeout: 180_000 });--const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-route-sweep-"));-process.env.FUOBE_DATA_DIR = dir;-process.env.COMFYUI_URL = "http://127.0.0.1:9";-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));--const { isWrapped } = await import("@/server/access/route");--const ROOT = path.resolve(__dirname, "..");-const METHODS = ["GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH", "DELETE"];--function routeFiles(d = path.join(ROOT, "src/app")): string[] {- return fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => {- const p = path.join(d, e.name);- if (e.isDirectory()) return routeFiles(p);- return /^route\.(ts|tsx|js|mjs)$/.test(e.name) ? [p] : [];- });-}--const FILES = routeFiles();-const rel = (f: string) => path.relative(ROOT, f);--describe("every route goes through handler()", () => {- it("finds the routes (192 at 545ebb5; more since)", () => {- expect(FILES.length).toBeGreaterThanOrEqual(192);- });-- it("exports no bare handler: each method is `export const X = handler(…)` or a const made by handler()", () => {- const bad: string[] = [];- for (const f of FILES) {- const src = fs.readFileSync(f, "utf8");- const name = rel(f);- for (const m of src.matchAll(/export\s+(?:async\s+)?function\s+(GET|HEAD|OPTIONS|POST|PUT|PATCH|DELETE)\b/g)) bad.push(`${name}: function ${m[1]}`);- for (const m of src.matchAll(/export\s*\{([^}]*)\}/g)) {- for (const part of m[1].split(",")) {- const exported = part.trim().split(/\s+as\s+/).pop()?.trim();- if (exported && METHODS.includes(exported)) bad.push(`${name}: export { … as ${exported} }`);- }- }- for (const m of src.matchAll(/export\s+const\s+(GET|HEAD|OPTIONS|POST|PUT|PATCH|DELETE)\s*=\s*([^;\n]*)/g)) {- const rhs = m[2].trim();- if (rhs.startsWith("handler(")) continue;- const alias = /^([A-Za-z_$][\w$]*)\s*;?$/.exec(rhs)?.[1];- if (alias && new RegExp(`const\\s+${alias}\\s*=\\s*handler\\(`).test(src)) continue;- bad.push(`${name}: ${m[1]} = ${rhs.slice(0, 40)}`);- }- }- expect(bad).toEqual([]);- });-- it("every exported method of every route module is a handler() wrapper", async () => {- const bad: string[] = [];- for (const f of FILES) {- const mod = (await import(f)) as Record<string, unknown>;- const methods = METHODS.filter((m) => m in mod);- if (!methods.length) bad.push(`${rel(f)}: exports no method`);- for (const m of methods) if (!isWrapped(mod[m])) bad.push(`${rel(f)}: ${m}`);- }- expect(bad).toEqual([]);- });-- it("passes refusals on: a catch that answers errors itself starts with rethrowAccess, or rethrows what it doesn't answer", () => {- const bad: string[] = [];- for (const f of FILES) {- const lines = fs.readFileSync(f, "utf8").split("\n");- lines.forEach((l, i) => {- const m = /^(\s*)\}\s*catch\s*\((\w+)\)\s*\{\s*$/.exec(l);- if (!m) return;- const body: string[] = [];- for (let j = i + 1; j < lines.length; j++) {- if (lines[j].trim().startsWith("}") && lines[j].search(/\S/) <= m[1].length) break;- body.push(lines[j].trim());- }- if (body[0] === `rethrowAccess(${m[2]});` || body.at(-1) === `throw ${m[2]};`) return;- bad.push(`${rel(f)}:${i + 1}`);- });- }- expect(bad).toEqual([]);- });-- it("names the four install-config routes as needing install.settings", () => {- const needs = (file: string, method: string) =>- new RegExp(`export\\s+const\\s+${method}\\s*=\\s*handler\\(\\{\\s*access:\\s*"perm:install\\.settings"`).test(fs.readFileSync(path.join(ROOT, file), "utf8"));- expect(needs("src/app/api/settings/route.ts", "PUT")).toBe(true);- expect(needs("src/app/api/settings/models/route.ts", "PUT")).toBe(true);- expect(needs("src/app/api/providers/test/route.ts", "POST")).toBe(true);- expect(needs("src/app/api/loras/route.ts", "POST")).toBe(true);- });-- it("keeps the public routes few: sign-in, sign-out, Better Auth's router and share files", () => {- const open = FILES.filter((f) => /access:\s*"public"/.test(fs.readFileSync(f, "utf8"))).map(rel).sort();- expect(open).toEqual([- "src/app/api/auth/login/route.ts",- "src/app/api/auth/logout/route.ts",- "src/app/api/identity/[...all]/route.ts",- "src/app/s/[token]/f/[...path]/route.ts",- ]);- });-});diff --git a/tests/runners-actor.test.ts b/tests/runners-actor.test.tsdeleted file mode 100644index c3e19598..00000000--- a/tests/runners-actor.test.ts+++ /dev/null@@ -1,302 +0,0 @@-/**- * Runners carry an actor (docs/research/accounts-8.md §7.11): background work runs as the person who started the- * row (runAs(row owner), via "runner"), never as whoever's request happened to start a timer, and a row whose owner- * was turned off fails with "Paused: the account that started this is off." Timers themselves belong to the server- * (asSystem).- */-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import type Anthropic from "@anthropic-ai/sdk";-import type { EpisodeSettings } from "@/lib/catalog/faceless";-import type { SwapProject } from "@/lib/catalog/swap-studio";-import type { PollContext } from "@/server/providers/types";-import { afterAll, afterEach, describe, expect, it, vi } from "vitest";--const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-runners-actor-"));-process.env.FUOBE_DATA_DIR = dir;-process.env.COMFYUI_URL = "http://127.0.0.1:9";-process.env.OLLAMA_URL = "http://127.0.0.1:9";--// No real sweeps in this process: each test drives the runner's ticks itself.-const stubTimer = setInterval(() => {}, 60_000);-clearInterval(stubTimer);-globalThis.__fuobeScheduleRunner = { tick: () => {}, timer: stubTimer };-globalThis.__fuobeFacelessRunner = { tick: () => {}, timer: stubTimer };-globalThis.__fuobeSwapStudioRunner = stubTimer;--const { db } = await import("@/server/db");-const gens = await import("@/server/generations");-const { PROVIDERS } = await import("@/server/providers");-const perms = await import("@/server/access/permissions");-const { maybeActor, currentActor, runAs, asSystem, SYSTEM } = await import("@/server/access/actor");-const sched = await import("@/server/assist/schedules");-const agent = await import("@/server/assist/agent");-const { setSetting } = await import("@/server/settings");-const swap = await import("@/server/swap-studio");-const faceless = await import("@/server/faceless");-const { newSegment, newShot, DEFAULT_SETTINGS } = await import("@/lib/catalog/swap-studio");-const { seedPerson, updatePerson, actor } = await import("./helpers/actors");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));--afterEach(() => {- updatePerson("u_owner", { status: "active", dormant: false });- vi.restoreAllMocks();-});--const who = () => {- const a = maybeActor();- return a && { userId: a.userId, via: a.via };-};--let rows = 0;-function storedRow(r: { status: string; externalId?: string; dependsOn?: string; outputs?: object[]; request?: object; createdAt?: number }): string {- const id = `row-${++rows}`;- const now = r.createdAt ?? Date.now();- db()- .prepare(- `INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, external_id, depends_on, created_at, updated_at)- VALUES (?, 'image', 'nano-banana-pro', 'cloud', 'mock', 'generate', 'image', ?, ?, ?, ?, ?, ?, ?)`,- )- .run(id, r.status, JSON.stringify({ modelId: "nano-banana-pro", prompt: "a lighthouse", ...r.request }), JSON.stringify(r.outputs ?? []), r.externalId ?? null, r.dependsOn ?? null, now, now);- return id;-}--describe("acting for a row's owner", () => {- it("reads the owner from created_by once rows have it, else the install owner", () => {- expect(perms.rowOwner({})).toBe("u_owner");- expect(perms.rowOwner({ created_by: null })).toBe("u_owner");- expect(perms.rowOwner({ created_by: "u_alex" })).toBe("u_alex");- });-- it("acts as that person, via the runner", () => {- const alex = seedPerson({ role: "admin" });- expect(perms.ownerActor(alex)).toEqual({ userId: alex, role: "admin", via: "runner", scopes: ["full"] });- expect(perms.runAsOwner(alex, () => currentActor().userId)).toBe(alex);- expect(perms.runAsOwner(null, () => who())).toEqual({ userId: "u_owner", via: "runner" });- });-- it("refuses for a person who is pending, off, deleted, dormant or unknown", () => {- for (const p of [{ status: "pending" as const }, { status: "disabled" as const }, { status: "deleted" as const }, { dormant: true }]) {- const id = seedPerson(p);- expect(() => perms.ownerActor(id)).toThrow(perms.AccountOffError);- }- expect(() => perms.ownerActor("u_nobody")).toThrow("Paused: the account that started this is off.");- });-});--describe("the generations runner", () => {- async function tickUntil(done: () => boolean) {- gens.ensureRunner();- for (let i = 0; i < 50 && !done(); i++) {- await globalThis.__fuobeRunner!.tick();- await new Promise((r) => setTimeout(r, 10));- }- }-- it("polls a running job as the person who started it, whoever's request started the runner", async () => {- const seen: unknown[] = [];- vi.spyOn(PROVIDERS.mock, "poll").mockImplementation(async () => {- seen.push(who());- return { state: "running", progress: 0.5 };- });- const id = storedRow({ status: "running", externalId: "mock-1" });- // A member's request is what first starts the runner; the timers it sets up still belong to the server.- runAs(actor(seedPerson(), "member"), () => gens.ensureRunner());- await asSystem(() => tickUntil(() => seen.length > 0));- expect(seen[0]).toEqual({ userId: "u_owner", via: "runner" });- db().prepare("UPDATE generations SET status = 'canceled' WHERE id = ?").run(id);- });-- it("fails a running job whose owner was turned off, with the words the plan gives", async () => {- vi.spyOn(PROVIDERS.mock, "poll").mockResolvedValue({ state: "running" });- const id = storedRow({ status: "running", externalId: "mock-2" });- updatePerson("u_owner", { status: "disabled" });- await tickUntil(() => gens.getGeneration(id)?.status === "failed");- expect(gens.getGeneration(id)).toMatchObject({ status: "failed", error: "Paused: the account that started this is off." });- });-- it("cancels the provider's job of an owner who was turned off, so it stops running and charging", async () => {- vi.spyOn(PROVIDERS.mock, "poll").mockResolvedValue({ state: "running" });- // The demo provider has nothing to cancel; a cloud one does.- const cancel = vi.fn<(ctx: PollContext) => Promise<void>>(async () => {});- PROVIDERS.mock.cancel = cancel;- const id = storedRow({ status: "running", externalId: "mock-cancel" });- updatePerson("u_owner", { status: "disabled" });- try {- await tickUntil(() => gens.getGeneration(id)?.status === "failed");- } finally {- delete PROVIDERS.mock.cancel;- }- expect(cancel).toHaveBeenCalledTimes(1);- expect(cancel.mock.calls[0][0]).toMatchObject({ externalId: "mock-cancel" });- expect(gens.getGeneration(id)).toMatchObject({ status: "failed", error: "Paused: the account that started this is off." });- });-- it("drops the steps waiting only to feed a paused one, as a failed step does", async () => {- // A per-frame join: one lane failed, the other still waits on its own input (and is only for the join).- const t0 = Date.now() - 1000;- const input = storedRow({ status: "queued", createdAt: t0 });- const lane = storedRow({ status: "failed", createdAt: t0 });- const join = storedRow({ status: "queued", createdAt: t0 + 1, dependsOn: "" });- const waiting = storedRow({ status: "queued", createdAt: t0 + 2, dependsOn: input, request: { dropWhenUnused: true } });- db().prepare("UPDATE generations SET depends_on = ? WHERE id = ?").run(JSON.stringify([lane, waiting]), join);- updatePerson("u_owner", { status: "disabled" });- await tickUntil(() => gens.getGeneration(join)?.status === "failed");- expect(gens.getGeneration(join)).toMatchObject({ status: "failed", error: "Paused: the account that started this is off." });- expect(gens.getGeneration(waiting)).toMatchObject({ status: "canceled", error: gens.DROPPED_UNUSED });- db().prepare("UPDATE generations SET status = 'canceled' WHERE id = ?").run(input);- });-- it("fails a waiting step of a chain whose owner went dormant, and plans the next one as the owner", async () => {- const parent = storedRow({ status: "succeeded", outputs: [{ url: "/api/files/x.png", kind: "image" }] });- const child = storedRow({ status: "queued", dependsOn: parent });- updatePerson("u_owner", { dormant: true });- await tickUntil(() => gens.getGeneration(child)?.status === "failed");- expect(gens.getGeneration(child)).toMatchObject({ status: "failed", error: "Paused: the account that started this is off." });- });-});--describe("Faceless", () => {- const cloud: EpisodeSettings = {- engine: "cloud",- length: 20,- animation: "animated",- aspect: "16:9",- subtitles: true,- music: false,- styleId: "editorial-motion-graphics",- styleRefs: [],- voice: { kind: "preset", id: "Xb7hH8MSUJpSbSDYk0k2" },- elements: [],- };-- it("doesn't start stage two for an owner who was turned off, whoever looks: the episode fails saying why", async () => {- setSetting("demoMode", "auto");- setSetting("enhanceProvider", "none");- const ep = faceless.createEpisode({ kind: "explainer", topic: "Why bridges sway", settings: cloud, autoRender: true });- await faceless.scriptWritten(ep.id);- const plan = () => JSON.parse((db().prepare("SELECT plan_json FROM faceless_episodes WHERE id = ?").get(ep.id) as { plan_json: string }).plan_json);- // Stage one runs (demo jobs); nobody reads the episode and the sweep is off, so stage two waits for a look.- gens.ensureRunner();- await vi.waitFor(() => expect(Object.values(plan().ids as Record<string, string>).every((id) => gens.getGeneration(id)?.status === "succeeded")).toBe(true), { timeout: 60_000, interval: 200 });- expect(plan().awaiting).toBe(true);- updatePerson("u_owner", { status: "disabled" });- const v = runAs(actor(seedPerson(), "admin"), () => faceless.episodeView(ep.id));- expect(v.episode).toMatchObject({ status: "failed", error: "Paused: the account that started this is off." });- expect(plan().awaiting).toBe(true);- }, 90_000);-});--describe("Assist", () => {- type Block = Anthropic.Beta.BetaContentBlock;- const done = (seen: unknown[]): import("@/server/assist/agent").ModelCall =>- async () => {- seen.push(who());- return { content: [{ type: "text", text: "Done.", citations: null } as Block], stop_reason: "end_turn", stop_details: null } as unknown as Anthropic.Beta.BetaMessage;- };-- it("carries a chat on as its author, whoever's request or schedule carried it", async () => {- setSetting("anthropicKey", "sk-ant-test");- const t = agent.createThread({ engine: "cloud", agent: "claude", title: "Ad" });- agent.addMessage(t.id, "Make an ad");- const seen: unknown[] = [];- await runAs(SYSTEM, () => agent.run(t.id, done(seen)));- expect(seen[0]).toEqual({ userId: "u_owner", via: "runner" });- });-- it("ends a chat whose author was turned off with the plan's words, and leaves it idle", async () => {- const t = agent.createThread({ engine: "cloud", agent: "claude", title: "Off" });- agent.addMessage(t.id, "Make an ad");- updatePerson("u_owner", { status: "disabled" });- const seen: unknown[] = [];- await agent.run(t.id, done(seen));- expect(seen).toEqual([]);- const { thread } = agent.getThread(t.id)!;- expect(thread.status).toBe("idle");- expect(thread.items.at(-1)).toMatchObject({ role: "notice", tone: "error", text: "Paused: the account that started this is off." });- });-- it("runs a scheduled task as the person who owns it, from the server's sweep", async () => {- const T = (s: string) => Date.parse(s);- const s = sched.createSchedule(- { title: "Daily ad", prompt: "Make today's ad", tz: "UTC", engine: "cloud", approval: "ask", rule: { kind: "daily", time: "09:00" } },- T("2026-10-27T08:00:00Z"),- );- const seen: unknown[] = [];- const started = await asSystem(() => sched.sweepSchedules(T("2026-10-27T09:00:30Z"), { model: done(seen) }));- expect(started).toHaveLength(1);- await vi.waitFor(() => expect(seen.length).toBeGreaterThan(0));- expect(seen[0]).toEqual({ userId: "u_owner", via: "runner" });- sched.deleteSchedule(s.id);- });-- it("records a failed run when the task's owner is off, and starts no chat", async () => {- const T = (s: string) => Date.parse(s);- const s = sched.createSchedule(- { title: "Weekly", prompt: "Make the weekly ad", tz: "UTC", engine: "cloud", approval: "ask", rule: { kind: "daily", time: "10:00" } },- T("2026-10-28T08:00:00Z"),- );- updatePerson("u_owner", { status: "disabled" });- const seen: unknown[] = [];- expect(await asSystem(() => sched.sweepSchedules(T("2026-10-28T10:00:30Z"), { model: done(seen) }))).toEqual([]);- expect(seen).toEqual([]);- expect(sched.getSchedule(s.id)?.last).toMatchObject({ status: "failed", text: "Paused: the account that started this is off." });- });-});--describe("Character Swap Studio", () => {- /** A project whose second segment's take waits for the first segment's take (still running). */- function waitingProject(): string {- // The first take's job keeps running (the server's own runner polls it too).- vi.spyOn(PROVIDERS.mock, "poll").mockResolvedValue({ state: "running" });- const running = storedRow({ status: "running", externalId: "mock-swap" });- const shot = { ...newShot(0, 96, DEFAULT_SETTINGS, true, () => 0.5), id: "shot-a" };- const [a, b] = [newSegment(shot, 0, 48, 0, () => 0.1), newSegment(shot, 48, 96, 1, () => 0.2)];- const take = (id: string, over: object) => ({ id, createdAt: 1, engine: "open", signature: "", dependencies: [], prompt: "", seed: 1, favourite: false, decision: "pending", notes: "", ...over });- const segments = [- { ...a, takes: [take("t1", { state: "launched", genId: running })] },- { ...b, takes: [take("t2", { state: "waiting", waitsOn: [{ segmentId: a.id, takeId: "t1" }], dependencies: [{ segmentId: a.id, takeId: "t1", frames: 8 }] })] },- ];- const clip = {- id: "clip-1",- name: "walk",- source: { url: "/api/files/uploads/x/walk.mp4", name: "walk.mp4", duration: 4, fps: 24, width: 1280, height: 720, hasAudio: true },- normalized: { url: "/api/files/outputs/x/walk24.mp4", genId: "g-norm" },- frames: 96,- cuts: [],- detected: null,- cutsReviewed: true,- shots: [{ ...shot, segments }],- transcript: null,- review: "pending",- reviewNotes: "",- assembly: null,- };- const id = `swap-${++rows}`;- const doc = { id, name: "Off", engine: "open", character: { image: "/api/files/uploads/x/hero.png", description: "a woman" }, defaults: DEFAULT_SETTINGS, clips: [clip], createdAt: 0, updatedAt: 0, revision: 1 };- db()- .prepare("INSERT INTO swap_projects (id, name, engine, data_json, revision, waiting, created_at, updated_at) VALUES (?, 'Off', 'open', ?, 1, 1, ?, ?)")- .run(id, JSON.stringify(doc), Date.now(), Date.now());- return id;- }- const takes = (p: SwapProject) => p.clips[0].shots[0].segments!.flatMap((g) => g.takes.map((t) => ({ id: t.id, state: t.state, reason: t.reason })));- const waitingCount = (id: string) => (db().prepare("SELECT waiting FROM swap_projects WHERE id = ?").get(id) as { waiting: number }).waiting;-- it("keeps a take waiting while its owner is on, whoever looks at the project", () => {- const id = waitingProject();- const viewer = actor(seedPerson(), "member");- const p = runAs(viewer, () => swap.advanceProject(id));- expect(takes(p).find((t) => t.id === "t2")).toMatchObject({ state: "waiting" });- expect(waitingCount(id)).toBe(1);- });-- it("stops the waiting takes of a project whose owner was turned off, saying why, so the sweep lets it go", () => {- const id = waitingProject();- updatePerson("u_owner", { status: "disabled" });- // A teammate's look (the page's poll) launches nothing for the owner.- const p = runAs(actor(seedPerson(), "admin"), () => swap.projectView(id)).project;- expect(takes(p).find((t) => t.id === "t2")).toEqual({ id: "t2", state: "stopped", reason: "Paused: the account that started this is off." });- expect(waitingCount(id)).toBe(0);- });-});diff --git a/tests/setup/actor.ts b/tests/setup/actor.tsdeleted file mode 100644index 5eae0776..00000000--- a/tests/setup/actor.ts+++ /dev/null@@ -1,11 +0,0 @@-import { beforeAll, beforeEach } from "vitest";-import { enterAs, LOCAL_OWNER } from "@/server/access/actor";--/**- * Every test acts as the local owner ("Just me on this computer"), so suites that call server modules directly keep- * working now that server code asks who is acting (docs/research/accounts-8.md §13). A test that needs nobody calls- * asNobody() (tests/helpers/actors.ts); one that needs someone else wraps its work in runAs().- */-enterAs(LOCAL_OWNER);-beforeAll(() => enterAs(LOCAL_OWNER));-beforeEach(() => enterAs(LOCAL_OWNER));diff --git a/tests/share-links.test.ts b/tests/share-links.test.tsindex 583151ba..9510c3ce 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(new Request("http://localhost/"))).json()) as { items: ShareListItem[]; signIn: boolean };+ const list = (await (await listRoute.GET()).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 a20f3343..8d2e7e91 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(new Request("http://localhost/"))).json();+ const list = await (await projects.GET()).json();expect(list.items[0]).toMatchObject({ id, clips: 0 });const p = await post(clips, id, { url: clip, name: "dance.mp4" });diff --git a/vitest.config.ts b/vitest.config.tsindex 09f56d83..cc92f57f 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -8,5 +8,5 @@ export default defineConfig({"server-only": path.resolve(__dirname, "tests/stubs/server-only.ts"),},},- test: { include: ["tests/**/*.test.ts"], environment: "node", setupFiles: ["tests/setup/actor.ts"] },+ test: { include: ["tests/**/*.test.ts"], environment: "node" },});