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.

add rate limiting

Kiran Kb330e27ffb09
diff --git a/apps/web/app/api/tokens/route.ts b/apps/web/app/api/tokens/route.ts
index 2f02c4308e..712daa72d0 100644
--- a/apps/web/app/api/tokens/route.ts
+++ b/apps/web/app/api/tokens/route.ts
@@ -1,3 +1,4 @@
+import { getRateLimitForPlan } from "@/lib/api/tokens/ratelimit";
import { parseRequestBody } from "@/lib/api/utils";
import { hashToken, withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
@@ -50,6 +51,7 @@ export const POST = withWorkspace(
partialKey,
userId: isMachine ? machineUser?.id! : session.user.id,
projectId: workspace.id,
+ rateLimit: getRateLimitForPlan(workspace.plan),
scopes:
scopes && scopes.length > 0 ? [...new Set(scopes)].join(" ") : null,
},
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/tokens/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/tokens/page-client.tsx
index c2abfd2928..e504efd324 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/tokens/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/tokens/page-client.tsx
@@ -42,7 +42,7 @@ export default function TokensPageClient() {
<div className="rounded-lg border border-gray-200 bg-white">
<div className="flex flex-col items-center justify-between gap-2 space-y-3 p-5 sm:flex-row sm:space-y-0 sm:p-10">
<div className="flex flex-col space-y-3">
- <h2 className="text-xl font-medium">Workspace API Keys</h2>
+ <h2 className="text-xl font-medium">API Keys</h2>
<p className="text-sm text-gray-500">
These API keys allow other apps to access your workspace. Use it
with caution – do not share your API key with others, or expose it
@@ -75,7 +75,7 @@ export default function TokensPageClient() {
<div className="flex flex-col items-center justify-center space-y-4 pb-20 pt-10">
<FolderOpen className="h-6 w-6 text-gray-500" />
<p className="text-sm text-gray-500">
- No API keys found. Create one above.
+ No API keys found for this workspace.
</p>
</div>
)}
diff --git a/apps/web/lib/api/tokens/ratelimit.ts b/apps/web/lib/api/tokens/ratelimit.ts
new file mode 100644
index 0000000000..35b00fe1ad
--- /dev/null
+++ b/apps/web/lib/api/tokens/ratelimit.ts
@@ -0,0 +1,20 @@
+import { PlanProps } from "@/lib/types";
+
+// Get rate limit for a given plan in requests per minute
+export const getRateLimitForPlan = (plan: PlanProps) => {
+ switch (plan) {
+ case "free":
+ return 600;
+ case "pro":
+ return 3000;
+ case "business":
+ case "business plus":
+ case "business extra":
+ case "business max":
+ return 6000;
+ // case "enterprise":
+ // return ;
+ }
+
+ return 600;
+}
\ No newline at end of file
diff --git a/apps/web/lib/api/tokens/scopes.ts b/apps/web/lib/api/tokens/scopes.ts
index 68073e6aa8..5761344c59 100644
--- a/apps/web/lib/api/tokens/scopes.ts
+++ b/apps/web/lib/api/tokens/scopes.ts
@@ -143,7 +143,7 @@ export const resourcePermissions = [
// Map roles to scopes
// { owner: ["workspace.write"], member: ["workspace.read"] }
-export const roleScopeMapping = resourcePermissions.reduce<
+export const roleScopesMapping = resourcePermissions.reduce<
Record<Role, Scope[]>
>(
(acc, { permissions }) => {
diff --git a/apps/web/lib/auth/workspace-edge.ts b/apps/web/lib/auth/workspace-edge.ts
index 11681f2e9f..7e1994341a 100644
--- a/apps/web/lib/auth/workspace-edge.ts
+++ b/apps/web/lib/auth/workspace-edge.ts
@@ -11,7 +11,7 @@ import { StreamingTextResponse } from "ai";
import { getToken } from "next-auth/jwt";
import { NextRequest } from "next/server";
import { throwIfNoAccess } from "../api/tokens/permissions";
-import { Scope, roleScopeMapping } from "../api/tokens/scopes";
+import { Scope, roleScopesMapping } from "../api/tokens/scopes";
import { isBetaTester } from "../edge-config";
import { prismaEdge } from "../prisma/edge";
import { hashToken } from "./hash-token";
@@ -127,7 +127,7 @@ export const withWorkspaceEdge = (
hashedKey,
},
select: {
- ...(isRestrictedToken && { scopes: true }),
+ ...(isRestrictedToken && { scopes: true, ratelimit: true }),
user: {
select: {
id: true,
@@ -146,8 +146,11 @@ export const withWorkspaceEdge = (
});
}
+ // Rate limit checks for API keys
+ const rateLimit = "rateLimit" in token ? token.rateLimit : 600;
+
const { success, limit, reset, remaining } = await ratelimit(
- 600,
+ rateLimit,
"1 m",
).limit(apiKey);
headers = {
@@ -233,12 +236,16 @@ export const withWorkspaceEdge = (
}
// For session requests, find the scopes based on the user's role
- if (!apiKey) {
- scopes = roleScopeMapping[workspace.users[0].role];
+ if (session && !apiKey) {
+ scopes = roleScopesMapping[workspace.users[0].role];
}
// Check user has permission to make the action
- throwIfNoAccess({ scopes, requiredScopes, workspaceId: workspace.id });
+ throwIfNoAccess({
+ scopes,
+ requiredScopes,
+ workspaceId: workspace.id,
+ });
// beta feature checks
if (betaFeature) {
diff --git a/apps/web/lib/auth/workspace.ts b/apps/web/lib/auth/workspace.ts
index 620ebc7eb1..2390ee7b44 100644
--- a/apps/web/lib/auth/workspace.ts
+++ b/apps/web/lib/auth/workspace.ts
@@ -15,7 +15,11 @@ import {
import { Link as LinkProps } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import { throwIfNoAccess } from "../api/tokens/permissions";
-import { Scope, availableScopes, roleScopeMapping } from "../api/tokens/scopes";
+import {
+ Scope,
+ availableScopes,
+ roleScopesMapping,
+} from "../api/tokens/scopes";
import { isBetaTester } from "../edge-config";
import { hashToken } from "./hash-token";
import { Session, getSession } from "./utils";
@@ -154,7 +158,7 @@ export const withWorkspace = (
hashedKey,
},
select: {
- ...(isRestrictedToken && { scopes: true }),
+ ...(isRestrictedToken && { scopes: true, rateLimit: true }),
user: {
select: {
id: true,
@@ -173,8 +177,11 @@ export const withWorkspace = (
});
}
+ // Rate limit checks for API keys
+ const rateLimit = "rateLimit" in token ? token.rateLimit : 600;
+
const { success, limit, reset, remaining } = await ratelimit(
- 600,
+ rateLimit,
"1 m",
).limit(apiKey);
headers = {
@@ -287,12 +294,16 @@ export const withWorkspace = (
}
// For session requests, find the scopes based on the user's role
- if (!apiKey) {
- scopes = roleScopeMapping[workspace.users[0].role];
+ if (session && !apiKey) {
+ scopes = roleScopesMapping[workspace.users[0].role];
}
// Check user has permission to make the action
- throwIfNoAccess({ scopes, requiredScopes, workspaceId: workspace.id });
+ throwIfNoAccess({
+ scopes,
+ requiredScopes,
+ workspaceId: workspace.id,
+ });
// beta feature checks
if (betaFeature) {
diff --git a/apps/web/prisma/schema.prisma b/apps/web/prisma/schema.prisma
index ed9ac623dd..082c1c39c5 100644
--- a/apps/web/prisma/schema.prisma
+++ b/apps/web/prisma/schema.prisma
@@ -13,12 +13,12 @@ generator client {
}
model User {
- id String @id @default(cuid())
- name String?
- email String? @unique
- emailVerified DateTime?
- image String?
- isMachine Boolean @default(false)
+ id String @id @default(cuid())
+ name String?
+ email String? @unique
+ emailVerified DateTime?
+ image String?
+ isMachine Boolean @default(false)
accounts Account[]
sessions Session[]
@@ -94,9 +94,10 @@ model RestrictedToken {
name String
hashedKey String @unique
partialKey String
- scopes String? // space separated
+ scopes String? // space separated (Eg: "read:links write:links")
expires DateTime?
lastUsed DateTime?
+ rateLimit Int // rate limit for the token
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
userId String