Skip to content

Open source CapCut alternative.

TypeScript

Add Donkey API auth middleware

David Le98bd8f628957
diff --git a/docs/guides/frontend-nextjs-guidelines.md b/docs/guides/frontend-nextjs-guidelines.md
index 8bfab78f..4e57a0f1 100644
--- a/docs/guides/frontend-nextjs-guidelines.md
+++ b/docs/guides/frontend-nextjs-guidelines.md
@@ -35,6 +35,7 @@ This app is the `site` Next.js project. It is intended to run the public site an
## Data and API Access
- Route Handlers live in `src/app/api/**/route.ts`.
+- Protect Donkey APIs with `withDonkeyAuth` from `src/lib/donkey-api-auth.ts` unless an endpoint is intentionally public, such as health checks.
- Validate request bodies, search params, and dynamic route params with Zod before using them.
- Keep API responses explicit with `NextResponse.json(...)`.
- Do not call `fetch(...)` directly from React components. Put browser-facing API calls in a focused API client module, then import that client into components.
diff --git a/site/.env.example b/site/.env.example
index 65e47e0c..7361bd70 100644
--- a/site/.env.example
+++ b/site/.env.example
@@ -1,2 +1,3 @@
DATABASE_URL="postgresql://postgres:[PASSWORD]@[PROJECT-REF].pooler.supabase.com:6543/postgres?pgbouncer=true&connection_limit=1"
DIRECT_URL="postgresql://postgres:[PASSWORD]@db.[PROJECT-REF].supabase.co:5432/postgres"
+DONKEY_API_TOKEN="replace-with-a-long-random-token"
diff --git a/site/src/lib/donkey-api-auth.ts b/site/src/lib/donkey-api-auth.ts
new file mode 100644
index 00000000..bb6984b5
--- /dev/null
+++ b/site/src/lib/donkey-api-auth.ts
@@ -0,0 +1,89 @@
+import { type NextRequest, NextResponse } from "next/server";
+
+export type DonkeyAuthContext = {
+ platform: "api";
+ app: "donkey";
+ clientId: string | null;
+};
+
+export type DonkeyAuthenticatedRequest = NextRequest & {
+ donkey: DonkeyAuthContext;
+};
+
+export type DonkeyAuthHandler<
+ TReq extends DonkeyAuthenticatedRequest = DonkeyAuthenticatedRequest,
+ TArgs extends unknown[] = [],
+> = (request: TReq, ...args: TArgs) => Promise<NextResponse> | NextResponse;
+
+const apiTokenEnvName = "DONKEY_API_TOKEN";
+const apiKeyHeader = "x-donkey-api-key";
+const clientIdHeader = "x-donkey-client-id";
+
+function getConfiguredApiToken() {
+ const token = process.env[apiTokenEnvName]?.trim();
+
+ return token ? token : null;
+}
+
+function getRequestApiToken(headers: Headers) {
+ const authorizationHeader = headers.get("authorization")?.trim();
+
+ if (authorizationHeader) {
+ const bearerMatch = authorizationHeader.match(/^Bearer\s+(.+)$/i);
+
+ if (bearerMatch?.[1]) {
+ return bearerMatch[1].trim();
+ }
+ }
+
+ const apiKey = headers.get(apiKeyHeader)?.trim();
+
+ return apiKey ? apiKey : null;
+}
+
+export function getDonkeyAuthContext(headers: Headers): DonkeyAuthContext | null {
+ const configuredToken = getConfiguredApiToken();
+ const requestToken = getRequestApiToken(headers);
+
+ if (!configuredToken || requestToken !== configuredToken) {
+ return null;
+ }
+
+ const clientId = headers.get(clientIdHeader)?.trim();
+
+ return {
+ platform: "api",
+ app: "donkey",
+ clientId: clientId ? clientId : null,
+ };
+}
+
+export function withDonkeyAuth<
+ TReq extends DonkeyAuthenticatedRequest = DonkeyAuthenticatedRequest,
+ TArgs extends unknown[] = [],
+>(handler: DonkeyAuthHandler<TReq, TArgs>) {
+ return (request: NextRequest, ...args: TArgs) => {
+ const authContext = getDonkeyAuthContext(request.headers);
+
+ if (!authContext) {
+ return NextResponse.json(
+ {
+ error: "Unauthorized",
+ message: "Authentication required",
+ },
+ {
+ status: 401,
+ headers: {
+ "WWW-Authenticate": "Bearer",
+ },
+ },
+ );
+ }
+
+ const authenticatedRequest = Object.assign(request, {
+ donkey: authContext,
+ }) as TReq;
+
+ return handler(authenticatedRequest, ...args);
+ };
+}