Skip to content

Open source CapCut alternative.

TypeScript

Add super-user credit grant API

David Leb05ba238a1e0
diff --git a/docs/guides/backend-apis.md b/docs/guides/backend-apis.md
index a6c22cc4..88a349d8 100644
--- a/docs/guides/backend-apis.md
+++ b/docs/guides/backend-apis.md
@@ -81,6 +81,10 @@ checks, provider/model rates, debits, and audit rows.
charges, and adjustments behind it.
- Provider-invoking inference routes check credits before calling a hosted
model, then charge after provider success. Model listing remains uncharged.
+- Manual whole-dollar credit grants are available at `POST /api/credits/grants/`.
+ The caller must be authenticated and have `user.superUser = true`; the target
+ user is addressed by internal `user.id`. The route treats `$1` as `1` hosted
+ inference credit (`1,000,000` micros), then writes the grant and ledger entry.
- Keep rates and user limits configurable through backend-owned data, not the
Mac app.
- Usage records may store sanitized provider usage metadata and normalized
diff --git a/site/prisma/Auth.prisma b/site/prisma/Auth.prisma
index 4891ff92..38152b94 100644
--- a/site/prisma/Auth.prisma
+++ b/site/prisma/Auth.prisma
@@ -4,6 +4,7 @@ model User {
email String @unique
emailVerified Boolean @default(false)
image String?
+ superUser Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
sessions Session[]
diff --git a/site/prisma/migrations/20260524132000_add_user_super_user/migration.sql b/site/prisma/migrations/20260524132000_add_user_super_user/migration.sql
new file mode 100644
index 00000000..268c7af3
--- /dev/null
+++ b/site/prisma/migrations/20260524132000_add_user_super_user/migration.sql
@@ -0,0 +1,2 @@
+ALTER TABLE "user"
+ADD COLUMN "superUser" BOOLEAN NOT NULL DEFAULT false;
diff --git a/site/src/app/api/credits/grants/route.ts b/site/src/app/api/credits/grants/route.ts
new file mode 100644
index 00000000..7c8b80bb
--- /dev/null
+++ b/site/src/app/api/credits/grants/route.ts
@@ -0,0 +1,98 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+import { creditMicrosToString, creditStringToMicros } from "@/lib/credits/amounts";
+import { getCreditBalance, grantCredits } from "@/lib/credits/inference";
+import { isDonkeySuperUser, withDonkeyAuth } from "@/lib/donkey-api-auth";
+import { prisma } from "@/lib/prisma";
+
+export const dynamic = "force-dynamic";
+
+const creditGrantRequestSchema = z.object({
+ amountDollars: z.coerce.number().int().positive().max(100),
+ description: z.string().trim().min(1).max(500).optional(),
+ sourceId: z.string().trim().min(1).max(160).optional(),
+ userId: z.string().trim().min(1),
+}).strict();
+
+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 },
+ );
+ }
+
+ const parsed = creditGrantRequestSchema.safeParse(await request.json());
+ if (!parsed.success) {
+ return NextResponse.json(
+ {
+ error: "Invalid request",
+ issues: parsed.error.issues.map((issue) => ({
+ path: issue.path.join("."),
+ message: issue.message,
+ })),
+ },
+ { status: 400 },
+ );
+ }
+
+ const targetUser = await prisma.user.findUnique({
+ select: {
+ email: true,
+ id: true,
+ },
+ where: {
+ id: parsed.data.userId,
+ },
+ });
+
+ if (!targetUser) {
+ return NextResponse.json(
+ {
+ error: "Not found",
+ message: "No user exists with that id.",
+ },
+ { status: 404 },
+ );
+ }
+
+ const amountMicros = creditStringToMicros(String(parsed.data.amountDollars));
+ const sourceId =
+ parsed.data.sourceId ?? `manual-dollar:${targetUser.id}:${crypto.randomUUID()}`;
+ const description =
+ parsed.data.description ?? `Manual $${parsed.data.amountDollars} credit grant`;
+
+ const grant = await grantCredits({
+ amountMicros,
+ description,
+ metadata: {
+ amountDollars: String(parsed.data.amountDollars),
+ grantedByUserId: request.donkey.userId,
+ targetUserId: targetUser.id,
+ },
+ source: "manual_dollar",
+ sourceId,
+ userId: targetUser.id,
+ });
+ const balance = await getCreditBalance(targetUser.id);
+
+ return NextResponse.json({
+ amountDollars: parsed.data.amountDollars,
+ creditMicrosGranted: amountMicros.toString(),
+ creditsGranted: creditMicrosToString(amountMicros),
+ grant: {
+ id: grant.id,
+ source: grant.source,
+ sourceId: grant.sourceId,
+ },
+ targetUser: {
+ email: targetUser.email,
+ id: targetUser.id,
+ },
+ balance,
+ });
+});
diff --git a/site/src/lib/donkey-api-auth.ts b/site/src/lib/donkey-api-auth.ts
index 99f8249e..6844f59e 100644
--- a/site/src/lib/donkey-api-auth.ts
+++ b/site/src/lib/donkey-api-auth.ts
@@ -1,6 +1,7 @@
import { type NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
+import { prisma } from "@/lib/prisma";
export type DonkeyAuthContext = {
platform: "api";
@@ -68,3 +69,16 @@ export function withDonkeyAuth<
return handler(authenticatedRequest, ...args);
};
}
+
+export async function isDonkeySuperUser(userId: string) {
+ const user = await prisma.user.findUnique({
+ select: {
+ superUser: true,
+ },
+ where: {
+ id: userId,
+ },
+ });
+
+ return user?.superUser === true;
+}