Open source CapCut alternative.
TypeScript
feat(site): switch Cut's server APIs off on hosted deploys
David Le131d0e76412b
diff --git a/site/src/app/api/ai/chat/route.ts b/site/src/app/api/ai/chat/route.tsindex 1f32f9ee..7eb555bd 100644--- a/site/src/app/api/ai/chat/route.ts+++ b/site/src/app/api/ai/chat/route.ts@@ -8,6 +8,7 @@ export const runtime = "nodejs";import { callBrowserTool, registerSession, unregisterSession, type UIChunkWriter } from "@/cut/server/ai/bridge";import { systemPrompt } from "@/cut/server/ai/catalog";+import { hostedApiBlock } from "@/cut/server/local-only";interface ChatBody {messages: UIMessage[];@@ -46,6 +47,8 @@ function lastUserAttachments(messages: UIMessage[]): unknown[] {}export async function POST(req: Request) {+ const blocked = hostedApiBlock();+ if (blocked) return blocked;const body = (await req.json()) as ChatBody;const base = new URL(req.url).origin;const sessionKey = crypto.randomUUID();diff --git a/site/src/app/api/ai/models/route.ts b/site/src/app/api/ai/models/route.tsindex f0c83b76..8a585550 100644--- a/site/src/app/api/ai/models/route.ts+++ b/site/src/app/api/ai/models/route.ts@@ -4,6 +4,7 @@ import { NextResponse } from "next/server";export const runtime = "nodejs";import { AI_MODELS } from "@/cut/server/ai/models";+import { hostedApiBlock } from "@/cut/server/local-only";function probe(cmd: string, args: string[]): Promise<{ ok: boolean; note: string }> {return new Promise((resolve) => {@@ -27,6 +28,8 @@ const g = globalThis as unknown as {};export async function GET() {+ const blocked = hostedApiBlock();+ if (blocked) return blocked;const cached = g.__veditorAiProbe;let value = cached && Date.now() - cached.at < 60_000 ? cached.value : null;if (!value) {diff --git a/site/src/app/api/ai/proxy/route.ts b/site/src/app/api/ai/proxy/route.tsindex 91bdf0cb..6b65df51 100644--- a/site/src/app/api/ai/proxy/route.ts+++ b/site/src/app/api/ai/proxy/route.ts@@ -4,9 +4,12 @@ export const runtime = "nodejs";import { callBrowserTool } from "@/cut/server/ai/bridge";import { AI_SKILL_INDEX, AI_SKILLS, AI_TOOLS } from "@/cut/server/ai/catalog";+import { hostedApiBlock } from "@/cut/server/local-only";/** MCP-shaped tool catalog for the stdio proxy. */export async function GET(req: Request) {+ const blocked = hostedApiBlock();+ if (blocked) return blocked;const type = new URL(req.url).searchParams.get("type");if (type !== "catalog") return NextResponse.json({ error: "Bad request." }, { status: 400 });return NextResponse.json({@@ -24,6 +27,8 @@ const text = (value: unknown) => ({/** Execute one tool call: server-side skills directly, editor tools via the browser. */export async function POST(req: Request) {+ const blocked = hostedApiBlock();+ if (blocked) return blocked;const { sessionKey, name, args } = (await req.json()) as {sessionKey?: string;name?: string;diff --git a/site/src/app/api/ai/tool-result/route.ts b/site/src/app/api/ai/tool-result/route.tsindex 6a33bb05..522d6404 100644--- a/site/src/app/api/ai/tool-result/route.ts+++ b/site/src/app/api/ai/tool-result/route.ts@@ -3,9 +3,12 @@ import { NextResponse } from "next/server";export const runtime = "nodejs";import { resolveBrowserTool } from "@/cut/server/ai/bridge";+import { hostedApiBlock } from "@/cut/server/local-only";/** The browser posts tool outputs here after executing them on the store. */export async function POST(req: Request) {+ const blocked = hostedApiBlock();+ if (blocked) return blocked;const { sessionKey, toolCallId, output, errorText } = (await req.json()) as {sessionKey?: string;toolCallId?: string;diff --git a/site/src/cut/server/jobs.ts b/site/src/cut/server/jobs.tsindex 8894c4a0..13f41772 100644--- a/site/src/cut/server/jobs.ts+++ b/site/src/cut/server/jobs.ts@@ -2,6 +2,7 @@ import { spawn, type ChildProcess } from "node:child_process";import { mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises";import os from "node:os";import path from "node:path";+import { assertLocalRuntime } from "./local-only";import { exportsDir, mediaPath, readProject } from "./projects";import { hasStream, num } from "./util";@@ -71,6 +72,7 @@ function stamp() {}export async function createJob(form: FormData): Promise<Job> {+ assertLocalRuntime();const spec = JSON.parse(String(form.get("spec"))) as ExportSpec;const tmpDir = await mkdtemp(path.join(os.tmpdir(), "veditor-"));const id = crypto.randomUUID().slice(0, 12);diff --git a/site/src/cut/server/library.ts b/site/src/cut/server/library.tsindex 9956ef21..56569b8b 100644--- a/site/src/cut/server/library.ts+++ b/site/src/cut/server/library.ts@@ -1,6 +1,7 @@import { spawn } from "node:child_process";import { copyFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";import path from "node:path";+import { assertLocalRuntime } from "./local-only";import { mediaPath as projectMediaPath, readProject } from "./projects";import { exists, uniqueName } from "./util";@@ -25,12 +26,14 @@ interface LibraryIndex {}export function libMediaPath(fileName: string) {+ assertLocalRuntime();const safe = path.basename(fileName);if (!safe || safe.startsWith(".")) throw new Error("Invalid file name.");return path.join(LIB_MEDIA, safe);}async function readIndex(): Promise<LibraryIndex> {+ assertLocalRuntime();try {return JSON.parse(await readFile(INDEX, "utf8")) as LibraryIndex;} catch {@@ -39,6 +42,7 @@ async function readIndex(): Promise<LibraryIndex> {}async function writeIndex(idx: LibraryIndex) {+ assertLocalRuntime();await mkdir(LIB_MEDIA, { recursive: true });await writeFile(INDEX, JSON.stringify(idx, null, 2));}diff --git a/site/src/cut/server/local-only.ts b/site/src/cut/server/local-only.tsnew file mode 100644index 00000000..a9202ec6--- /dev/null+++ b/site/src/cut/server/local-only.ts@@ -0,0 +1,31 @@+// Cut is a local-only product. Its server APIs run on the user's own Mac —+// against their local ffmpeg/swiftc, their own claude/codex CLI logins, and+// local disk. They must never execute on hosted infrastructure, both because+// the tools and files aren't there and because those routes are unauthenticated+// by design (fine on localhost, an exposure on a public host).+//+// On a hosted deploy, cut.donkeyuse.com still serves Cut's client bundle, but+// every server API is switched off — so nothing reads local disk, spawns a+// process, or reaches any model, including our production models. Cut's AI only+// ever uses the user's local claude/codex logins; it has no path to hosted+// inference, and this guard keeps it that way.+//+// `VERCEL` is set on every Vercel build and runtime and is absent when running+// locally, so this guard is inert during local dev and a local `npm run start`,+// and only trips on a real deploy.++export function isHostedRuntime(): boolean {+ return Boolean(process.env.VERCEL);+}++/** Guard shared server code that touches local disk or spawns a process. */+export function assertLocalRuntime(): void {+ if (isHostedRuntime()) {+ throw new Error("Cut is local-only; its server APIs do not run on hosted infrastructure.");+ }+}++/** 404 a Cut API route when hosted; return null to proceed locally. */+export function hostedApiBlock(): Response | null {+ return isHostedRuntime() ? new Response(null, { status: 404 }) : null;+}diff --git a/site/src/cut/server/projects.ts b/site/src/cut/server/projects.tsindex 33f9dd09..18c12a6c 100644--- a/site/src/cut/server/projects.ts+++ b/site/src/cut/server/projects.ts@@ -1,6 +1,7 @@import { mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";import path from "node:path";import type { ProjectDoc, ProjectSummary } from "@/cut/lib/types";+import { assertLocalRuntime } from "./local-only";import { exists, uniqueName } from "./util";/** All projects live here; each project is one folder holding project.json,@@ -10,6 +11,7 @@ export const PROJECTS_ROOT = path.join(process.cwd(), "projects");const ID_RE = /^[a-z0-9][a-z0-9-]{2,40}$/;export function projectDir(id: string) {+ assertLocalRuntime();if (!ID_RE.test(id)) throw new Error("Invalid project id.");return path.join(PROJECTS_ROOT, id);}@@ -109,6 +111,7 @@ function summarize(id: string, doc: ProjectDoc): ProjectSummary {}export async function listProjects(): Promise<ProjectSummary[]> {+ assertLocalRuntime();await mkdir(PROJECTS_ROOT, { recursive: true });const entries = await readdir(PROJECTS_ROOT, { withFileTypes: true });const names = entriesdiff --git a/site/src/cut/server/transcribe.ts b/site/src/cut/server/transcribe.tsindex e860ad20..9e76e97a 100644--- a/site/src/cut/server/transcribe.ts+++ b/site/src/cut/server/transcribe.ts@@ -2,6 +2,7 @@ import { spawn } from "node:child_process";import { mkdir, mkdtemp, rm, stat } from "node:fs/promises";import os from "node:os";import path from "node:path";+import { assertLocalRuntime } from "./local-only";import { mediaPath, readProject } from "./projects";import { hasStream, num, round } from "./util";@@ -121,6 +122,7 @@ export function groupWords(words: Word[]): Cue[] {}export async function createTranscribeJob(spec: TranscribeSpec): Promise<TranscribeJob> {+ assertLocalRuntime();const job: TranscribeJob = {id: crypto.randomUUID().slice(0, 12),projectId: spec.projectId,diff --git a/site/src/proxy.ts b/site/src/proxy.tsindex 18cb9065..c4f95e52 100644--- a/site/src/proxy.ts+++ b/site/src/proxy.ts@@ -1,11 +1,10 @@import { NextResponse, type NextRequest } from "next/server";-// Cut (the video editor) is served on the cut.donkeyuse.com subdomain, but its-// routes live under /cut in this single site app. For requests on the Cut host we-// rewrite page paths to /cut/* so Cut's root-relative links (/, /library,-// /p/[id]) resolve to its routes, while the apex host keeps serving Donkey.-// /api/* and Next internals are left untouched — Cut's API handlers are mounted-// under the shared /api tree and don't collide with Donkey's.+// Cut (the video editor, publicly "Donkey Cut") is served on the+// cut.donkeyuse.com subdomain, but its routes live under /cut in this single+// site app. For requests on the Cut host we rewrite page paths to /cut/* so+// Cut's root-relative links (/, /library, /p/[id]) resolve to its routes, while+// the apex host keeps serving Donkey.//// This file must live in src/ (next to app/) and use the Next 16 `proxy` name;// a root-level middleware.ts is not loaded when the app is under src/.@@ -14,11 +13,55 @@ import { NextResponse, type NextRequest } from "next/server";// 127.0.0.1, so http://cut.localhost:3000/ exercises this path.const CUT_HOSTS = new Set(["cut.donkeyuse.com", "cut.localhost"]);+// Cut's server APIs are local-only (see src/cut/server/local-only.ts): the+// hosted deploy serves only Cut's client bundle, and that page drives the+// engine running on the user's own Mac. Two rules follow:+// - hosted: these API paths 404 before any handler runs, so no Cut server+// code (disk, ffmpeg, the user's AI CLIs) can execute off-Mac and the+// unauthenticated routes are unreachable.+// - local: the page served from the hosted origin calls this engine+// cross-origin, so grant exactly that origin CORS.+const CUT_API_PREFIXES = ["/api/ai", "/api/export", "/api/library", "/api/projects"];+const CUT_CLIENT_ORIGINS = new Set(["https://cut.donkeyuse.com"]);+const HOSTED = Boolean(process.env.VERCEL);++const isCutApi = (pathname: string) =>+ CUT_API_PREFIXES.some((p) => pathname === p || pathname.startsWith(`${p}/`));++function cutApi(req: NextRequest): NextResponse {+ if (HOSTED) return new NextResponse(null, { status: 404 });++ const origin = req.headers.get("origin") ?? "";+ if (!CUT_CLIENT_ORIGINS.has(origin)) return NextResponse.next();++ if (req.method === "OPTIONS") {+ return new NextResponse(null, {+ status: 204,+ headers: {+ "Access-Control-Allow-Origin": origin,+ "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",+ "Access-Control-Allow-Headers":+ req.headers.get("access-control-request-headers") ?? "Content-Type",+ // Chrome preflights public-site → local-network requests.+ "Access-Control-Allow-Private-Network": "true",+ "Access-Control-Max-Age": "86400",+ Vary: "Origin",+ },+ });+ }+ const res = NextResponse.next();+ res.headers.set("Access-Control-Allow-Origin", origin);+ res.headers.set("Vary", "Origin");+ return res;+}+export function proxy(req: NextRequest) {+ const { pathname } = req.nextUrl;+ if (isCutApi(pathname)) return cutApi(req);+const host = (req.headers.get("host") ?? "").split(":")[0];if (!CUT_HOSTS.has(host)) return NextResponse.next();- const { pathname } = req.nextUrl;if (pathname.startsWith("/cut") || pathname.startsWith("/api")) {return NextResponse.next();}@@ -28,6 +71,14 @@ export function proxy(req: NextRequest) {}export const config = {- // Run for page routes; skip Next internals and files with an extension.- matcher: ["/((?!_next/|.*\\..*).*)"],+ // Page routes (skip Next internals and files with an extension) plus every+ // Cut API path — including media/export files with extensions — so the+ // hosted 404 and local CORS above cover all of them.+ matcher: [+ "/((?!_next/|.*\\..*).*)",+ "/api/ai/:path*",+ "/api/export/:path*",+ "/api/library/:path*",+ "/api/projects/:path*",+ ],};