Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(web): add developer platform server actions

Richie McIlroy1a944788714b
diff --git a/apps/web/actions/developers/add-domain.ts b/apps/web/actions/developers/add-domain.ts
new file mode 100644
index 000000000..a0afa2fe7
--- /dev/null
+++ b/apps/web/actions/developers/add-domain.ts
@@ -0,0 +1,44 @@
+"use server";
+
+import { db } from "@cap/database";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { nanoId } from "@cap/database/helpers";
+import { developerAppDomains, developerApps } from "@cap/database/schema";
+import { and, eq, isNull } from "drizzle-orm";
+import { revalidatePath } from "next/cache";
+
+export async function addDeveloperDomain(appId: string, domain: string) {
+ const user = await getCurrentUser();
+ if (!user) throw new Error("Unauthorized");
+
+ const trimmed = domain.trim().toLowerCase();
+ if (!trimmed) throw new Error("Domain is required");
+
+ const urlPattern = /^https?:\/\/[a-z0-9.-]+(:[0-9]+)?$/;
+ if (!urlPattern.test(trimmed)) {
+ throw new Error("Domain must be a valid origin (e.g. https://myapp.com)");
+ }
+
+ const [app] = await db()
+ .select()
+ .from(developerApps)
+ .where(
+ and(
+ eq(developerApps.id, appId),
+ eq(developerApps.ownerId, user.id),
+ isNull(developerApps.deletedAt),
+ ),
+ )
+ .limit(1);
+
+ if (!app) throw new Error("App not found");
+
+ await db().insert(developerAppDomains).values({
+ id: nanoId(),
+ appId,
+ domain: trimmed,
+ });
+
+ revalidatePath("/dashboard/developers");
+ return { success: true };
+}
diff --git a/apps/web/actions/developers/create-app.ts b/apps/web/actions/developers/create-app.ts
new file mode 100644
index 000000000..fa964d755
--- /dev/null
+++ b/apps/web/actions/developers/create-app.ts
@@ -0,0 +1,68 @@
+"use server";
+
+import { db } from "@cap/database";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { encrypt } from "@cap/database/crypto";
+import { nanoId, nanoIdLong } from "@cap/database/helpers";
+import {
+ developerApiKeys,
+ developerApps,
+ developerCreditAccounts,
+} from "@cap/database/schema";
+import { hashKey } from "@/lib/developer-key-hash";
+
+export async function createDeveloperApp(data: {
+ name: string;
+ environment: "development" | "production";
+}) {
+ const user = await getCurrentUser();
+ if (!user) throw new Error("Unauthorized");
+
+ if (!data.name.trim()) throw new Error("App name is required");
+
+ const appId = nanoId();
+ const publicKeyRaw = `cpk_${nanoIdLong()}`;
+ const secretKeyRaw = `csk_${nanoIdLong()}`;
+ const publicKeyHash = await hashKey(publicKeyRaw);
+ const secretKeyHash = await hashKey(secretKeyRaw);
+
+ await db().insert(developerApps).values({
+ id: appId,
+ ownerId: user.id,
+ name: data.name.trim(),
+ environment: data.environment,
+ });
+
+ await db()
+ .insert(developerApiKeys)
+ .values([
+ {
+ id: nanoId(),
+ appId,
+ keyType: "public",
+ keyPrefix: publicKeyRaw.slice(0, 12),
+ keyHash: publicKeyHash,
+ encryptedKey: await encrypt(publicKeyRaw),
+ },
+ {
+ id: nanoId(),
+ appId,
+ keyType: "secret",
+ keyPrefix: secretKeyRaw.slice(0, 12),
+ keyHash: secretKeyHash,
+ encryptedKey: await encrypt(secretKeyRaw),
+ },
+ ]);
+
+ await db().insert(developerCreditAccounts).values({
+ id: nanoId(),
+ appId,
+ ownerId: user.id,
+ });
+
+ return {
+ appId,
+ publicKey: publicKeyRaw,
+ secretKey: secretKeyRaw,
+ };
+}
diff --git a/apps/web/actions/developers/delete-app.ts b/apps/web/actions/developers/delete-app.ts
new file mode 100644
index 000000000..f90ad7fec
--- /dev/null
+++ b/apps/web/actions/developers/delete-app.ts
@@ -0,0 +1,34 @@
+"use server";
+
+import { db } from "@cap/database";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { developerApps } from "@cap/database/schema";
+import { and, eq, isNull } from "drizzle-orm";
+import { revalidatePath } from "next/cache";
+
+export async function deleteDeveloperApp(appId: string) {
+ const user = await getCurrentUser();
+ if (!user) throw new Error("Unauthorized");
+
+ const [app] = await db()
+ .select()
+ .from(developerApps)
+ .where(
+ and(
+ eq(developerApps.id, appId),
+ eq(developerApps.ownerId, user.id),
+ isNull(developerApps.deletedAt),
+ ),
+ )
+ .limit(1);
+
+ if (!app) throw new Error("App not found");
+
+ await db()
+ .update(developerApps)
+ .set({ deletedAt: new Date() })
+ .where(eq(developerApps.id, appId));
+
+ revalidatePath("/dashboard/developers");
+ return { success: true };
+}
diff --git a/apps/web/actions/developers/delete-video.ts b/apps/web/actions/developers/delete-video.ts
new file mode 100644
index 000000000..b26e3817c
--- /dev/null
+++ b/apps/web/actions/developers/delete-video.ts
@@ -0,0 +1,36 @@
+"use server";
+
+import { db } from "@cap/database";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { developerApps, developerVideos } from "@cap/database/schema";
+import { and, eq, isNull } from "drizzle-orm";
+import { revalidatePath } from "next/cache";
+
+export async function deleteDeveloperVideo(appId: string, videoId: string) {
+ const user = await getCurrentUser();
+ if (!user) throw new Error("Unauthorized");
+
+ const [app] = await db()
+ .select()
+ .from(developerApps)
+ .where(
+ and(
+ eq(developerApps.id, appId),
+ eq(developerApps.ownerId, user.id),
+ isNull(developerApps.deletedAt),
+ ),
+ )
+ .limit(1);
+
+ if (!app) throw new Error("App not found");
+
+ await db()
+ .update(developerVideos)
+ .set({ deletedAt: new Date() })
+ .where(
+ and(eq(developerVideos.id, videoId), eq(developerVideos.appId, appId)),
+ );
+
+ revalidatePath("/dashboard/developers");
+ return { success: true };
+}
diff --git a/apps/web/actions/developers/purchase-credits.ts b/apps/web/actions/developers/purchase-credits.ts
new file mode 100644
index 000000000..da79b7464
--- /dev/null
+++ b/apps/web/actions/developers/purchase-credits.ts
@@ -0,0 +1,64 @@
+import { db } from "@cap/database";
+import { nanoId } from "@cap/database/helpers";
+import {
+ type DeveloperCreditReferenceType,
+ developerCreditAccounts,
+ developerCreditTransactions,
+} from "@cap/database/schema";
+import { eq, sql } from "drizzle-orm";
+
+const MICRO_CREDITS_PER_DOLLAR = 100_000;
+
+export async function addCreditsToAccount({
+ accountId,
+ amountCents,
+ referenceId,
+ referenceType,
+ metadata,
+}: {
+ accountId: string;
+ amountCents: number;
+ referenceId?: string;
+ referenceType?: DeveloperCreditReferenceType;
+ metadata?: Record<string, unknown>;
+}): Promise<number> {
+ const microCreditsToAdd = Math.floor(
+ (amountCents / 100) * MICRO_CREDITS_PER_DOLLAR,
+ );
+
+ const newBalance = await db().transaction(async (tx) => {
+ await tx
+ .update(developerCreditAccounts)
+ .set({
+ balanceMicroCredits: sql`${developerCreditAccounts.balanceMicroCredits} + ${microCreditsToAdd}`,
+ })
+ .where(eq(developerCreditAccounts.id, accountId));
+
+ const [updated] = await tx
+ .select({
+ balanceMicroCredits: developerCreditAccounts.balanceMicroCredits,
+ })
+ .from(developerCreditAccounts)
+ .where(eq(developerCreditAccounts.id, accountId))
+ .limit(1);
+
+ if (!updated) {
+ throw new Error(`Credit account not found: ${accountId}`);
+ }
+
+ await tx.insert(developerCreditTransactions).values({
+ id: nanoId(),
+ accountId,
+ type: "topup",
+ amountMicroCredits: microCreditsToAdd,
+ balanceAfterMicroCredits: updated.balanceMicroCredits,
+ referenceId,
+ referenceType,
+ metadata: metadata ?? { amountCents },
+ });
+
+ return updated.balanceMicroCredits;
+ });
+
+ return newBalance;
+}
diff --git a/apps/web/actions/developers/regenerate-keys.ts b/apps/web/actions/developers/regenerate-keys.ts
new file mode 100644
index 000000000..8906904c8
--- /dev/null
+++ b/apps/web/actions/developers/regenerate-keys.ts
@@ -0,0 +1,71 @@
+"use server";
+
+import { db } from "@cap/database";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { encrypt } from "@cap/database/crypto";
+import { nanoId, nanoIdLong } from "@cap/database/helpers";
+import { developerApiKeys, developerApps } from "@cap/database/schema";
+import { and, eq, isNull } from "drizzle-orm";
+import { revalidatePath } from "next/cache";
+import { hashKey } from "@/lib/developer-key-hash";
+
+export async function regenerateDeveloperKeys(appId: string) {
+ const user = await getCurrentUser();
+ if (!user) throw new Error("Unauthorized");
+
+ const [app] = await db()
+ .select()
+ .from(developerApps)
+ .where(
+ and(
+ eq(developerApps.id, appId),
+ eq(developerApps.ownerId, user.id),
+ isNull(developerApps.deletedAt),
+ ),
+ )
+ .limit(1);
+
+ if (!app) throw new Error("App not found");
+
+ await db()
+ .update(developerApiKeys)
+ .set({ revokedAt: new Date() })
+ .where(
+ and(
+ eq(developerApiKeys.appId, appId),
+ isNull(developerApiKeys.revokedAt),
+ ),
+ );
+
+ const publicKeyRaw = `cpk_${nanoIdLong()}`;
+ const secretKeyRaw = `csk_${nanoIdLong()}`;
+ const publicKeyHash = await hashKey(publicKeyRaw);
+ const secretKeyHash = await hashKey(secretKeyRaw);
+
+ await db()
+ .insert(developerApiKeys)
+ .values([
+ {
+ id: nanoId(),
+ appId,
+ keyType: "public",
+ keyPrefix: publicKeyRaw.slice(0, 12),
+ keyHash: publicKeyHash,
+ encryptedKey: await encrypt(publicKeyRaw),
+ },
+ {
+ id: nanoId(),
+ appId,
+ keyType: "secret",
+ keyPrefix: secretKeyRaw.slice(0, 12),
+ keyHash: secretKeyHash,
+ encryptedKey: await encrypt(secretKeyRaw),
+ },
+ ]);
+
+ revalidatePath("/dashboard/developers");
+ return {
+ publicKey: publicKeyRaw,
+ secretKey: secretKeyRaw,
+ };
+}
diff --git a/apps/web/actions/developers/remove-domain.ts b/apps/web/actions/developers/remove-domain.ts
new file mode 100644
index 000000000..e82e98bc5
--- /dev/null
+++ b/apps/web/actions/developers/remove-domain.ts
@@ -0,0 +1,38 @@
+"use server";
+
+import { db } from "@cap/database";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { developerAppDomains, developerApps } from "@cap/database/schema";
+import { and, eq, isNull } from "drizzle-orm";
+import { revalidatePath } from "next/cache";
+
+export async function removeDeveloperDomain(appId: string, domainId: string) {
+ const user = await getCurrentUser();
+ if (!user) throw new Error("Unauthorized");
+
+ const [app] = await db()
+ .select()
+ .from(developerApps)
+ .where(
+ and(
+ eq(developerApps.id, appId),
+ eq(developerApps.ownerId, user.id),
+ isNull(developerApps.deletedAt),
+ ),
+ )
+ .limit(1);
+
+ if (!app) throw new Error("App not found");
+
+ await db()
+ .delete(developerAppDomains)
+ .where(
+ and(
+ eq(developerAppDomains.id, domainId),
+ eq(developerAppDomains.appId, appId),
+ ),
+ );
+
+ revalidatePath("/dashboard/developers");
+ return { success: true };
+}
diff --git a/apps/web/actions/developers/update-app.ts b/apps/web/actions/developers/update-app.ts
new file mode 100644
index 000000000..82100b74e
--- /dev/null
+++ b/apps/web/actions/developers/update-app.ts
@@ -0,0 +1,46 @@
+"use server";
+
+import { db } from "@cap/database";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { developerApps } from "@cap/database/schema";
+import { and, eq, isNull } from "drizzle-orm";
+import { revalidatePath } from "next/cache";
+
+export async function updateDeveloperApp(data: {
+ appId: string;
+ name?: string;
+ environment?: "development" | "production";
+ logoUrl?: string | null;
+}) {
+ const user = await getCurrentUser();
+ if (!user) throw new Error("Unauthorized");
+
+ const [app] = await db()
+ .select()
+ .from(developerApps)
+ .where(
+ and(
+ eq(developerApps.id, data.appId),
+ eq(developerApps.ownerId, user.id),
+ isNull(developerApps.deletedAt),
+ ),
+ )
+ .limit(1);
+
+ if (!app) throw new Error("App not found");
+
+ const updates: Partial<typeof developerApps.$inferInsert> = {};
+ if (data.name !== undefined) updates.name = data.name.trim();
+ if (data.environment !== undefined) updates.environment = data.environment;
+ if (data.logoUrl !== undefined) updates.logoUrl = data.logoUrl;
+
+ if (Object.keys(updates).length > 0) {
+ await db()
+ .update(developerApps)
+ .set(updates)
+ .where(eq(developerApps.id, data.appId));
+ }
+
+ revalidatePath("/dashboard/developers");
+ return { success: true };
+}
diff --git a/apps/web/actions/developers/update-auto-topup.ts b/apps/web/actions/developers/update-auto-topup.ts
new file mode 100644
index 000000000..68927e65c
--- /dev/null
+++ b/apps/web/actions/developers/update-auto-topup.ts
@@ -0,0 +1,60 @@
+"use server";
+
+import { db } from "@cap/database";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { developerApps, developerCreditAccounts } from "@cap/database/schema";
+import { and, eq, isNull } from "drizzle-orm";
+import { revalidatePath } from "next/cache";
+
+export async function updateDeveloperAutoTopUp(data: {
+ appId: string;
+ enabled: boolean;
+ thresholdMicroCredits?: number;
+ amountCents?: number;
+}) {
+ const user = await getCurrentUser();
+ if (!user) throw new Error("Unauthorized");
+
+ const [app] = await db()
+ .select()
+ .from(developerApps)
+ .where(
+ and(
+ eq(developerApps.id, data.appId),
+ eq(developerApps.ownerId, user.id),
+ isNull(developerApps.deletedAt),
+ ),
+ )
+ .limit(1);
+
+ if (!app) throw new Error("App not found");
+
+ if (
+ data.thresholdMicroCredits !== undefined &&
+ data.thresholdMicroCredits < 0
+ ) {
+ throw new Error("Threshold must be non-negative");
+ }
+ if (data.amountCents !== undefined && data.amountCents <= 0) {
+ throw new Error("Top-up amount must be positive");
+ }
+
+ const updates: Partial<typeof developerCreditAccounts.$inferInsert> = {
+ autoTopUpEnabled: data.enabled,
+ };
+
+ if (data.thresholdMicroCredits !== undefined) {
+ updates.autoTopUpThresholdMicroCredits = data.thresholdMicroCredits;
+ }
+ if (data.amountCents !== undefined) {
+ updates.autoTopUpAmountCents = data.amountCents;
+ }
+
+ await db()
+ .update(developerCreditAccounts)
+ .set(updates)
+ .where(eq(developerCreditAccounts.appId, data.appId));
+
+ revalidatePath("/dashboard/developers");
+ return { success: true };
+}