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 Agentaa2c39e39fef
diff --git a/apps/web/app/(ee)/api/embed/referrals/bounties/[bountyId]/social-content-stats/route.ts b/apps/web/app/(ee)/api/embed/referrals/bounties/[bountyId]/social-content-stats/route.ts
index ea7b327d2b..4da9a32024 100644
--- a/apps/web/app/(ee)/api/embed/referrals/bounties/[bountyId]/social-content-stats/route.ts
+++ b/apps/web/app/(ee)/api/embed/referrals/bounties/[bountyId]/social-content-stats/route.ts
@@ -8,7 +8,8 @@ import { getBountyOrThrow } from "@/lib/bounty/api/get-bounty-or-throw";
import { resolveBountyDetails } from "@/lib/bounty/utils";
import { withReferralsEmbedToken } from "@/lib/embed/referrals/auth";
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 { NextResponse } from "next/server";
import * as z from "zod/v4";
@@ -22,16 +23,10 @@ export const GET = withReferralsEmbedToken(
const { bountyId } = params;
const { url } = searchParamsSchema.parse(searchParams);
- const { success } = await ratelimit(10, "1 h").limit(
- `partner-profile:social-content-stats:${programEnrollment.partnerId}`,
- );
-
- if (!success) {
- throw new DubApiError({
- code: "rate_limit_exceeded",
- message: "You've been rate limited. Please try again later.",
- });
- }
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.socialContentStats,
+ identifier: programEnrollment.partnerId,
+ });
const bounty = await getBountyOrThrow({
bountyId,
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/[bountyId]/social-content-stats/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/[bountyId]/social-content-stats/route.ts
index 9c5227c4d5..0a73e5dcd2 100644
--- a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/[bountyId]/social-content-stats/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/[bountyId]/social-content-stats/route.ts
@@ -8,7 +8,8 @@ import {
} from "@/lib/bounty/api/bounty-availability";
import { getBountyOrThrow } from "@/lib/bounty/api/get-bounty-or-throw";
import { resolveBountyDetails } from "@/lib/bounty/utils";
-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";
@@ -23,16 +24,10 @@ export const GET = withPartnerProfile(
const { url } = searchParamsSchema.parse(searchParams);
- const { success } = await ratelimit(10, "1 h").limit(
- `partner-profile:social-content-stats:${partner.id}`,
- );
-
- if (!success) {
- throw new DubApiError({
- code: "rate_limit_exceeded",
- message: "You've been rate limited. Please try again later.",
- });
- }
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.socialContentStats,
+ identifier: partner.id,
+ });
const programEnrollment = await getProgramEnrollmentOrThrow({
partnerId: partner.id,
diff --git a/apps/web/app/api/domains/search-availability/route.ts b/apps/web/app/api/domains/search-availability/route.ts
index a99dc4f1fa..b5ef4e7e61 100644
--- a/apps/web/app/api/domains/search-availability/route.ts
+++ b/apps/web/app/api/domains/search-availability/route.ts
@@ -1,6 +1,7 @@
import { getDomainSearchAvailability } from "@/lib/api/domains/get-domain-search-availability";
import { withWorkspace } from "@/lib/auth";
-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";
@@ -19,14 +20,10 @@ export const GET = withWorkspace(
async ({ searchParams }) => {
const { domain } = schema.parse(searchParams);
- // max 1 requests per 5s
- const { success } = await ratelimit(1, "5 s").limit(
- `domain-search:${domain}`,
- );
-
- if (!success) {
- return new Response("Don't DDoS me pls 🥺", { status: 429 });
- }
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.domainSearchAvailability,
+ identifier: domain,
+ });
const response = await getDomainSearchAvailability(domain);
diff --git a/apps/web/app/api/links/route.ts b/apps/web/app/api/links/route.ts
index 3d0393d812..21d17bde5b 100644
--- a/apps/web/app/api/links/route.ts
+++ b/apps/web/app/api/links/route.ts
@@ -8,7 +8,8 @@ import {
MEGA_WORKSPACE_LINKS_LIMIT,
SORTABLE_LINKS_LIMIT,
} from "@/lib/constants/misc";
-import { ratelimit } from "@/lib/upstash";
+import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";
+import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
import {
createLinkBodySchemaAsync,
@@ -64,15 +65,10 @@ export const POST = withWorkspace(
if (!session) {
const ip = req.headers.get("x-forwarded-for") || LOCALHOST_IP;
- const { success } = await ratelimit(10, "1 d").limit(ip);
-
- if (!success) {
- throw new DubApiError({
- code: "rate_limit_exceeded",
- message:
- "Rate limited – you can only create up to 10 links per day without an account.",
- });
- }
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.anonymousLinkCreate,
+ identifier: ip,
+ });
}
const { link, error, code } = await processLink({
diff --git a/apps/web/lib/actions/partners/merge-partner-accounts.ts b/apps/web/lib/actions/partners/merge-partner-accounts.ts
index a727605aa2..b2d3449c94 100644
--- a/apps/web/lib/actions/partners/merge-partner-accounts.ts
+++ b/apps/web/lib/actions/partners/merge-partner-accounts.ts
@@ -3,7 +3,9 @@
import { generateOTP } from "@/lib/auth/utils";
import { dispatchWorkflows } from "@/lib/jobs/publish-workflows";
import { prisma } from "@/lib/prisma";
-import { ratelimit, redis } from "@/lib/upstash";
+import { redis } from "@/lib/upstash";
+import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";
+import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
import { emailSchema } from "@/lib/zod/schemas/auth";
import { sendBatchEmail } from "@dub/email";
import VerifyEmailForAccountMerge from "@dub/email/templates/verify-email-for-account-merge";
@@ -13,7 +15,6 @@ import { authPartnerActionClient } from "../safe-action";
const CACHE_KEY_PREFIX = "merge-partner-accounts";
const CACHE_EXPIRY_IN = 10 * 60; // 10 minutes
const EMAIL_OTP_EXPIRY_IN = 5 * 60; // 5 minutes
-const MAX_ATTEMPTS = 3; // 3 attempts per 24 hours
const schema = z.discriminatedUnion("step", [
z.object({
@@ -71,15 +72,10 @@ const sendTokens = async ({
targetEmail: string;
userId: string;
}) => {
- const { success } = await ratelimit(MAX_ATTEMPTS, "24 h").limit(
- `${CACHE_KEY_PREFIX}:step-1:${userId}`,
- );
-
- if (!success) {
- throw new Error(
- "You've reached the maximum number of attempts for the past 24 hours. Please wait and try again later.",
- );
- }
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.mergePartnerAccounts,
+ identifier: ["step-1", userId],
+ });
const anotherRequestExists = await redis.exists(
`${CACHE_KEY_PREFIX}:${userId}`,
@@ -212,15 +208,10 @@ const verifyTokens = async ({
targetCode: string;
userId: string;
}) => {
- const { success } = await ratelimit(MAX_ATTEMPTS, "24 h").limit(
- `${CACHE_KEY_PREFIX}:step-2:${userId}`,
- );
-
- if (!success) {
- throw new Error(
- "You've reached the maximum number of attempts for the past 24 hours. Please wait and try again later.",
- );
- }
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.mergePartnerAccounts,
+ identifier: ["step-2", userId],
+ });
const [sourceToken, targetToken] = await Promise.all([
prisma.emailVerificationToken.findUnique({
@@ -313,15 +304,10 @@ const verifyTokens = async ({
// Step 3: Merge partner accounts
const mergeAccounts = async ({ userId }: { userId: string }) => {
- const { success } = await ratelimit(MAX_ATTEMPTS, "24 h").limit(
- `${CACHE_KEY_PREFIX}:step-3:${userId}`,
- );
-
- if (!success) {
- throw new Error(
- "You've reached the maximum number of attempts for the past 24 hours. Please wait and try again later.",
- );
- }
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.mergePartnerAccounts,
+ identifier: ["step-3", userId],
+ });
const accounts = await redis.get<{
sourceEmail: string;
diff --git a/apps/web/lib/actions/send-invite-referral-email.ts b/apps/web/lib/actions/send-invite-referral-email.ts
index 13d8d467cb..607a0fad6d 100644
--- a/apps/web/lib/actions/send-invite-referral-email.ts
+++ b/apps/web/lib/actions/send-invite-referral-email.ts
@@ -3,7 +3,8 @@
import { sendEmail } from "@dub/email";
import ReferralInvite from "@dub/email/templates/referral-invite";
import * as z from "zod/v4";
-import { ratelimit } from "../upstash";
+import { assertRateLimit } from "../upstash/assert-rate-limit";
+import { RATELIMIT_POLICIES } from "../upstash/ratelimit-policies";
import { emailSchema } from "../zod/schemas/auth";
import { authActionClient } from "./safe-action";
@@ -19,18 +20,15 @@ export const sendInviteReferralEmail = authActionClient
const { workspace } = ctx;
const { email } = parsedInput;
- // Allow 5 emails / workspace / minute
- const { success: successWorkspace } = await ratelimit(5, "1 m").limit(
- `invite-referral-email:${workspace.id}`,
- );
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.inviteReferralEmailWorkspace,
+ identifier: workspace.id,
+ });
- // Allow 2 emails to a specific address / 2 hours (not one / hour to allow one quick retry)
- const { success: successEmail } = await ratelimit(2, "2 h").limit(
- `invite-referral-email:${email}`,
- );
-
- if (!successWorkspace || !successEmail)
- throw new Error("Failed to send: rate limit exceeded");
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.inviteReferralEmailTarget,
+ identifier: email,
+ });
try {
return await sendEmail({
diff --git a/apps/web/lib/api/utils.ts b/apps/web/lib/api/utils.ts
index b6d4d07fb9..e8caae6776 100644
--- a/apps/web/lib/api/utils.ts
+++ b/apps/web/lib/api/utils.ts
@@ -1,7 +1,8 @@
import { ipAddress } from "@vercel/functions";
import { getToken } from "next-auth/jwt";
import { NextRequest } from "next/server";
-import { ratelimit } from "../upstash";
+import { assertRateLimit } from "../upstash/assert-rate-limit";
+import { RATELIMIT_POLICIES } from "../upstash/ratelimit-policies";
import { DubApiError } from "./errors";
// TODO move into `lib/api/utils/**` as individual files
@@ -30,14 +31,9 @@ export const ratelimitOrThrow = async (
});
if (!session?.email) {
const ip = ipAddress(req);
- const { success } = await ratelimit().limit(
- `${identifier || "ratelimit"}:${ip}`,
- );
- if (!success) {
- throw new DubApiError({
- code: "rate_limit_exceeded",
- message: "Don't DDoS me pls 🥺",
- });
- }
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.anonymousIpRequest,
+ identifier: [identifier || "ratelimit", ip ?? ""],
+ });
}
};
diff --git a/apps/web/lib/upstash/ratelimit-policies.ts b/apps/web/lib/upstash/ratelimit-policies.ts
index b9bbee67da..66c157ebd3 100644
--- a/apps/web/lib/upstash/ratelimit-policies.ts
+++ b/apps/web/lib/upstash/ratelimit-policies.ts
@@ -275,4 +275,60 @@ export const RATELIMIT_POLICIES = {
window: "24 h",
keyPrefix: "rl:tremendous:verify-otp",
},
+
+ // Anonymous (unauthenticated) link creation by IP
+ anonymousLinkCreate: {
+ attempts: 10,
+ window: "1 d",
+ keyPrefix: "rl:links:create:anonymous",
+ message:
+ "Rate limited – you can only create up to 10 links per day without an account.",
+ },
+
+ // Shared by partner-profile + embed referrals social content stats
+ socialContentStats: {
+ attempts: 10,
+ window: "1 h",
+ keyPrefix: "rl:partner-profile:social-content-stats",
+ message: "You've been rate limited. Please try again later.",
+ },
+
+ inviteReferralEmailWorkspace: {
+ attempts: 5,
+ window: "1 m",
+ keyPrefix: "rl:invite-referral-email:workspace",
+ message: "Failed to send: rate limit exceeded",
+ },
+
+ // Keyed on the recipient so many workspaces can't spam the same address
+ inviteReferralEmailTarget: {
+ attempts: 2,
+ window: "2 h",
+ keyPrefix: "rl:invite-referral-email:target",
+ message: "Failed to send: rate limit exceeded",
+ },
+
+ // Keyed on step + user so each merge step has its own 24h budget
+ mergePartnerAccounts: {
+ attempts: 3,
+ window: "24 h",
+ keyPrefix: "rl:merge-partner-accounts",
+ message:
+ "You've reached the maximum number of attempts for the past 24 hours. Please wait and try again later.",
+ },
+
+ // Unauthenticated IP requests (metatags, qr, providers, etc.)
+ anonymousIpRequest: {
+ attempts: 10,
+ window: "10 s",
+ keyPrefix: "rl:anonymous",
+ message: "Don't DDoS me pls 🥺",
+ },
+
+ domainSearchAvailability: {
+ attempts: 1,
+ window: "5 s",
+ keyPrefix: "rl:domains:search-availability",
+ message: "Don't DDoS me pls 🥺",
+ },
} as const satisfies Record<string, RatelimitPolicy>;