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.

Centralize auth rate limits into RATELIMIT_POLICIES with assertRateLimit util

Kiran Kce93b7fdf1ba
diff --git a/apps/web/app/(ee)/api/auth/saml/verify/route.tsx b/apps/web/app/(ee)/api/auth/saml/verify/route.tsx
index feb915cba6..e557f3f1ea 100644
--- a/apps/web/app/(ee)/api/auth/saml/verify/route.tsx
+++ b/apps/web/app/(ee)/api/auth/saml/verify/route.tsx
@@ -1,9 +1,9 @@
-import { shouldApplyRateLimit } from "@/lib/api/environment";
+import { DubApiError } from "@/lib/api/errors";
+import { getIP } from "@/lib/api/utils/get-ip";
import { jackson } from "@/lib/jackson";
import { prisma } from "@/lib/prisma";
-import { ratelimit } from "@/lib/upstash";
-import { LOCALHOST_IP } from "@dub/utils";
-import { ipAddress } from "@vercel/functions";
+import { assertRateLimit } from "@/lib/upstash";
+import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
import { NextResponse } from "next/server";
export async function POST(req: Request) {
@@ -18,16 +18,22 @@ export async function POST(req: Request) {
);
}
- if (shouldApplyRateLimit) {
- const ip = process.env.VERCEL === "1" ? ipAddress(req) : LOCALHOST_IP;
- const { success } = await ratelimit(10, "1 m").limit(`saml-verify:${ip}`);
-
- if (!success) {
+ try {
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.samlVerify,
+ identifier: await getIP(),
+ });
+ } catch (error) {
+ if (error instanceof DubApiError && error.code === "rate_limit_exceeded") {
return NextResponse.json(
- { error: "Too many requests. Please try again later." },
+ {
+ error: error.message,
+ },
{ status: 429 },
);
}
+
+ throw error;
}
const workspace = await prisma.project.findUnique({
diff --git a/apps/web/app/api/auth/reset-password/route.ts b/apps/web/app/api/auth/reset-password/route.ts
index fb10ca0ba1..643e5ede6d 100644
--- a/apps/web/app/api/auth/reset-password/route.ts
+++ b/apps/web/app/api/auth/reset-password/route.ts
@@ -1,7 +1,10 @@
import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
-import { parseRequestBody, ratelimitOrThrow } from "@/lib/api/utils";
+import { parseRequestBody } from "@/lib/api/utils";
+import { getIP } from "@/lib/api/utils/get-ip";
import { hashPassword, validatePassword } from "@/lib/auth/password";
import { prisma } from "@/lib/prisma";
+import { assertRateLimit } from "@/lib/upstash";
+import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
import { resetPasswordSchema } from "@/lib/zod/schemas/auth";
import { sendEmail } from "@dub/email";
import PasswordUpdated from "@dub/email/templates/password-updated";
@@ -11,7 +14,10 @@ import { NextRequest, NextResponse } from "next/server";
// POST /api/auth/reset-password - reset password using the reset token
export async function POST(req: NextRequest) {
try {
- await ratelimitOrThrow(req, "reset-password");
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.passwordReset,
+ identifier: await getIP(),
+ });
const { token, password } = resetPasswordSchema.parse(
await parseRequestBody(req),
diff --git a/apps/web/app/api/user/route.ts b/apps/web/app/api/user/route.ts
index b546ad0605..9f8e183f31 100644
--- a/apps/web/app/api/user/route.ts
+++ b/apps/web/app/api/user/route.ts
@@ -168,6 +168,7 @@ export const PATCH = withSession(async ({ req, session }) => {
email: session.user.email,
newEmail: email,
identifier: session.user.id,
+ userId: session.user.id,
hostName: emailChangeHost,
});
}
diff --git a/apps/web/lib/actions/check-account-exists.ts b/apps/web/lib/actions/check-account-exists.ts
index 1f3ace527d..ec2f468a24 100644
--- a/apps/web/lib/actions/check-account-exists.ts
+++ b/apps/web/lib/actions/check-account-exists.ts
@@ -2,9 +2,9 @@
import { getIP } from "@/lib/api/utils/get-ip";
import { prisma } from "@/lib/prisma";
-import { ratelimit } from "@/lib/upstash";
+import { assertRateLimit } from "@/lib/upstash";
+import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
import * as z from "zod/v4";
-import { shouldApplyRateLimit } from "../api/environment";
import { isSamlEnforcedForEmailDomain } from "../api/workspaces/is-saml-enforced-for-email-domain";
import { emailSchema } from "../zod/schemas/auth";
import { throwIfAuthenticated } from "./auth/throw-if-authenticated";
@@ -21,15 +21,10 @@ export const checkAccountExistsAction = actionClient
.action(async ({ parsedInput }) => {
const { email } = parsedInput;
- if (shouldApplyRateLimit) {
- const { success } = await ratelimit(8, "1 m").limit(
- `account-exists:${await getIP()}`,
- );
-
- if (!success) {
- throw new Error("Too many requests. Please try again later.");
- }
- }
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.accountExistsCheck,
+ identifier: await getIP(),
+ });
const [user, isSamlEnforced] = await Promise.all([
prisma.user.findUnique({
diff --git a/apps/web/lib/actions/create-user-account.ts b/apps/web/lib/actions/create-user-account.ts
index 709862364e..08bd494066 100644
--- a/apps/web/lib/actions/create-user-account.ts
+++ b/apps/web/lib/actions/create-user-account.ts
@@ -46,8 +46,10 @@ export const createUserAccountAction = actionClient
const verificationToken = await prisma.emailVerificationToken.findUnique({
where: {
- identifier: email,
- token: code,
+ identifier_token: {
+ identifier: email,
+ token: code,
+ },
},
});
diff --git a/apps/web/lib/actions/partners/update-partner-profile.ts b/apps/web/lib/actions/partners/update-partner-profile.ts
index 1029317953..7663bf1c9e 100644
--- a/apps/web/lib/actions/partners/update-partner-profile.ts
+++ b/apps/web/lib/actions/partners/update-partner-profile.ts
@@ -236,6 +236,7 @@ export const updatePartnerProfileAction = authPartnerActionClient
email: partner.email,
newEmail,
identifier: partner.id,
+ userId: user.id,
isPartnerProfile: true,
hostName: PARTNERS_DOMAIN,
});
diff --git a/apps/web/lib/actions/request-password-reset.ts b/apps/web/lib/actions/request-password-reset.ts
index 331a5446c9..8f5221ee57 100644
--- a/apps/web/lib/actions/request-password-reset.ts
+++ b/apps/web/lib/actions/request-password-reset.ts
@@ -1,7 +1,8 @@
"use server";
import { prisma } from "@/lib/prisma";
-import { ratelimit } from "@/lib/upstash";
+import { assertRateLimit } from "@/lib/upstash";
+import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
import { sendEmail } from "@dub/email";
import ResetPasswordLink from "@dub/email/templates/reset-password-link";
import { randomBytes } from "crypto";
@@ -21,13 +22,10 @@ export const requestPasswordResetAction = actionClient
.action(async ({ parsedInput }) => {
const { email } = parsedInput;
- const { success } = await ratelimit(2, "1 m").limit(
- `request-password-reset:${email.toLowerCase()}`,
- );
-
- if (!success) {
- throw new Error("Too many requests. Please try again later.");
- }
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.passwordResetRequest,
+ identifier: email.toLowerCase(),
+ });
const user = await prisma.user.findUnique({
where: {
diff --git a/apps/web/lib/actions/send-otp.ts b/apps/web/lib/actions/send-otp.ts
index 2dd3049a8a..47a00da2af 100644
--- a/apps/web/lib/actions/send-otp.ts
+++ b/apps/web/lib/actions/send-otp.ts
@@ -3,7 +3,8 @@
import { getIP } from "@/lib/api/utils/get-ip";
import { isEmailDomainBlocked } from "@/lib/email/is-email-domain-blocked";
import { prisma } from "@/lib/prisma";
-import { ratelimit } from "@/lib/upstash";
+import { assertRateLimit } from "@/lib/upstash";
+import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
import { sendEmail } from "@dub/email";
import VerifyEmail from "@dub/email/templates/verify-email";
import { flattenValidationErrors } from "next-safe-action";
@@ -30,13 +31,10 @@ export const sendOtpAction = actionClient
.action(async ({ parsedInput }) => {
const { email } = parsedInput;
- const { success } = await ratelimit(2, "1 m").limit(
- `send-otp:${email}:${await getIP()}`,
- );
-
- if (!success) {
- throw new Error("Too many requests. Please try again later.");
- }
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.signupOtpSend,
+ identifier: [email, await getIP()],
+ });
const isGenericEmailWithPlus = email.includes("+") && isGenericEmail(email);
const emailDomainBlocked = await isEmailDomainBlocked(email);
diff --git a/apps/web/lib/auth/options.ts b/apps/web/lib/auth/options.ts
index 6d6a6cf8fa..7d83c6dffb 100644
--- a/apps/web/lib/auth/options.ts
+++ b/apps/web/lib/auth/options.ts
@@ -3,7 +3,8 @@ import { jackson } from "@/lib/jackson";
import { prisma } from "@/lib/prisma";
import { isStored, storage } from "@/lib/storage";
import { UserProps } from "@/lib/types";
-import { ratelimit } from "@/lib/upstash";
+import { assertRateLimit } from "@/lib/upstash";
+import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
import { sendEmail } from "@dub/email";
import LoginLink from "@dub/email/templates/login-link";
import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
@@ -18,7 +19,7 @@ import EmailProvider from "next-auth/providers/email";
import GithubProvider from "next-auth/providers/github";
import GoogleProvider from "next-auth/providers/google";
import { createId } from "../api/create-id";
-import { isProduction, shouldApplyRateLimit } from "../api/environment";
+import { isProduction } from "../api/environment";
import { isSamlEnforcedForEmailDomain } from "../api/workspaces/is-saml-enforced-for-email-domain";
import { qstash } from "../cron";
import { completeProgramApplications } from "../partners/complete-program-applications";
@@ -95,7 +96,12 @@ const CustomPrismaAdapter = (p: PrismaClient) => {
export const authOptions: NextAuthOptions = {
providers: [
EmailProvider({
- sendVerificationRequest({ identifier, url }) {
+ async sendVerificationRequest({ identifier, url }) {
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.loginLinkSend,
+ identifier,
+ });
+
if (!isProduction) {
console.log(`Login link: ${url}`);
return;
@@ -266,15 +272,10 @@ export const authOptions: NextAuthOptions = {
throw new Error("no-credentials");
}
- if (shouldApplyRateLimit) {
- const { success } = await ratelimit(5, "1 m").limit(
- `login-attempts:${email}`,
- );
-
- if (!success) {
- throw new Error("too-many-login-attempts");
- }
- }
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.login,
+ identifier: email.trim().toLowerCase(),
+ });
// SSO enforcement check
const ssoEnforced = await isSamlEnforcedForEmailDomain(email);
diff --git a/apps/web/lib/auth/request-email-change.ts b/apps/web/lib/auth/request-email-change.ts
index cb34a443e1..f4354cc9a3 100644
--- a/apps/web/lib/auth/request-email-change.ts
+++ b/apps/web/lib/auth/request-email-change.ts
@@ -7,13 +7,15 @@ import { hashToken } from ".";
import { DubApiError } from "../api/errors";
import { isEmailDomainBlocked } from "../email/is-email-domain-blocked";
import { isGenericEmail } from "../is-generic-email";
-import { ratelimit, redis } from "../upstash";
+import { assertRateLimit, redis } from "../upstash";
+import { RATELIMIT_POLICIES } from "../upstash/ratelimit-policies";
// Send the OTP to confirm the email address change for existing users/partners
export const requestEmailChange = async ({
email,
newEmail,
identifier,
+ userId,
isPartnerProfile = false,
syncIdentity = false,
partnerId,
@@ -23,6 +25,7 @@ export const requestEmailChange = async ({
email: string;
newEmail: string;
identifier: string;
+ userId: string;
isPartnerProfile?: boolean; // If true, the email is being changed for a partner profile
syncIdentity?: boolean; // If true, update both user and partner email on confirm
partnerId?: string;
@@ -36,17 +39,15 @@ export const requestEmailChange = async ({
});
}
- const { success } = await ratelimit(3, "1 d").limit(
- `email-change-request:${identifier}`,
- );
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.emailChangeRequest,
+ identifier: userId,
+ });
- if (!success) {
- throw new DubApiError({
- code: "rate_limit_exceeded",
- message:
- "You've requested too many email change requests. Please try again later.",
- });
- }
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.emailChangeRequestTarget,
+ identifier: newEmail.toLowerCase(),
+ });
const isGenericEmailWithPlus = email.includes("+") && isGenericEmail(email);
const emailDomainBlocked = await isEmailDomainBlocked(newEmail);
diff --git a/apps/web/lib/partners/sync-partner-identity.ts b/apps/web/lib/partners/sync-partner-identity.ts
index 7c1942419a..4467f93440 100644
--- a/apps/web/lib/partners/sync-partner-identity.ts
+++ b/apps/web/lib/partners/sync-partner-identity.ts
@@ -171,6 +171,7 @@ export async function requestSyncedEmailChange({
email: currentEmail,
newEmail,
identifier: userId,
+ userId,
hostName,
syncIdentity: true,
partnerId,
diff --git a/apps/web/lib/upstash/assert-rate-limit.ts b/apps/web/lib/upstash/assert-rate-limit.ts
new file mode 100644
index 0000000000..925e4ae1de
--- /dev/null
+++ b/apps/web/lib/upstash/assert-rate-limit.ts
@@ -0,0 +1,85 @@
+import { pluralize } from "@dub/utils";
+import { shouldApplyRateLimit } from "../api/environment";
+import { DubApiError } from "../api/errors";
+import { ratelimit } from "./ratelimit";
+import { RatelimitPolicy } from "./ratelimit-policies";
+
+// Formats ms until reset as a human-friendly duration
+export const formatRetryAfter = (resetAt: number) => {
+ const seconds = Math.max(Math.ceil((resetAt - Date.now()) / 1000), 1);
+
+ if (seconds < 60) {
+ return `${seconds} ${pluralize("second", seconds)}`;
+ }
+
+ const minutes = Math.ceil(seconds / 60);
+
+ if (minutes < 60) {
+ return `${minutes} ${pluralize("minute", minutes)}`;
+ }
+
+ const hours = Math.ceil(minutes / 60);
+
+ return `${hours} ${pluralize("hour", hours)}`;
+};
+
+// Formats a ratelimit window as a human-friendly duration
+const formatWindow = (window: RatelimitPolicy["window"]) => {
+ const [count, unit] = window.split(" ");
+
+ const unitName =
+ {
+ ms: "millisecond",
+ s: "second",
+ m: "minute",
+ h: "hour",
+ d: "day",
+ }[unit] ?? unit;
+
+ return count === "1"
+ ? unitName
+ : `${count} ${pluralize(unitName, Number(count))}`;
+};
+
+// Enforces a rate limit policy for the given identifier, throwing a
+// rate_limit_exceeded DubApiError when the limit is exceeded
+export async function assertRateLimit({
+ policy,
+ identifier,
+}: {
+ policy: RatelimitPolicy;
+ identifier: string | string[]; // dynamic part(s) of the key, e.g. email or [email, ip]
+}) {
+ if (!shouldApplyRateLimit) {
+ return;
+ }
+
+ const key = [
+ policy.keyPrefix,
+ ...(Array.isArray(identifier) ? identifier : [identifier]),
+ ].join(":");
+
+ const { success, reset } = await ratelimit(
+ policy.attempts,
+ policy.window,
+ ).limit(key);
+
+ if (!success) {
+ const retryAfter = formatRetryAfter(reset);
+
+ const message =
+ typeof policy.message === "function"
+ ? policy.message({
+ retryAfter,
+ attempts: policy.attempts,
+ window: policy.window,
+ })
+ : policy.message ??
+ `You've reached the rate limit of ${policy.attempts} attempts per ${formatWindow(policy.window)}. Please try again in ${retryAfter}.`;
+
+ throw new DubApiError({
+ code: "rate_limit_exceeded",
+ message,
+ });
+ }
+}
diff --git a/apps/web/lib/upstash/index.ts b/apps/web/lib/upstash/index.ts
index 2898c8ab1a..6d93432e6f 100644
--- a/apps/web/lib/upstash/index.ts
+++ b/apps/web/lib/upstash/index.ts
@@ -1,3 +1,4 @@
+export * from "./assert-rate-limit";
export * from "./format-redis-link";
export * from "./ratelimit";
export * from "./record-metatags";
diff --git a/apps/web/lib/upstash/ratelimit-policies.ts b/apps/web/lib/upstash/ratelimit-policies.ts
index 458c034133..464dacc9b2 100644
--- a/apps/web/lib/upstash/ratelimit-policies.ts
+++ b/apps/web/lib/upstash/ratelimit-policies.ts
@@ -1,3 +1,20 @@
+import { ratelimit } from "./ratelimit";
+
+type RatelimitWindow = Parameters<typeof ratelimit>[1] & string;
+
+export type RatelimitPolicy = {
+ attempts: number;
+ window: RatelimitWindow;
+ keyPrefix: string;
+ message?:
+ | string
+ | ((ctx: {
+ retryAfter: string;
+ attempts: number;
+ window: string;
+ }) => string);
+};
+
export const RATELIMIT_POLICIES = {
programImageUpload: {
attempts: 10,
@@ -11,6 +28,59 @@ export const RATELIMIT_POLICIES = {
keyPrefix: "rl:message:attachment:upload",
},
- // TODO:
- // Centralize rate limiting policies
-} as const;
+ login: {
+ attempts: 5,
+ window: "1 m",
+ keyPrefix: "rl:auth:login",
+ message: "too-many-login-attempts", // exact error code matched by the sign-in page, must stay verbatim
+ },
+
+ loginLinkSend: {
+ attempts: 2,
+ window: "1 m",
+ keyPrefix: "rl:auth:login-link:send",
+ },
+
+ signupOtpSend: {
+ attempts: 2,
+ window: "1 m",
+ keyPrefix: "rl:auth:signup:otp:send",
+ },
+
+ accountExistsCheck: {
+ attempts: 8,
+ window: "1 m",
+ keyPrefix: "rl:auth:account-exists:check",
+ },
+
+ passwordResetRequest: {
+ attempts: 2,
+ window: "1 m",
+ keyPrefix: "rl:auth:password-reset:request",
+ },
+
+ passwordReset: {
+ attempts: 2,
+ window: "1 m",
+ keyPrefix: "rl:auth:password-reset:confirm",
+ },
+
+ emailChangeRequest: {
+ attempts: 3,
+ window: "24 h",
+ keyPrefix: "rl:auth:email-change",
+ },
+
+ // Keyed on the target email so many accounts can't spam the same address
+ emailChangeRequestTarget: {
+ attempts: 3,
+ window: "24 h",
+ keyPrefix: "rl:auth:email-change:target",
+ },
+
+ samlVerify: {
+ attempts: 10,
+ window: "1 m",
+ keyPrefix: "rl:auth:saml-verify",
+ },
+} as const satisfies Record<string, RatelimitPolicy>;
diff --git a/apps/web/ui/auth/login/login-form.tsx b/apps/web/ui/auth/login/login-form.tsx
index f1c18ec085..10df6954c0 100644
--- a/apps/web/ui/auth/login/login-form.tsx
+++ b/apps/web/ui/auth/login/login-form.tsx
@@ -37,6 +37,8 @@ export const errorCodes = {
"email-not-verified": "Please verify your email address.",
"require-saml-sso":
"Your organization requires authentication through your company's identity provider.",
+ EmailSignin:
+ "Failed to send login email. Please try again in a minute or contact support.",
Callback:
"We encountered an issue processing your request. Please try again or contact support if the problem persists.",
OAuthSignin: