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.

Migrate 10 rate limits to assertRateLimit

Cursor Agente12a07f98eed
diff --git a/apps/web/app/(ee)/api/embed/referrals/tremendous/send-otp/route.ts b/apps/web/app/(ee)/api/embed/referrals/tremendous/send-otp/route.ts
index d7fa890783..942d928ed1 100644
--- a/apps/web/app/(ee)/api/embed/referrals/tremendous/send-otp/route.ts
+++ b/apps/web/app/(ee)/api/embed/referrals/tremendous/send-otp/route.ts
@@ -6,7 +6,9 @@ import { extractEmailDomain } from "@/lib/email/extract-email-domain";
import { withReferralsEmbedToken } from "@/lib/embed/referrals/auth";
import { prisma } from "@/lib/prisma";
import { TREMENDOUS_PROHIBITED_TOP_LEVEL_DOMAINS } from "@/lib/tremendous/constants";
-import { ratelimit, redis } from "@/lib/upstash";
+import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";
+import { redis } from "@/lib/upstash";
+import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
import { emailSchema } from "@/lib/zod/schemas/auth";
import { ACTIVE_ENROLLMENT_STATUSES } from "@/lib/zod/schemas/partners";
import { sendEmail } from "@dub/email";
@@ -33,16 +35,10 @@ export const POST = withReferralsEmbedToken(
const { email } = sendOtpSchema.parse(await parseRequestBody(req));
const { partnerId } = programEnrollment;
- const { success } = await ratelimit(10, "24 h").limit(
- `tremendous-send-otp:${partnerId}`,
- );
-
- if (!success) {
- throw new DubApiError({
- code: "rate_limit_exceeded",
- message: "Too many requests. Please try again later.",
- });
- }
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.tremendousSendOtp,
+ identifier: partnerId,
+ });
const emailDomain = extractEmailDomain(email)!;
diff --git a/apps/web/app/(ee)/api/embed/referrals/tremendous/verify-otp/route.ts b/apps/web/app/(ee)/api/embed/referrals/tremendous/verify-otp/route.ts
index ec1e06af65..97aed02644 100644
--- a/apps/web/app/(ee)/api/embed/referrals/tremendous/verify-otp/route.ts
+++ b/apps/web/app/(ee)/api/embed/referrals/tremendous/verify-otp/route.ts
@@ -4,7 +4,9 @@ import { extractEmailDomain } from "@/lib/email/extract-email-domain";
import { withReferralsEmbedToken } from "@/lib/embed/referrals/auth";
import { prisma } from "@/lib/prisma";
import { TREMENDOUS_PROHIBITED_TOP_LEVEL_DOMAINS } from "@/lib/tremendous/constants";
-import { ratelimit, redis } from "@/lib/upstash";
+import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";
+import { redis } from "@/lib/upstash";
+import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
import { emailSchema } from "@/lib/zod/schemas/auth";
import { ACTIVE_ENROLLMENT_STATUSES } from "@/lib/zod/schemas/partners";
import { TREMENDOUS_SUPPORTED_COUNTRIES } from "@dub/utils";
@@ -31,16 +33,10 @@ export const POST = withReferralsEmbedToken(
const { email, code } = verifyOtpSchema.parse(await parseRequestBody(req));
const { partnerId } = programEnrollment;
- const { success } = await ratelimit(10, "24 h").limit(
- `tremendous-verify-otp:${partnerId}`,
- );
-
- if (!success) {
- throw new DubApiError({
- code: "rate_limit_exceeded",
- message: "Too many requests. Please try again later.",
- });
- }
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.tremendousVerifyOtp,
+ identifier: partnerId,
+ });
const emailDomain = extractEmailDomain(email)!;
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/analytics/export/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/analytics/export/route.ts
index 090d5dbe15..012f12d60c 100644
--- a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/analytics/export/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/analytics/export/route.ts
@@ -15,7 +15,8 @@ import {
LARGE_PROGRAM_MIN_TOTAL_COMMISSIONS_CENTS,
MAX_PARTNER_LINKS_FOR_LOCAL_FILTERING,
} from "@/lib/constants/partner-profile";
-import { ratelimit } from "@/lib/upstash";
+import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";
+import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
import { partnerProfileAnalyticsQuerySchema } from "@/lib/zod/schemas/partner-profile";
import { parseFilterValue, toCentsNumber } from "@dub/utils";
@@ -24,17 +25,10 @@ export const maxDuration = 300;
// GET /api/partner-profile/programs/[programId]/analytics/export – get export data for partner profile analytics
export const GET = withPartnerProfile(
async ({ partner, params, searchParams }) => {
- const { success } = await ratelimit(1, "30 s").limit(
- `analyticsExport:partner:${partner.id}:${params.programId}`,
- );
-
- if (!success) {
- throw new DubApiError({
- code: "rate_limit_exceeded",
- message:
- "Analytics export is limited to once every 30 seconds. Please try again shortly.",
- });
- }
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.partnerAnalyticsExport,
+ identifier: [partner.id, params.programId],
+ });
const { program, links, totalCommissions } =
await getProgramEnrollmentOrThrow({
diff --git a/apps/web/app/(ee)/api/track/application/route.ts b/apps/web/app/(ee)/api/track/application/route.ts
index ed5b08b078..75f1510da5 100644
--- a/apps/web/app/(ee)/api/track/application/route.ts
+++ b/apps/web/app/(ee)/api/track/application/route.ts
@@ -17,7 +17,8 @@ import {
recordClickZod,
recordClickZodSchema,
} from "@/lib/tinybird/record-click-zod";
-import { ratelimit } from "@/lib/upstash";
+import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";
+import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
import { publishLinkClickEvent } from "@/lib/upstash/redis-streams/link-click-events";
import { MARKETPLACE_RESERVED_SLUGS } from "@/ui/program-marketplace/utils/urls";
import {
@@ -48,16 +49,10 @@ export const POST = withAxiom(async (req) => {
}
const ip = await getIP();
- const { success } = await ratelimit(10, "10 s").limit(
- `track-application:${ip}`,
- );
-
- if (!success) {
- throw new DubApiError({
- code: "rate_limit_exceeded",
- message: "Too many requests. Please try again later.",
- });
- }
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.trackApplication,
+ identifier: ip,
+ });
const { eventName, url, referrer } = trackApplicationEventSchema.parse(
await parseRequestBody(req),
diff --git a/apps/web/app/api/tokens/route.ts b/apps/web/app/api/tokens/route.ts
index 675c812122..6890fa207a 100644
--- a/apps/web/app/api/tokens/route.ts
+++ b/apps/web/app/api/tokens/route.ts
@@ -5,7 +5,8 @@ import { parseRequestBody } from "@/lib/api/utils";
import { hashToken, withWorkspace } from "@/lib/auth";
import { generateRandomName } from "@/lib/names";
import { prisma } from "@/lib/prisma";
-import { ratelimit } from "@/lib/upstash";
+import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";
+import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
import { createTokenSchema, tokenSchema } from "@/lib/zod/schemas/token";
import { sendEmail } from "@dub/email";
import APIKeyCreated from "@dub/email/templates/api-key-created";
@@ -66,16 +67,10 @@ 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.",
- });
- }
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.createToken,
+ identifier: workspace.id,
+ });
const { name, isMachine, scopes } = createTokenSchema.parse(
await parseRequestBody(req),
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/invites/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/invites/route.ts
index ca6d66a7dc..4835a1bf72 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/invites/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/invites/route.ts
@@ -4,7 +4,9 @@ import { assertRoleAllowedForPlan } from "@/lib/api/workspaces/assert-role-plan"
import { withWorkspace } from "@/lib/auth";
import { exceededLimitError } from "@/lib/exceeded-limit-error";
import { prisma } from "@/lib/prisma";
-import { ratelimit, redis } from "@/lib/upstash";
+import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";
+import { redis } from "@/lib/upstash";
+import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
import { inviteTeammatesSchema } from "@/lib/zod/schemas/invites";
import {
getWorkspaceUsersQuerySchema,
@@ -58,17 +60,10 @@ export const POST = withWorkspace(
});
}
- const { success } = await ratelimit(1, "1 s").limit(
- `workspace-invites:${workspace.id}`,
- );
-
- if (!success) {
- throw new DubApiError({
- code: "rate_limit_exceeded",
- message:
- "You've reached the rate limit for inviting teammates. Please try again later after few seconds.",
- });
- }
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.workspaceInvite,
+ identifier: workspace.id,
+ });
if (teammates.length > 10) {
throw new DubApiError({
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/sitemaps/import/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/sitemaps/import/route.ts
index cd38532c95..ece5044063 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/sitemaps/import/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/sitemaps/import/route.ts
@@ -8,7 +8,8 @@ import {
parseTrackedSitemaps,
replaceTrackedSitemapsInColumn,
} from "@/lib/sitemaps/site-visit-tracking";
-import { ratelimit } from "@/lib/upstash";
+import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";
+import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
import { NextResponse } from "next/server";
import * as z from "zod/v4";
@@ -43,15 +44,10 @@ export const POST = withWorkspace(
});
}
- const rateLimitKey = `sitemap-import:${workspace.id}:${sitemapUrl ?? "all"}`;
- const { success } = await ratelimit(5, "1 m").limit(rateLimitKey);
- if (!success) {
- throw new DubApiError({
- code: "rate_limit_exceeded",
- message:
- "Sitemap import was requested too recently. Please wait a minute and try again.",
- });
- }
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.sitemapImport,
+ identifier: [workspace.id, sitemapUrl ?? "all"],
+ });
const selectedDomain = await getSiteLinksDomain(
workspace.id,
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/support/slack-invite/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/support/slack-invite/route.ts
index 95186bd695..e960876528 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/support/slack-invite/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/support/slack-invite/route.ts
@@ -3,7 +3,8 @@ import { withWorkspace } from "@/lib/auth";
import { SLACK_SUPPORT_INVITE_MAX_EMAILS } from "@/lib/constants/misc";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
import { requestSlackConnectSupportInvite } from "@/lib/slack/support-invite";
-import { ratelimit } from "@/lib/upstash";
+import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";
+import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
import { isWorkspaceBillingTrialActive } from "@dub/utils";
import { NextResponse } from "next/server";
import * as z from "zod/v4";
@@ -72,29 +73,15 @@ export const POST = withWorkspace(
emails = [email];
}
- const { success: workspaceSuccess } = await ratelimit(5, "1 d").limit(
- `slack-support-invite:workspace:${workspace.id}`,
- );
-
- if (!workspaceSuccess) {
- throw new DubApiError({
- code: "rate_limit_exceeded",
- message:
- "This workspace has reached the daily limit for Slack invite requests. Please try again tomorrow.",
- });
- }
-
- const { success: userSuccess } = await ratelimit(10, "1 h").limit(
- `slack-support-invite:${workspace.id}:${session.user.id}`,
- );
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.slackSupportInviteWorkspace,
+ identifier: workspace.id,
+ });
- if (!userSuccess) {
- throw new DubApiError({
- code: "rate_limit_exceeded",
- message:
- "You've requested too many Slack invites recently. Please try again later.",
- });
- }
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.slackSupportInviteUser,
+ identifier: [workspace.id, session.user.id],
+ });
const { inviteIds } = await requestSlackConnectSupportInvite({
workspaceSlug: workspace.slug,
diff --git a/apps/web/lib/submitted-leads/submit-lead-action.ts b/apps/web/lib/submitted-leads/submit-lead-action.ts
index 75e74f1b3e..8fe2d9f9f8 100644
--- a/apps/web/lib/submitted-leads/submit-lead-action.ts
+++ b/apps/web/lib/submitted-leads/submit-lead-action.ts
@@ -10,7 +10,8 @@ import {
} from "@/lib/submitted-leads/constants";
import { notifyPartnerLeadSubmitted } from "@/lib/submitted-leads/notify-partner-lead-submitted";
import { SubmittedLeadFormDataField } from "@/lib/types";
-import { ratelimit } from "@/lib/upstash";
+import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";
+import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
import {
formFieldSchema,
submittedLeadFormSchema,
@@ -75,16 +76,10 @@ export const submitLeadAction = authPartnerActionClient
});
}
- const { success } = await ratelimit(10, "1 m").limit(
- `rl:submitted-lead:${partner.id}`,
- );
-
- if (!success) {
- throw new DubApiError({
- code: "rate_limit_exceeded",
- message: "Too many leads submitted. Please try again later.",
- });
- }
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.submitLead,
+ identifier: partner.id,
+ });
const programEnrollment = await prisma.programEnrollment.findUnique({
where: {
diff --git a/apps/web/lib/upstash/ratelimit-policies.ts b/apps/web/lib/upstash/ratelimit-policies.ts
index 34cfc59acc..b9bbee67da 100644
--- a/apps/web/lib/upstash/ratelimit-policies.ts
+++ b/apps/web/lib/upstash/ratelimit-policies.ts
@@ -202,4 +202,77 @@ export const RATELIMIT_POLICIES = {
keyPrefix: "rl:partner:identity:verification:start",
message: "Too many verification attempts. Please try again later.",
},
+
+ // Keyed on partner + program so one partner cannot exhaust another's budget
+ partnerAnalyticsExport: {
+ attempts: 1,
+ window: "30 s",
+ keyPrefix: "rl:analytics:export:partner",
+ message:
+ "Analytics export is limited to once every 30 seconds. Please try again shortly.",
+ },
+
+ createToken: {
+ attempts: 1,
+ window: "5 s",
+ keyPrefix: "rl:tokens:create",
+ },
+
+ submitLead: {
+ attempts: 10,
+ window: "1 m",
+ keyPrefix: "rl:submitted-lead",
+ message: "Too many leads submitted. Please try again later.",
+ },
+
+ trackApplication: {
+ attempts: 10,
+ window: "10 s",
+ keyPrefix: "rl:track:application",
+ },
+
+ workspaceInvite: {
+ attempts: 1,
+ window: "1 s",
+ keyPrefix: "rl:workspace:invites",
+ message:
+ "You've reached the rate limit for inviting teammates. Please try again later after few seconds.",
+ },
+
+ slackSupportInviteWorkspace: {
+ attempts: 5,
+ window: "1 d",
+ keyPrefix: "rl:slack-support-invite:workspace",
+ message:
+ "This workspace has reached the daily limit for Slack invite requests. Please try again tomorrow.",
+ },
+
+ // Keyed on workspace + user so one member cannot exhaust the workspace budget
+ slackSupportInviteUser: {
+ attempts: 10,
+ window: "1 h",
+ keyPrefix: "rl:slack-support-invite",
+ message:
+ "You've requested too many Slack invites recently. Please try again later.",
+ },
+
+ sitemapImport: {
+ attempts: 5,
+ window: "1 m",
+ keyPrefix: "rl:sitemap-import",
+ message:
+ "Sitemap import was requested too recently. Please wait a minute and try again.",
+ },
+
+ tremendousSendOtp: {
+ attempts: 10,
+ window: "24 h",
+ keyPrefix: "rl:tremendous:send-otp",
+ },
+
+ tremendousVerifyOtp: {
+ attempts: 10,
+ window: "24 h",
+ keyPrefix: "rl:tremendous:verify-otp",
+ },
} as const satisfies Record<string, RatelimitPolicy>;