Skip to content

Open source CapCut alternative.

TypeScript

Add Stripe billing and API-key management endpoints

David Le66af2fef140e
diff --git a/site/src/app/api/api-keys/[id]/route.ts b/site/src/app/api/api-keys/[id]/route.ts
new file mode 100644
index 00000000..c81f3669
--- /dev/null
+++ b/site/src/app/api/api-keys/[id]/route.ts
@@ -0,0 +1,23 @@
+import { NextResponse } from "next/server";
+
+import { auth } from "@/lib/auth";
+import { withDonkeyAuth } from "@/lib/donkey-api-auth";
+
+export const dynamic = "force-dynamic";
+
+type RouteContext = { params: Promise<{ id: string }> };
+
+// Revoke (delete) one of the signed-in user's API keys. Better Auth enforces
+// ownership against the session, so a user can only delete their own keys.
+export const DELETE = withDonkeyAuth(
+ async (request, context: RouteContext) => {
+ const { id } = await context.params;
+
+ await auth.api.deleteApiKey({
+ body: { keyId: id },
+ headers: request.headers,
+ });
+
+ return NextResponse.json({ deleted: true });
+ },
+);
diff --git a/site/src/app/api/api-keys/route.ts b/site/src/app/api/api-keys/route.ts
new file mode 100644
index 00000000..ea243e44
--- /dev/null
+++ b/site/src/app/api/api-keys/route.ts
@@ -0,0 +1,98 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+import { auth, visionApiKeyPrefix } from "@/lib/auth";
+import { getActiveVisionSubscription } from "@/lib/billing/vision-subscription";
+import {
+ donkeySessionUserId,
+ withDonkeyAuth,
+} from "@/lib/donkey-api-auth";
+import { validationErrorResponse } from "@/lib/inference/responses";
+
+export const dynamic = "force-dynamic";
+
+function unauthorized() {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+}
+
+const createApiKeySchema = z.object({
+ name: z.string().trim().min(1).max(120),
+});
+
+type ApiKeyRecord = {
+ id: string;
+ name: string | null;
+ start: string | null;
+ prefix: string | null;
+ enabled: boolean | null;
+ referenceId: string;
+ createdAt: Date;
+ lastRequest: Date | null;
+ expiresAt: Date | null;
+};
+
+function toSafeApiKey(key: ApiKeyRecord) {
+ return {
+ createdAt: key.createdAt,
+ enabled: key.enabled ?? true,
+ expiresAt: key.expiresAt,
+ id: key.id,
+ lastRequest: key.lastRequest,
+ name: key.name,
+ // start + prefix let the UI show e.g. "dk_live_abc…" without the secret.
+ prefix: key.prefix,
+ start: key.start,
+ };
+}
+
+// List the signed-in user's Vision API keys (secrets never returned). The
+// referenceId filter is defense-in-depth: the plugin already scopes by session,
+// but we never return a key the session user does not own.
+export const GET = withDonkeyAuth(async (request) => {
+ const userId = donkeySessionUserId(request);
+ if (!userId) {
+ return unauthorized();
+ }
+
+ const result = (await auth.api.listApiKeys({
+ headers: request.headers,
+ })) as { apiKeys: ApiKeyRecord[] } | ApiKeyRecord[];
+ const keys = Array.isArray(result) ? result : result.apiKeys;
+ const ownKeys = keys.filter((key) => key.referenceId === userId);
+
+ return NextResponse.json({ apiKeys: ownKeys.map(toSafeApiKey) });
+});
+
+// Create a new key. Gated on an active Vision API subscription. The full secret
+// is returned exactly once here and never again.
+export const POST = withDonkeyAuth(async (request) => {
+ const userId = donkeySessionUserId(request);
+ if (!userId) {
+ return unauthorized();
+ }
+
+ const subscription = await getActiveVisionSubscription(userId);
+ if (!subscription) {
+ return unauthorized();
+ }
+
+ const body = await request.json().catch(() => null);
+ const parsed = createApiKeySchema.safeParse(body);
+ if (!parsed.success) {
+ return validationErrorResponse(parsed.error);
+ }
+
+ const created = await auth.api.createApiKey({
+ body: {
+ name: parsed.data.name,
+ prefix: visionApiKeyPrefix,
+ },
+ headers: request.headers,
+ });
+
+ return NextResponse.json({
+ apiKey: toSafeApiKey(created as ApiKeyRecord),
+ // The plaintext secret — display once, store securely client-side, then drop.
+ secret: created.key,
+ });
+});
diff --git a/site/src/app/api/billing/checkout/route.ts b/site/src/app/api/billing/checkout/route.ts
new file mode 100644
index 00000000..15cbbff8
--- /dev/null
+++ b/site/src/app/api/billing/checkout/route.ts
@@ -0,0 +1,64 @@
+import { NextResponse } from "next/server";
+
+import { auth } from "@/lib/auth";
+import {
+ ensureStripeCustomer,
+ getStripe,
+ visionPriceId,
+} from "@/lib/billing/stripe";
+import {
+ notFoundResponse,
+ unauthorizedResponse,
+ withDonkeyAuth,
+} from "@/lib/donkey-api-auth";
+
+export const dynamic = "force-dynamic";
+
+// Start a Stripe Checkout session for the Vision API subscription. Session-only
+// (API keys are not accepted here, the default for withDonkeyAuth). This route
+// keeps its getSession call because it needs the user's email/name for Stripe.
+export const POST = withDonkeyAuth(async (request) => {
+ const session = await auth.api.getSession({ headers: request.headers });
+ if (!session) {
+ return unauthorizedResponse();
+ }
+
+ // Only the Vision API plan is self-serve. Other plan keys (e.g. the Mac app
+ // "pro" plan) are not wired to Stripe yet. This stays a 404 rather than a 401
+ // so the landing card does not treat it as a sign-in prompt.
+ const body = (await request.json().catch(() => ({}))) as {
+ planKey?: unknown;
+ };
+ const planKey =
+ typeof body.planKey === "string" ? body.planKey : "vision";
+ if (planKey !== "vision") {
+ return notFoundResponse();
+ }
+
+ const customerId = await ensureStripeCustomer({
+ email: session.user.email,
+ name: session.user.name,
+ userId: session.user.id,
+ });
+ const stripe = getStripe();
+ const origin = request.nextUrl.origin;
+ const checkout = await stripe.checkout.sessions.create({
+ allow_promotion_codes: true,
+ cancel_url: `${origin}/dashboard?checkout=cancelled`,
+ client_reference_id: session.user.id,
+ customer: customerId,
+ line_items: [{ price: visionPriceId(), quantity: 1 }],
+ mode: "subscription",
+ subscription_data: { metadata: { userId: session.user.id } },
+ success_url: `${origin}/dashboard?checkout=success`,
+ });
+
+ if (!checkout.url) {
+ return NextResponse.json(
+ { error: "server-error", message: "Stripe did not return a URL." },
+ { status: 502 },
+ );
+ }
+
+ return NextResponse.json({ url: checkout.url });
+});
diff --git a/site/src/app/api/billing/portal/route.ts b/site/src/app/api/billing/portal/route.ts
new file mode 100644
index 00000000..bee0a18c
--- /dev/null
+++ b/site/src/app/api/billing/portal/route.ts
@@ -0,0 +1,35 @@
+import { NextResponse } from "next/server";
+
+import { getStripe } from "@/lib/billing/stripe";
+import {
+ donkeySessionUserId,
+ notFoundResponse,
+ unauthorizedResponse,
+ withDonkeyAuth,
+} from "@/lib/donkey-api-auth";
+import { prisma } from "@/lib/prisma";
+
+export const dynamic = "force-dynamic";
+
+// Open the Stripe billing portal for the signed-in customer.
+export const POST = withDonkeyAuth(async (request) => {
+ const userId = donkeySessionUserId(request);
+ if (!userId) {
+ return unauthorizedResponse();
+ }
+
+ const subscription = await prisma.visionApiSubscription.findUnique({
+ where: { userId },
+ });
+ if (!subscription?.stripeCustomerId) {
+ return notFoundResponse();
+ }
+
+ const stripe = getStripe();
+ const portal = await stripe.billingPortal.sessions.create({
+ customer: subscription.stripeCustomerId,
+ return_url: `${request.nextUrl.origin}/dashboard`,
+ });
+
+ return NextResponse.json({ url: portal.url });
+});
diff --git a/site/src/app/api/billing/subscription/route.ts b/site/src/app/api/billing/subscription/route.ts
new file mode 100644
index 00000000..b0bbefec
--- /dev/null
+++ b/site/src/app/api/billing/subscription/route.ts
@@ -0,0 +1,39 @@
+import { NextResponse } from "next/server";
+
+import { isActiveVisionStatus } from "@/lib/billing/vision-subscription";
+import {
+ donkeySessionUserId,
+ unauthorizedResponse,
+ withDonkeyAuth,
+} from "@/lib/donkey-api-auth";
+import { prisma } from "@/lib/prisma";
+
+export const dynamic = "force-dynamic";
+
+// Current Vision API subscription for the signed-in user, or null. Returns
+// isActive so clients don't re-derive the active-status rule.
+export const GET = withDonkeyAuth(async (request) => {
+ const userId = donkeySessionUserId(request);
+ if (!userId) {
+ return unauthorizedResponse();
+ }
+
+ const subscription = await prisma.visionApiSubscription.findUnique({
+ where: { userId },
+ });
+
+ if (!subscription?.stripeSubscriptionId) {
+ return NextResponse.json({ subscription: null });
+ }
+
+ return NextResponse.json({
+ subscription: {
+ cancelAtPeriodEnd: subscription.cancelAtPeriodEnd,
+ currentPeriodEnd: subscription.currentPeriodEnd?.toISOString() ?? null,
+ isActive: isActiveVisionStatus(subscription.status),
+ monthlyCallQuota: subscription.monthlyCallQuota,
+ planKey: subscription.planKey,
+ status: subscription.status,
+ },
+ });
+});
diff --git a/site/src/app/api/billing/usage/route.ts b/site/src/app/api/billing/usage/route.ts
new file mode 100644
index 00000000..da79f42a
--- /dev/null
+++ b/site/src/app/api/billing/usage/route.ts
@@ -0,0 +1,59 @@
+import { NextResponse } from "next/server";
+
+import { inferenceUsageRoutes } from "@/lib/credits/inference";
+import {
+ donkeySessionUserId,
+ unauthorizedResponse,
+ withDonkeyAuth,
+} from "@/lib/donkey-api-auth";
+import { prisma } from "@/lib/prisma";
+
+export const dynamic = "force-dynamic";
+
+// Current-period Vision API call usage vs quota, plus recent API calls, for the
+// dashboard. Reads the authoritative per-period counter on the subscription;
+// the recent list is independent so it runs in parallel.
+export const GET = withDonkeyAuth(async (request) => {
+ const userId = donkeySessionUserId(request);
+ if (!userId) {
+ return unauthorizedResponse();
+ }
+
+ const [subscription, recent] = await Promise.all([
+ prisma.visionApiSubscription.findUnique({ where: { userId } }),
+ prisma.inferenceUsageEvent.findMany({
+ orderBy: { createdAt: "desc" },
+ select: {
+ createdAt: true,
+ model: true,
+ requestKind: true,
+ status: true,
+ },
+ take: 20,
+ // billingStatus "included" = the API-key path, so this list never mixes
+ // in the user's Mac-app (credit-billed) vision calls.
+ where: {
+ billingStatus: "included",
+ route: inferenceUsageRoutes.vision,
+ userId,
+ },
+ }),
+ ]);
+
+ const limit = subscription?.monthlyCallQuota ?? 0;
+ const used = subscription?.periodCallCount ?? 0;
+
+ return NextResponse.json({
+ limit,
+ periodEnd: subscription?.currentPeriodEnd?.toISOString() ?? null,
+ periodStart: subscription?.currentPeriodStart?.toISOString() ?? null,
+ recent: recent.map((event) => ({
+ createdAt: event.createdAt.toISOString(),
+ model: event.model,
+ requestKind: event.requestKind,
+ status: event.status,
+ })),
+ remaining: Math.max(0, limit - used),
+ used,
+ });
+});
diff --git a/site/src/app/api/billing/webhook/route.ts b/site/src/app/api/billing/webhook/route.ts
new file mode 100644
index 00000000..4b1c7af4
--- /dev/null
+++ b/site/src/app/api/billing/webhook/route.ts
@@ -0,0 +1,76 @@
+import { NextResponse } from "next/server";
+import type Stripe from "stripe";
+
+import {
+ getStripe,
+ stripeId,
+ syncVisionSubscription,
+} from "@/lib/billing/stripe";
+import { notFoundResponse } from "@/lib/donkey-api-auth";
+
+export const dynamic = "force-dynamic";
+
+// Public, signature-verified Stripe webhook. This is an intentional exception to
+// the "wrap every route with withDonkeyAuth" rule (see docs/guides/backend-apis):
+// Stripe authenticates via the webhook signature, not a Donkey session.
+export async function POST(request: Request) {
+ const secret = process.env.STRIPE_WEBHOOK_SECRET;
+ if (!secret) {
+ return notFoundResponse();
+ }
+
+ const signature = request.headers.get("stripe-signature");
+ if (!signature) {
+ return NextResponse.json(
+ { error: "bad-request", message: "Missing stripe-signature." },
+ { status: 400 },
+ );
+ }
+
+ const stripe = getStripe();
+ const rawBody = await request.text();
+
+ let event: Stripe.Event;
+ try {
+ event = await stripe.webhooks.constructEventAsync(rawBody, signature, secret);
+ } catch (error) {
+ console.error("[billing] webhook signature verification failed", error);
+ return NextResponse.json(
+ { error: "bad-request", message: "Invalid signature." },
+ { status: 400 },
+ );
+ }
+
+ switch (event.type) {
+ case "checkout.session.completed": {
+ const subscriptionId = stripeId(event.data.object.subscription);
+ if (subscriptionId) {
+ const subscription = await stripe.subscriptions.retrieve(subscriptionId);
+ await syncVisionSubscription(subscription);
+ }
+ break;
+ }
+ case "customer.subscription.created":
+ case "customer.subscription.updated":
+ case "customer.subscription.deleted": {
+ await syncVisionSubscription(event.data.object);
+ break;
+ }
+ case "invoice.paid":
+ case "invoice.payment_failed": {
+ const invoice = event.data.object as Stripe.Invoice & {
+ subscription?: string | { id: string } | null;
+ };
+ const subscriptionId = stripeId(invoice.subscription);
+ if (subscriptionId) {
+ const subscription = await stripe.subscriptions.retrieve(subscriptionId);
+ await syncVisionSubscription(subscription);
+ }
+ break;
+ }
+ default:
+ break;
+ }
+
+ return NextResponse.json({ received: true });
+}
diff --git a/site/src/app/api/credits/grants/route.ts b/site/src/app/api/credits/grants/route.ts
index 7c8b80bb..2b0584dd 100644
--- a/site/src/app/api/credits/grants/route.ts
+++ b/site/src/app/api/credits/grants/route.ts
@@ -3,7 +3,11 @@ 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 {
+ isDonkeySuperUser,
+ notFoundResponse,
+ withDonkeyAuth,
+} from "@/lib/donkey-api-auth";
import { prisma } from "@/lib/prisma";
export const dynamic = "force-dynamic";
@@ -51,13 +55,7 @@ export const POST = withDonkeyAuth(async (request) => {
});
if (!targetUser) {
- return NextResponse.json(
- {
- error: "Not found",
- message: "No user exists with that id.",
- },
- { status: 404 },
- );
+ return notFoundResponse();
}
const amountMicros = creditStringToMicros(String(parsed.data.amountDollars));
diff --git a/site/src/lib/billing/stripe.ts b/site/src/lib/billing/stripe.ts
new file mode 100644
index 00000000..a2220edc
--- /dev/null
+++ b/site/src/lib/billing/stripe.ts
@@ -0,0 +1,185 @@
+import Stripe from "stripe";
+
+import { prisma } from "@/lib/prisma";
+
+// The Vision API product is a single self-serve plan. The monthly call quota is
+// read from the Stripe price metadata (key "monthlyCallQuota") so it can be
+// tuned in the Stripe dashboard without a deploy; this constant is the fallback.
+export const visionPlanKey = "vision";
+export const defaultVisionMonthlyQuota = 5_000;
+
+let cachedStripe: Stripe | null = null;
+
+export function getStripe(): Stripe {
+ if (cachedStripe) {
+ return cachedStripe;
+ }
+
+ const secretKey = process.env.STRIPE_SECRET_KEY;
+ if (!secretKey) {
+ throw new StripeNotConfiguredError();
+ }
+
+ cachedStripe = new Stripe(secretKey);
+ return cachedStripe;
+}
+
+export class StripeNotConfiguredError extends Error {
+ public constructor() {
+ super("Stripe is not configured.");
+ this.name = "StripeNotConfiguredError";
+ }
+}
+
+export function visionPriceId(): string {
+ const priceId = process.env.STRIPE_VISION_PRICE_ID;
+ if (!priceId) {
+ throw new StripeNotConfiguredError();
+ }
+
+ return priceId;
+}
+
+export function quotaFromPrice(price: Stripe.Price | null | undefined): number {
+ const raw = price?.metadata?.monthlyCallQuota;
+ if (raw) {
+ const parsed = Number.parseInt(raw, 10);
+ if (Number.isFinite(parsed) && parsed > 0) {
+ return parsed;
+ }
+ }
+
+ return defaultVisionMonthlyQuota;
+}
+
+// Reuse one Stripe customer per user. The id is stored on the user's
+// VisionApiSubscription row once known.
+export async function ensureStripeCustomer(input: {
+ userId: string;
+ email: string;
+ name?: string | null;
+}): Promise<string> {
+ const existing = await prisma.visionApiSubscription.findUnique({
+ where: { userId: input.userId },
+ });
+ if (existing?.stripeCustomerId) {
+ return existing.stripeCustomerId;
+ }
+
+ const stripe = getStripe();
+ const customer = await stripe.customers.create({
+ email: input.email,
+ metadata: { userId: input.userId },
+ name: input.name ?? undefined,
+ });
+
+ await prisma.visionApiSubscription.upsert({
+ create: {
+ planKey: visionPlanKey,
+ stripeCustomerId: customer.id,
+ userId: input.userId,
+ },
+ update: { stripeCustomerId: customer.id },
+ where: { userId: input.userId },
+ });
+
+ return customer.id;
+}
+
+// Source of truth for a subscription's lifecycle. Called from webhook handlers
+// with a fully-expanded Stripe subscription; maps it onto our row.
+export async function syncVisionSubscription(
+ subscription: Stripe.Subscription,
+): Promise<void> {
+ const userId = await resolveUserIdForSubscription(subscription);
+ const customerId = stripeId(subscription.customer);
+ if (!userId || !customerId) {
+ console.error("[billing] could not resolve user/customer for subscription", {
+ customer: customerId,
+ subscription: subscription.id,
+ userId,
+ });
+ return;
+ }
+
+ const item = subscription.items.data[0];
+ const price = item?.price;
+ const periodStart = unixToDate(item?.current_period_start ?? null);
+ const periodEnd = unixToDate(item?.current_period_end ?? null);
+
+ // Reset the per-period call counter when the billing period rolls over, so a
+ // new period starts the quota fresh.
+ const existing = await prisma.visionApiSubscription.findUnique({
+ select: { currentPeriodStart: true },
+ where: { userId },
+ });
+ const periodRolledOver =
+ periodStart !== null &&
+ existing?.currentPeriodStart?.getTime() !== periodStart.getTime();
+
+ await prisma.visionApiSubscription.upsert({
+ create: {
+ cancelAtPeriodEnd: subscription.cancel_at_period_end,
+ currentPeriodEnd: periodEnd,
+ currentPeriodStart: periodStart,
+ monthlyCallQuota: quotaFromPrice(price),
+ planKey: visionPlanKey,
+ status: subscription.status,
+ stripeCustomerId: customerId,
+ stripeSubscriptionId: subscription.id,
+ userId,
+ },
+ update: {
+ cancelAtPeriodEnd: subscription.cancel_at_period_end,
+ currentPeriodEnd: periodEnd,
+ currentPeriodStart: periodStart,
+ monthlyCallQuota: quotaFromPrice(price),
+ status: subscription.status,
+ stripeCustomerId: customerId,
+ stripeSubscriptionId: subscription.id,
+ ...(periodRolledOver ? { periodCallCount: 0 } : {}),
+ },
+ where: { userId },
+ });
+}
+
+async function resolveUserIdForSubscription(
+ subscription: Stripe.Subscription,
+): Promise<string | null> {
+ const metadataUserId = subscription.metadata?.userId;
+ if (metadataUserId) {
+ return metadataUserId;
+ }
+
+ const customerId = stripeId(subscription.customer);
+ if (customerId) {
+ const row = await prisma.visionApiSubscription.findFirst({
+ where: { stripeCustomerId: customerId },
+ });
+ if (row) {
+ return row.userId;
+ }
+ }
+
+ return null;
+}
+
+// Normalize a Stripe field that may be an id string or an expanded object (or
+// absent) to its id. Shared by the webhook handlers.
+export function stripeId(
+ value: string | { id: string } | null | undefined,
+): string | null {
+ if (!value) {
+ return null;
+ }
+
+ return typeof value === "string" ? value : value.id;
+}
+
+function unixToDate(seconds: number | null | undefined): Date | null {
+ if (!seconds) {
+ return null;
+ }
+
+ return new Date(seconds * 1000);
+}
diff --git a/site/src/lib/billing/vision-subscription.ts b/site/src/lib/billing/vision-subscription.ts
new file mode 100644
index 00000000..3d26154d
--- /dev/null
+++ b/site/src/lib/billing/vision-subscription.ts
@@ -0,0 +1,66 @@
+import type { VisionApiSubscription } from "@/generated/prisma/client";
+import { prisma } from "@/lib/prisma";
+
+// Stripe subscription statuses that grant Vision API access.
+const activeStatuses = new Set(["active", "trialing"]);
+
+export type ActiveVisionSubscription = VisionApiSubscription;
+
+export function isActiveVisionStatus(status: string) {
+ return activeStatuses.has(status);
+}
+
+export async function getActiveVisionSubscription(
+ userId: string,
+): Promise<ActiveVisionSubscription | null> {
+ const subscription = await prisma.visionApiSubscription.findUnique({
+ where: { userId },
+ });
+ if (!subscription || !isActiveVisionStatus(subscription.status)) {
+ return null;
+ }
+
+ return subscription;
+}
+
+// Atomically reserve one call against the monthly quota. The conditional
+// UPDATE only increments when the row is still under quota, so concurrent
+// requests can never push periodCallCount past monthlyCallQuota — the count and
+// the check are a single statement. Returns the remaining calls after this one.
+export async function reserveVisionApiCall(input: {
+ userId: string;
+ monthlyCallQuota: number;
+}) {
+ const reserved = await prisma.visionApiSubscription.updateMany({
+ data: { periodCallCount: { increment: 1 } },
+ where: {
+ periodCallCount: { lt: input.monthlyCallQuota },
+ userId: input.userId,
+ },
+ });
+
+ if (reserved.count === 0) {
+ return { ok: false as const };
+ }
+
+ const row = await prisma.visionApiSubscription.findUnique({
+ select: { periodCallCount: true },
+ where: { userId: input.userId },
+ });
+ const used = row?.periodCallCount ?? input.monthlyCallQuota;
+
+ return {
+ ok: true as const,
+ remaining: Math.max(0, input.monthlyCallQuota - used),
+ };
+}
+
+// Release a previously reserved call when the request ultimately fails, so a
+// failed parse doesn't consume the developer's quota (mirrors how the credit
+// path only charges successful calls). Never drops below zero.
+export async function releaseVisionApiCall(userId: string) {
+ await prisma.visionApiSubscription.updateMany({
+ data: { periodCallCount: { decrement: 1 } },
+ where: { periodCallCount: { gt: 0 }, userId },
+ });
+}