Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Limit the workspace API keys

Kiran K525a84a6e040
diff --git a/apps/web/app/api/tokens/route.ts b/apps/web/app/api/tokens/route.ts
index e2e616360c..b7a9b0f158 100644
--- a/apps/web/app/api/tokens/route.ts
+++ b/apps/web/app/api/tokens/route.ts
@@ -4,15 +4,18 @@ import { scopesToName, validateScopesForRole } from "@/lib/api/tokens/scopes";
import { parseRequestBody } from "@/lib/api/utils";
import { hashToken, withWorkspace } from "@/lib/auth";
import { generateRandomName } from "@/lib/names";
+import { ratelimit } from "@/lib/upstash";
import { createTokenSchema, tokenSchema } from "@/lib/zod/schemas/token";
import { sendEmail } from "@dub/email";
import { APIKeyCreated } from "@dub/email/templates/api-key-created";
import { prisma } from "@dub/prisma";
-import { User } from "@dub/prisma/client";
+import { Prisma, User } from "@dub/prisma/client";
import { getCurrentPlan, nanoid } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
+const MAX_WORKSPACE_TOKENS = 100;
+
// GET /api/tokens - get all tokens for a workspace
export const GET = withWorkspace(
async ({ workspace }) => {
@@ -52,6 +55,17 @@ export const GET = withWorkspace(
// POST /api/tokens – create a new token for a workspace
export const POST = withWorkspace(
async ({ req, session, workspace }) => {
+ const { success } = await ratelimit(1, "5 s").limit(
+ `create-tokens:${workspace.id}`,
+ );
+
+ if (!success) {
+ throw new DubApiError({
+ code: "rate_limit_exceeded",
+ message: "Too many requests. Please try again later.",
+ });
+ }
+
const { name, isMachine, scopes } = createTokenSchema.parse(
await parseRequestBody(req),
);
@@ -85,47 +99,71 @@ export const POST = withWorkspace(
});
}
- // Create machine user if needed
- if (isMachine) {
- const randomName = generateRandomName();
- machineUser = await prisma.user.create({
- data: {
- id: createId({ prefix: "user_" }),
- name: `${randomName} (Machine User)`,
- isMachine: true,
- },
- select: {
- id: true,
- },
- });
-
- // Add machine user to workspace
- await prisma.projectUsers.create({
- data: {
- role: "member",
- userId: machineUser.id,
- projectId: workspace.id,
- },
- });
- }
-
// Create token
const token = `dub_${nanoid(24)}`;
const hashedKey = await hashToken(token);
const partialKey = `${token.slice(0, 3)}...${token.slice(-4)}`;
- await prisma.restrictedToken.create({
- data: {
- name,
- hashedKey,
- partialKey,
- userId: isMachine ? machineUser?.id! : session.user.id,
- projectId: workspace.id,
- rateLimit: getCurrentPlan(workspace.plan).limits.api,
- scopes:
- scopes && scopes.length > 0 ? [...new Set(scopes)].join(" ") : null,
+ await prisma.$transaction(
+ async (tx) => {
+ const totalTokens = await tx.restrictedToken.count({
+ where: {
+ projectId: workspace.id,
+ installationId: null, // Skip OAuth installations tokens
+ },
+ });
+
+ if (totalTokens >= MAX_WORKSPACE_TOKENS) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: `You've reached your limit of ${MAX_WORKSPACE_TOKENS} API keys for this workspace. Please contact support to increase this limit.`,
+ });
+ }
+
+ // Create machine user if needed
+ if (isMachine) {
+ machineUser = await tx.user.create({
+ data: {
+ id: createId({ prefix: "user_" }),
+ name: `${generateRandomName()} (Machine User)`,
+ isMachine: true,
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ // Add machine user to workspace
+ await tx.projectUsers.create({
+ data: {
+ role: "member",
+ userId: machineUser.id,
+ projectId: workspace.id,
+ },
+ });
+ }
+
+ return await tx.restrictedToken.create({
+ data: {
+ name,
+ hashedKey,
+ partialKey,
+ userId: isMachine ? machineUser?.id! : session.user.id,
+ projectId: workspace.id,
+ rateLimit: getCurrentPlan(workspace.plan).limits.api,
+ scopes:
+ scopes && scopes.length > 0
+ ? [...new Set(scopes)].join(" ")
+ : null,
+ },
+ });
},
- });
+ {
+ isolationLevel: Prisma.TransactionIsolationLevel.ReadUncommitted,
+ maxWait: 5000,
+ timeout: 5000,
+ },
+ );
waitUntil(
sendEmail({