The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
getRatelimitForPlan + bust tokenCache
Steven Tey1af0054548a1
diff --git a/apps/web/lib/api/get-ratelimit-for-plan.ts b/apps/web/lib/api/get-ratelimit-for-plan.tsnew file mode 100644index 0000000000..2e4a87ae19--- /dev/null+++ b/apps/web/lib/api/get-ratelimit-for-plan.ts@@ -0,0 +1,8 @@+import { FREE_PLAN, PLANS } from "@dub/utils";++export const getRatelimitForPlan = (plan: string) => {+ const currentPlanName = plan.toLowerCase().split(" ")[0]; // to account for old Business plans (e.g. "Business Plus")+ return (+ PLANS.find((p) => p.name.toLowerCase() === currentPlanName) || FREE_PLAN+ );+};diff --git a/apps/web/lib/auth/token-cache.ts b/apps/web/lib/auth/token-cache.tsindex 669c8d9918..193fb5803f 100644--- a/apps/web/lib/auth/token-cache.ts+++ b/apps/web/lib/auth/token-cache.ts@@ -2,7 +2,7 @@ import { redis } from "@/lib/upstash";import { z } from "zod";const CACHE_EXPIRATION = 60 * 60 * 24; // 24 hours-const CACHE_KEY_PREFIX = "tokenCache";+const CACHE_KEY_PREFIX = "dubTokenCache";const tokenCacheItemSchema = z.object({scopes: z.string().nullish(),@@ -22,7 +22,7 @@ const tokenCacheItemSchema = z.object({.nullish(),});-type TokenCacheItem = z.infer<typeof tokenCacheItemSchema>;+export type TokenCacheItem = z.infer<typeof tokenCacheItemSchema>;// Cache for restricted tokens (and legacy personal tokens)class TokenCache {diff --git a/apps/web/lib/auth/workspace.ts b/apps/web/lib/auth/workspace.tsindex db19aed198..c0ada60d88 100644--- a/apps/web/lib/auth/workspace.ts+++ b/apps/web/lib/auth/workspace.ts@@ -2,9 +2,10 @@ import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";import { BetaFeatures, PlanProps, WorkspaceWithUsers } from "@/lib/types";import { ratelimit } from "@/lib/upstash";import { prisma } from "@dub/prisma";-import { API_DOMAIN, getCurrentPlan, getSearchParams } from "@dub/utils";+import { API_DOMAIN, getSearchParams } from "@dub/utils";import { waitUntil } from "@vercel/functions";import { headers } from "next/headers";+import { getRatelimitForPlan } from "../api/get-ratelimit-for-plan";import {PermissionAction,getPermissionsByRole,@@ -17,7 +18,7 @@ import { getFeatureFlags } from "../edge-config";import { logConversionEvent } from "../tinybird/log-conversion-events";import { hashToken } from "./hash-token";import { rateLimitRequest } from "./rate-limit-request";-import { tokenCache } from "./token-cache";+import { TokenCacheItem, tokenCache } from "./token-cache";import { Session, getSession } from "./utils";export const RATE_LIMIT_FOR_SESSIONS = {@@ -110,7 +111,7 @@ export const withWorkspace = (let workspaceId: string | undefined;let workspaceSlug: string | undefined;let permissions: PermissionAction[] = [];- let token: any | null = null;+ let token: TokenCacheItem | null = null;const isRestrictedToken = apiKey?.startsWith("dub_");const idOrSlug =@@ -239,12 +240,8 @@ export const withWorkspace = (? "1 s": "1 m";- if (token.project?.plan) {- const planLimit = getCurrentPlan(token.project?.plan);- limit = planLimit.limits[isAnalytics ? "analyticsApi" : "api"];- } else {- limit = 60; // default rate limit for personal API keys- }+ const planLimit = getRatelimitForPlan(token.project?.plan || "free");+ limit = planLimit.limits[isAnalytics ? "analyticsApi" : "api"];const { success, headers } = await rateLimitRequest({identifier: `workspace:ratelimit:${hashedKey}`,@@ -266,7 +263,7 @@ export const withWorkspace = (}// Find workspaceId if it's a restricted token- if (isRestrictedToken) {+ if (isRestrictedToken && token?.projectId) {workspaceId = token.projectId;}@@ -408,8 +405,8 @@ export const withWorkspace = (permissions = getPermissionsByRole(workspace.users[0].role);// Find the subset of permissions that the user has access to based on the token scopes- if (isRestrictedToken) {- const tokenScopes: Scope[] = token.scopes.split(" ") || [];+ if (isRestrictedToken && token?.scopes) {+ const tokenScopes = (token.scopes.split(" ") as Scope[]) || [];permissions = mapScopesToPermissions(tokenScopes).filter((p) =>permissions.includes(p),);diff --git a/apps/web/scripts/migrations/backfill-workspace-groups-limit.ts b/apps/web/scripts/migrations/backfill-workspace-groups-limit.tsdeleted file mode 100644index b6297dfee2..0000000000--- a/apps/web/scripts/migrations/backfill-workspace-groups-limit.ts+++ /dev/null@@ -1,59 +0,0 @@-import { prisma } from "@dub/prisma";-import { getCurrentPlan } from "@dub/utils";-import "dotenv-flow/config";--// one time script for backfilling groupsLimit for workspaces-async function main() {- const workspaces = await prisma.project.findMany({- where: {- groupsLimit: 0,- plan: {- notIn: ["free", "pro"],- },- },- select: {- id: true,- slug: true,- plan: true,- groupsLimit: true,- },- take: 100,- });-- if (workspaces.length === 0) {- console.log("No workspaces to update.");- return;- }-- console.table(workspaces);- console.log(`Found ${workspaces.length} workspaces to update.`);-- // Batch update the workspaces- // if "business plus/extra/max", group under business- const groupedByPlan = workspaces.reduce(- (acc, ws) => {- const plan = ws.plan.startsWith("business") ? "business" : ws.plan;- if (!acc[plan]) acc[plan] = [];- acc[plan].push(ws.id);- return acc;- },- {} as Record<string, string[]>,- );-- console.log(groupedByPlan);-- for (const [plan, workspaceIds] of Object.entries(groupedByPlan)) {- await prisma.project.updateMany({- where: {- id: {- in: workspaceIds,- },- },- data: {- groupsLimit: getCurrentPlan(plan).limits.groups!,- },- });- }-}--main();diff --git a/packages/utils/src/constants/pricing.tsx b/packages/utils/src/constants/pricing.tsxindex 202c4658f1..d1e3c7e35e 100644--- a/packages/utils/src/constants/pricing.tsx+++ b/packages/utils/src/constants/pricing.tsx@@ -484,7 +484,7 @@ export const PLANS: PlanDetails[] = [users: 30,ai: 1_000,api: 3_000,- analyticsApi: 20,+ analyticsApi: 16,retention: "Unlimited",},},@@ -570,12 +570,6 @@ export const getPlanDetails = ({return enrichPlanWithTierData(planDetails, planTier);};-export const getCurrentPlan = (plan: string) => {- return (- PLANS.find((p) => p.name.toLowerCase() === plan.toLowerCase()) || FREE_PLAN- );-};-export const getNextPlan = (plan?: string | null) => {if (!plan) return PRO_PLAN;const currentPlan = plan.toLowerCase().split(" ")[0]; // to account for old Business plans (e.g. "Business Plus")