Skip to content

Open source CapCut alternative.

TypeScript

refactor(site): declare route roles on the auth wrapper

David Leab98225500df
diff --git a/docs/guides/backend-apis.md b/docs/guides/backend-apis.md
index 82c66c1b..34cbd6f7 100644
--- a/docs/guides/backend-apis.md
+++ b/docs/guides/backend-apis.md
@@ -22,6 +22,11 @@ Inside the handler, `request.donkey` carries who the caller is. Its `method`
field says how they authenticated — by session cookie, API key, or dev bypass —
and the handler branches on that, never on the path.
+A route that requires more than being signed in declares the role in the same
+wrapper: `withSuperUser(handler)` rejects everyone else with a plain 403 before
+the handler runs. Roles are a typed set on the auth options, so a handler never
+hand-rolls its own role check.
+
Better Auth is the login layer, mounted at `/api/auth/[...all]` and configured
in one place. The only interactive login is Google OAuth; email-and-password
stays off unless the product deliberately adds another method. Better Auth's own
diff --git a/site/src/app/api/credits/grants/route.ts b/site/src/app/api/credits/grants/route.ts
index 23917824..ab4a1bf1 100644
--- a/site/src/app/api/credits/grants/route.ts
+++ b/site/src/app/api/credits/grants/route.ts
@@ -4,11 +4,7 @@ import { z } from "zod";
import { creditMicrosToString, creditStringToMicros } from "@/lib/credits/amounts";
import { getCreditBalance, grantCredits } from "@/lib/credits/inference";
import { maxCreditGrantDollars } from "@/lib/credits/top-up";
-import {
- isDonkeySuperUser,
- notFoundResponse,
- withDonkeyAuth,
-} from "@/lib/donkey-api-auth";
+import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";
import { prisma } from "@/lib/prisma";
export const dynamic = "force-dynamic";
@@ -29,17 +25,7 @@ const creditGrantRequestSchema = z
message: "Provide a userId or an email.",
});
-export const POST = withDonkeyAuth(async (request) => {
- if (!(await isDonkeySuperUser(request.donkey.userId))) {
- return NextResponse.json(
- {
- error: "Forbidden",
- message: "Only super users can grant credits.",
- },
- { status: 403 },
- );
- }
-
+export const POST = withSuperUser(async (request) => {
const parsed = creditGrantRequestSchema.safeParse(await request.json());
if (!parsed.success) {
return NextResponse.json(
diff --git a/site/src/app/api/jobs/[jobId]/route.ts b/site/src/app/api/jobs/[jobId]/route.ts
index 29439722..ca4d4489 100644
--- a/site/src/app/api/jobs/[jobId]/route.ts
+++ b/site/src/app/api/jobs/[jobId]/route.ts
@@ -1,10 +1,4 @@
-import { NextResponse } from "next/server";
-
-import {
- isDonkeySuperUser,
- notFoundResponse,
- withDonkeyAuth,
-} from "@/lib/donkey-api-auth";
+import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";
import { jobStatusResponse } from "@/lib/jobs/queue";
import { prisma } from "@/lib/prisma";
@@ -13,17 +7,7 @@ export const dynamic = "force-dynamic";
type RouteContext = { params: Promise<{ jobId: string }> };
// Poll one background job for its outcome.
-export const GET = withDonkeyAuth(async (request, context: RouteContext) => {
- if (!(await isDonkeySuperUser(request.donkey.userId))) {
- return NextResponse.json(
- {
- error: "Forbidden",
- message: "Only super users can run jobs.",
- },
- { status: 403 },
- );
- }
-
+export const GET = withSuperUser(async (request, context: RouteContext) => {
const { jobId } = await context.params;
const job = await prisma.asyncJob.findUnique({ where: { id: jobId } });
if (!job) return notFoundResponse();
diff --git a/site/src/app/api/jobs/route.ts b/site/src/app/api/jobs/route.ts
index 840519fd..c4ae3eb8 100644
--- a/site/src/app/api/jobs/route.ts
+++ b/site/src/app/api/jobs/route.ts
@@ -2,7 +2,7 @@ import { NextResponse } from "next/server";
import { z } from "zod";
import type { Prisma } from "@/generated/prisma/client";
-import { isDonkeySuperUser, withDonkeyAuth } from "@/lib/donkey-api-auth";
+import { withSuperUser } from "@/lib/donkey-api-auth";
import { enqueueJob, healJob } from "@/lib/jobs/queue";
import { jobKinds } from "@/lib/jobs/registry";
import { prisma } from "@/lib/prisma";
@@ -15,17 +15,7 @@ export const maxDuration = 300;
// The most recent jobs, newest first, each self-healed on the way out so a
// lost message republishes and a crashed execution reads as an error rather
// than running forever.
-export const GET = withDonkeyAuth(async (request) => {
- if (!(await isDonkeySuperUser(request.donkey.userId))) {
- return NextResponse.json(
- {
- error: "Forbidden",
- message: "Only super users can run jobs.",
- },
- { status: 403 },
- );
- }
-
+export const GET = withSuperUser(async () => {
const rows = await prisma.asyncJob.findMany({
orderBy: { createdAt: "desc" },
take: 10,
@@ -54,17 +44,7 @@ const jobRequestSchema = z
// Start a background job. The kind names an executor in the registry, and the
// payload must match that kind's schema. The caller polls /api/jobs/[jobId]
// for the outcome.
-export const POST = withDonkeyAuth(async (request) => {
- if (!(await isDonkeySuperUser(request.donkey.userId))) {
- return NextResponse.json(
- {
- error: "Forbidden",
- message: "Only super users can run jobs.",
- },
- { status: 403 },
- );
- }
-
+export const POST = withSuperUser(async (request) => {
const parsed = jobRequestSchema.safeParse(await request.json());
if (!parsed.success) {
return NextResponse.json(
diff --git a/site/src/lib/donkey-api-auth.ts b/site/src/lib/donkey-api-auth.ts
index 6a17f216..3f0d18fd 100644
--- a/site/src/lib/donkey-api-auth.ts
+++ b/site/src/lib/donkey-api-auth.ts
@@ -15,11 +15,18 @@ export type DonkeyAuthContext = {
apiKeyId: string | null;
};
+// The known roles a route can require beyond being signed in. Add new roles
+// here so every requirement stays part of this one typed set.
+export type DonkeyRole = "SUPER_USER";
+
export type DonkeyAuthOptions = {
// Routes are session-only by default. Set true to also accept a Vision API
// key as a bearer token. This is the typed allowlist for "which routes
// support API keys" — no path string matching.
allowApiKey?: boolean;
+ // When set, the authenticated user must hold this role or the request is
+ // rejected with 403 before the handler runs.
+ role?: DonkeyRole;
};
export type DonkeyAuthenticatedRequest = NextRequest & {
@@ -49,6 +56,11 @@ export function notFoundResponse() {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
+// Generic 403 for a signed-in caller without the role a route requires.
+export function forbiddenResponse() {
+ return NextResponse.json({ error: "Forbidden" }, { status: 403 });
+}
+
export type DonkeyAuthHandler<
TReq extends DonkeyAuthenticatedRequest = DonkeyAuthenticatedRequest,
TArgs extends unknown[] = [],
@@ -195,6 +207,13 @@ export function withDonkeyAuth<
);
}
+ if (
+ options.role === "SUPER_USER" &&
+ !(await isDonkeySuperUser(authContext.userId))
+ ) {
+ return forbiddenResponse();
+ }
+
const authenticatedRequest = Object.assign(request, {
donkey: authContext,
}) as TReq;
@@ -203,6 +222,18 @@ export function withDonkeyAuth<
};
}
+// Superuser-only route: withDonkeyAuth with the SUPER_USER role required.
+// export const POST = withSuperUser(async (request) => { ... });
+export function withSuperUser<
+ TReq extends DonkeyAuthenticatedRequest = DonkeyAuthenticatedRequest,
+ TArgs extends unknown[] = [],
+>(
+ handler: DonkeyAuthHandler<TReq, TArgs>,
+ options: Omit<DonkeyAuthOptions, "role"> = {},
+) {
+ return withDonkeyAuth(handler, { ...options, role: "SUPER_USER" });
+}
+
export async function isDonkeySuperUser(userId: string) {
const user = await prisma.user.findUnique({
select: {