Open source CapCut alternative.
TypeScript
feat(site): machine auth for the cut surface
David Le0640ff300a60
diff --git a/site/src/app/api/api-keys/[id]/route.ts b/site/src/app/api/api-keys/[id]/route.tsnew file mode 100644index 00000000..420a5026--- /dev/null+++ b/site/src/app/api/api-keys/[id]/route.ts@@ -0,0 +1,24 @@+import { NextResponse } from "next/server";+import {+ donkeySessionUserId,+ notFoundResponse,+ unauthorizedResponse,+ withDonkeyAuth,+} from "@/lib/donkey-api-auth";+import { prisma } from "@/lib/prisma";++export const runtime = "nodejs";++/** Revoke a key. The row stays for the audit trail; `enabled: false` stops+ * matching live traffic immediately. */+export const DELETE = withDonkeyAuth(async (request, ctx: { params: Promise<{ id: string }> }) => {+ const userId = donkeySessionUserId(request);+ if (!userId) return unauthorizedResponse();+ const { id } = await ctx.params;+ const updated = await prisma.apikey.updateMany({+ where: { id, referenceId: userId, enabled: true },+ data: { enabled: false, updatedAt: new Date() },+ });+ if (updated.count === 0) return notFoundResponse();+ return NextResponse.json({ ok: true });+});diff --git a/site/src/app/api/api-keys/route.ts b/site/src/app/api/api-keys/route.tsnew file mode 100644index 00000000..e8571ff5--- /dev/null+++ b/site/src/app/api/api-keys/route.ts@@ -0,0 +1,64 @@+import { randomBytes, randomUUID } from "node:crypto";+import { NextResponse } from "next/server";+import {+ API_KEY_PREFIX,+ donkeySessionUserId,+ hashApiKey,+ unauthorizedResponse,+ withDonkeyAuth,+} from "@/lib/donkey-api-auth";+import { prisma } from "@/lib/prisma";++// API keys for the Cut surface, stored in the Better-Auth-shaped Apikey+// table. Managed with the signed-in session only — a key cannot mint or list+// keys. The full secret is returned once, at creation; the row holds its+// hash (`key`) and a display head (`start`).++export const runtime = "nodejs";++const MAX_KEYS = 20;++export const GET = withDonkeyAuth(async (request) => {+ const userId = donkeySessionUserId(request);+ if (!userId) return unauthorizedResponse();+ const rows = await prisma.apikey.findMany({+ where: { referenceId: userId },+ orderBy: { createdAt: "desc" },+ select: {+ id: true,+ name: true,+ start: true,+ enabled: true,+ createdAt: true,+ lastRequest: true,+ },+ });+ return NextResponse.json(rows);+});++export const POST = withDonkeyAuth(async (request) => {+ const userId = donkeySessionUserId(request);+ if (!userId) return unauthorizedResponse();+ const body = (await request.json().catch(() => ({}))) as { name?: string };+ const name = (body.name ?? "").trim() || "API key";+ const live = await prisma.apikey.count({ where: { referenceId: userId, enabled: true } });+ if (live >= MAX_KEYS)+ return NextResponse.json({ error: "Key limit reached. Revoke one first." }, { status: 400 });+ const secret = `${API_KEY_PREFIX}${randomBytes(24).toString("base64url")}`;+ const now = new Date();+ const row = await prisma.apikey.create({+ data: {+ id: randomUUID(),+ name,+ referenceId: userId,+ prefix: API_KEY_PREFIX,+ start: secret.slice(0, API_KEY_PREFIX.length + 6),+ key: hashApiKey(secret),+ enabled: true,+ createdAt: now,+ updatedAt: now,+ },+ select: { id: true, name: true, start: true, createdAt: true },+ });+ return NextResponse.json({ ...row, key: secret });+});diff --git a/site/src/app/api/cut-cloud/[[...slug]]/route.ts b/site/src/app/api/cut-cloud/[[...slug]]/route.tsindex 1ab2315d..de239219 100644--- a/site/src/app/api/cut-cloud/[[...slug]]/route.ts+++ b/site/src/app/api/cut-cloud/[[...slug]]/route.ts@@ -9,7 +9,13 @@ import { cutCloudCatchAll } from "@/cut/server/cloud/routes";// engine's /api/cut/* paths to this prefix.export const runtime = "nodejs";-const handle = withDonkeyAuth((request) => cutCloudCatchAll(request));+// The Cut API surface takes machine callers: a `dk_live_` bearer key acts as+// its user across the same routes the page uses, and the Cut runner calls+// back here with its grant while executing a queued turn.+const handle = withDonkeyAuth((request) => cutCloudCatchAll(request), {+ allowApiKey: true,+ allowRunner: true,+});// The daily GC cron has no session; Vercel authenticates its invocations with// the CRON_SECRET bearer token. Everything else goes through auth (a superuserdiff --git a/site/src/app/api/inference/assets/refresh/route.ts b/site/src/app/api/inference/assets/refresh/route.tsindex d3a4888e..4f19cba3 100644--- a/site/src/app/api/inference/assets/refresh/route.ts+++ b/site/src/app/api/inference/assets/refresh/route.ts@@ -84,4 +84,4 @@ export const POST = withDonkeyAuth(async (request) => {throw error;}-});+}, { allowRunner: true });diff --git a/site/src/app/api/inference/assets/route.ts b/site/src/app/api/inference/assets/route.tsindex c2726c62..1e9c65ea 100644--- a/site/src/app/api/inference/assets/route.ts+++ b/site/src/app/api/inference/assets/route.ts@@ -190,4 +190,4 @@ export const POST = withDonkeyAuth(async (request) => {throw error;}-});+}, { allowRunner: true });diff --git a/site/src/app/api/inference/responses/route.ts b/site/src/app/api/inference/responses/route.tsindex c79629c3..f7bddadd 100644--- a/site/src/app/api/inference/responses/route.ts+++ b/site/src/app/api/inference/responses/route.ts@@ -239,4 +239,4 @@ export const POST = withDonkeyAuth(async (request) => {throw error;}-});+}, { allowRunner: true });diff --git a/site/src/app/api/inference/uploads/route.ts b/site/src/app/api/inference/uploads/route.tsindex c33d1fd7..b8e852a5 100644--- a/site/src/app/api/inference/uploads/route.ts+++ b/site/src/app/api/inference/uploads/route.ts@@ -82,4 +82,4 @@ export const POST = withDonkeyAuth(async (request) => {}throw error;}-});+}, { allowRunner: true });diff --git a/site/src/lib/donkey-api-auth.ts b/site/src/lib/donkey-api-auth.tsindex e1a8a66d..53b3d479 100644--- a/site/src/lib/donkey-api-auth.ts+++ b/site/src/lib/donkey-api-auth.ts@@ -1,3 +1,4 @@+import { createHash, timingSafeEqual } from "node:crypto";import { type NextRequest, NextResponse } from "next/server";import { auth } from "@/lib/auth";@@ -6,7 +7,7 @@ import { prisma } from "@/lib/prisma";export type DonkeyAuthContext = {platform: "api";app: "donkey";- method: "session-cookie" | "dev-bypass";+ method: "session-cookie" | "dev-bypass" | "runner" | "api-key";clientId: string | null;// The app's active conversation for this request, from x-donkey-conversation-id.// Null for background work.@@ -22,6 +23,13 @@ export type DonkeyAuthOptions = {// When set, the authenticated user must hold this role or the request is// rejected with 403 before the handler runs.role?: DonkeyRole;+ // Accept a `dk_live_` bearer key as the user. Off by default: only routes+ // that opt in (the Cut API surface) take machine callers.+ allowApiKey?: boolean;+ // Accept the Cut runner's shared-secret grant. Off by default: only the+ // routes the worker actually calls back (the Cut API surface and hosted+ // inference) opt in, so a leaked secret stays contained to them.+ allowRunner?: boolean;};export type DonkeyAuthenticatedRequest = NextRequest & {@@ -80,11 +88,24 @@ function conversationIdFromHeaders(headers: Headers): string | null {export async function getDonkeyAuthContext(headers: Headers,+ options: { allowApiKey?: boolean; allowRunner?: boolean } = {},): Promise<DonkeyAuthContext | null> {const devBypass = devAuthBypassContext(headers);if (devBypass) {return devBypass;}+ if (options.allowRunner) {+ const runner = runnerAuthContext(headers);+ if (runner) {+ return runner;+ }+ }+ if (options.allowApiKey) {+ const apiKey = await apiKeyAuthContext(headers);+ if (apiKey) {+ return apiKey;+ }+ }const session = await auth.api.getSession({headers,@@ -111,6 +132,71 @@ export function shouldBypassDonkeyInferenceCredits(return authContext.method === "dev-bypass";}+export const API_KEY_PREFIX = "dk_live_";++/** The stored form of an API key: SHA-256 hex of the whole secret. */+export function hashApiKey(secret: string): string {+ return createHash("sha256").update(secret).digest("hex");+}++/** A machine caller holding a per-user key: `Authorization: Bearer dk_live_…`.+ * Rows live in the Better-Auth-shaped Apikey table (`key` holds the SHA-256+ * of the whole secret, `referenceId` the owner), so the plugin can take the+ * table over unchanged when it ships. The lookup is by hash; the table never+ * holds a usable secret. */+async function apiKeyAuthContext(headers: Headers): Promise<DonkeyAuthContext | null> {+ const header = headers.get("authorization");+ const secret = header?.startsWith("Bearer ") ? header.slice(7).trim() : null;+ if (!secret || !secret.startsWith(API_KEY_PREFIX)) return null;+ const row = await prisma.apikey.findFirst({+ where: { key: hashApiKey(secret) },+ select: { id: true, referenceId: true, enabled: true, expiresAt: true },+ });+ if (!row || row.enabled === false) return null;+ if (row.expiresAt && row.expiresAt.getTime() < Date.now()) return null;+ void prisma.apikey+ .update({+ where: { id: row.id },+ data: { lastRequest: new Date(), requestCount: { increment: 1 } },+ })+ .catch(() => {});+ const clientId = headers.get(clientIdHeader)?.trim();+ return {+ platform: "api",+ app: "donkey",+ method: "api-key",+ clientId: clientId ? clientId : null,+ conversationId: conversationIdFromHeaders(headers),+ userId: row.referenceId,+ };+}++const runnerSecretHeader = "x-donkey-runner-secret";+const runnerUserHeader = "x-donkey-runner-user";++/** The Cut runner acting for one user: the worker container executes a job+ * the hosted API queued for that user, and calls back with the shared secret+ * plus the job's user id. The secret is the whole grant, so it compares in+ * constant time and both headers are required. */+function runnerAuthContext(headers: Headers): DonkeyAuthContext | null {+ const secret = process.env.CUT_RUNNER_SECRET;+ const got = headers.get(runnerSecretHeader);+ const userId = headers.get(runnerUserHeader)?.trim();+ if (!secret || !got || !userId) return null;+ const a = Buffer.from(got);+ const b = Buffer.from(secret);+ if (a.length !== b.length || !timingSafeEqual(a, b)) return null;+ const clientId = headers.get(clientIdHeader)?.trim();+ return {+ platform: "api",+ app: "donkey",+ method: "runner",+ clientId: clientId ? clientId : null,+ conversationId: conversationIdFromHeaders(headers),+ userId,+ };+}+function devAuthBypassContext(headers: Headers): DonkeyAuthContext | null {if (process.env.NODE_ENV === "production") {return null;@@ -136,7 +222,10 @@ export function withDonkeyAuth<TArgs extends unknown[] = [],>(handler: DonkeyAuthHandler<TReq, TArgs>, options: DonkeyAuthOptions = {}) {return async (request: NextRequest, ...args: TArgs) => {- const authContext = await getDonkeyAuthContext(request.headers);+ const authContext = await getDonkeyAuthContext(request.headers, {+ allowApiKey: options.allowApiKey,+ allowRunner: options.allowRunner,+ });if (!authContext) {return NextResponse.json(