The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Implement OTP rate limiting on the signup
Kiran K0d24e817b9a2
diff --git a/apps/web/lib/actions/create-user-account.ts b/apps/web/lib/actions/create-user-account.tsindex 8493f82c4b..38c1080aa9 100644--- a/apps/web/lib/actions/create-user-account.ts+++ b/apps/web/lib/actions/create-user-account.ts@@ -2,9 +2,9 @@import { ratelimit } from "@/lib/upstash";import { prisma } from "@dub/prisma";+import { waitUntil } from "@vercel/functions";import { flattenValidationErrors } from "next-safe-action";import { createId } from "../api/create-id";-import { getIP } from "../api/utils";import { hashPassword } from "../auth/password";import z from "../zod";import { signUpSchema } from "../zod/schemas/auth";@@ -15,6 +15,9 @@ const schema = signUpSchema.extend({code: z.string().min(6, "OTP must be 6 characters long."),});+const MAX_OTP_ATTEMPTS = 5; // Block after 5 failed attempts+const OTP_LOCKOUT_DURATION = "24 h"; // Block for 24 hours+// Sign up a new user using email and passwordexport const createUserAccountAction = actionClient.schema(schema, {@@ -25,26 +28,45 @@ export const createUserAccountAction = actionClient.action(async ({ parsedInput }) => {const { email, password, code } = parsedInput;- const { success } = await ratelimit(2, "1 m").limit(`signup:${getIP()}`);+ const signupAttemptKey = `signup:attempts:${email}`;++ const { remaining: attemptsRemaining } = await ratelimit(+ MAX_OTP_ATTEMPTS,+ OTP_LOCKOUT_DURATION,+ ).getRemaining(signupAttemptKey);- if (!success) {- throw new Error("Too many requests. Please try again later.");+ if (attemptsRemaining <= 0) {+ throw new Error("Too many failed attempts. You have to try again later.");}const verificationToken = await prisma.emailVerificationToken.findUnique({where: {identifier: email,token: code,- expires: {- gte: new Date(),- },},});if (!verificationToken) {+ await ratelimit(MAX_OTP_ATTEMPTS, OTP_LOCKOUT_DURATION).limit(+ signupAttemptKey,+ );+throw new Error("Invalid verification code entered.");}+ if (verificationToken.expires && verificationToken.expires < new Date()) {+ waitUntil(+ prisma.emailVerificationToken.delete({+ where: {+ identifier: email,+ token: code,+ },+ }),+ );++ throw new Error("The OTP has expired. Please request a new one.");+ }+await prisma.emailVerificationToken.delete({where: {identifier: email,