Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(web): apply rate limits to email sign-in codes

Richie McIlroy0883a08b97ca
diff --git a/apps/mobile/src/auth/SignInPanel.test.tsx b/apps/mobile/src/auth/SignInPanel.test.tsx
index 54ddee082..365cb15f0 100644
--- a/apps/mobile/src/auth/SignInPanel.test.tsx
+++ b/apps/mobile/src/auth/SignInPanel.test.tsx
@@ -934,6 +934,72 @@ describe("SignInPanel", () => {
).toBe(true);
});
+ it("shows a retry-later message when code requests are throttled", async () => {
+ const { MobileApiError } = await import("@/api/mobile");
+ authFns.requestEmailCode.mockRejectedValueOnce(
+ new MobileApiError("Too Many Requests", 429, null),
+ );
+ const renderer = await renderPanel();
+ const [emailInput] = renderer.root.findAllByProps({
+ placeholder: "[email protected]",
+ });
+ const [emailButton] = renderer.root.findAllByProps({
+ accessibilityLabel: "Login with email",
+ });
+ if (!emailInput || !emailButton) {
+ throw new Error("Email sign in controls were not rendered");
+ }
+
+ await act(async () => {
+ emailInput.props.onChangeText("[email protected]");
+ });
+ await act(async () => {
+ await emailButton.props.onPress();
+ });
+
+ expect(getTextNodes(renderer.toJSON())).toContain(
+ "Too many codes requested. Try again in a few minutes.",
+ );
+ });
+
+ it("shows a retry-later message when code verification is throttled", async () => {
+ const { MobileApiError } = await import("@/api/mobile");
+ authFns.verifyEmailCode.mockRejectedValueOnce(
+ new MobileApiError("Too Many Requests", 429, null),
+ );
+ const renderer = await renderPanel();
+ const [emailInput] = renderer.root.findAllByProps({
+ placeholder: "[email protected]",
+ });
+ const [emailButton] = renderer.root.findAllByProps({
+ accessibilityLabel: "Login with email",
+ });
+ if (!emailInput || !emailButton) {
+ throw new Error("Email sign in controls were not rendered");
+ }
+
+ await act(async () => {
+ emailInput.props.onChangeText("[email protected]");
+ });
+ await act(async () => {
+ await emailButton.props.onPress();
+ });
+
+ const [codeInput] = renderer.root.findAllByProps({
+ textContentType: "oneTimeCode",
+ });
+ if (!codeInput) throw new Error("One-time code input was not rendered");
+
+ await act(async () => {
+ codeInput.props.onChangeText("123456");
+ await Promise.resolve();
+ });
+
+ expect(getTextNodes(renderer.toJSON())).toContain(
+ "Too many attempts. Try again in a few minutes.",
+ );
+ });
+
it("switches to a web-like verification code step after requesting email", async () => {
const renderer = await renderPanel();
const [emailInput] = renderer.root.findAllByProps({
diff --git a/apps/mobile/src/auth/SignInPanel.tsx b/apps/mobile/src/auth/SignInPanel.tsx
index 1a57ad267..3ec3beb48 100644
--- a/apps/mobile/src/auth/SignInPanel.tsx
+++ b/apps/mobile/src/auth/SignInPanel.tsx
@@ -33,6 +33,9 @@ const getEmailRequestErrorMessage = (error: unknown) => {
if (error.status === 403) {
return "This email cannot be used to sign in to Cap.";
}
+ if (error.status === 429) {
+ return "Too many codes requested. Try again in a few minutes.";
+ }
}
return error instanceof Error
? error.message
@@ -43,6 +46,9 @@ const getCodeVerificationErrorMessage = (error: unknown) => {
if (error instanceof MobileApiError) {
if (error.status === 400) return "Enter a valid email and 6-digit code.";
if (error.status === 403) return "That code is invalid or expired.";
+ if (error.status === 429) {
+ return "Too many attempts. Try again in a few minutes.";
+ }
}
return error instanceof Error ? error.message : "Unable to verify that code.";
};
diff --git a/apps/web/__tests__/unit/mobile-email-session.test.ts b/apps/web/__tests__/unit/mobile-email-session.test.ts
new file mode 100644
index 000000000..8d103a4fb
--- /dev/null
+++ b/apps/web/__tests__/unit/mobile-email-session.test.ts
@@ -0,0 +1,335 @@
+import type { DbClient } from "@cap/web-backend/src/Database";
+import type { HttpApi } from "@effect/platform";
+import type { SQL } from "drizzle-orm";
+import { MySqlDialect } from "drizzle-orm/mysql-core";
+import type { Context, Layer as EffectLayer } from "effect";
+import {
+ afterAll,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from "vitest";
+
+type TokenRow = { identifier: string; token: string; expires: Date };
+
+const mocks = vi.hoisted(() => ({
+ isRateLimited: vi.fn<(ruleId: string, opts?: unknown) => Promise<boolean>>(),
+ sendEmail: vi.fn<(input: { react: { code: string } }) => Promise<void>>(),
+ tokenRow: null as TokenRow | null,
+ selectBarrier: null as null | { size: number; waiting: (() => void)[] },
+ apiKeys: [] as string[],
+ dispose: async () => {},
+}));
+
+vi.mock("server-only", () => ({}));
+vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }));
+vi.mock("@/lib/rate-limit", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/lib/rate-limit")>()),
+ isRateLimited: mocks.isRateLimited,
+}));
+vi.mock("@cap/database/emails/config", () => ({ sendEmail: mocks.sendEmail }));
+vi.mock("@cap/database/emails/otp-email", () => ({
+ OTPEmail: (props: { code: string; email: string }) => props,
+}));
+vi.mock("@/lib/account-deletion-request", () => ({
+ createAccountDeletionRequest: vi.fn(),
+ createMobileContentReport: vi.fn(),
+ hasPendingAccountDeletion: vi.fn(async () => false),
+}));
+vi.mock("@cap/database/auth/auth-options", () => ({
+ authOptions: () => ({
+ adapter: {
+ createUser: vi.fn(async ({ email }: { email: string }) => ({
+ id: "user-1",
+ email,
+ })),
+ getUserByEmail: vi.fn(async (email: string) => ({
+ id: "user-1",
+ email,
+ })),
+ updateUser: vi.fn(async ({ id }: { id: string }) => ({ id })),
+ },
+ }),
+}));
+
+vi.mock("@/lib/server", async () => {
+ const { Database, Videos } = await import("@cap/web-backend");
+ const { HttpAuthMiddleware } = await import("@cap/web-domain");
+ const { HttpApiBuilder, HttpServer } = await import("@effect/platform");
+ const { Effect, Layer } = await import("effect");
+ const Db = await import("@cap/database/schema");
+
+ const matches = (condition: SQL, row: TokenRow) => {
+ const query = new MySqlDialect().sqlToQuery(condition);
+ const columns = [
+ ...query.sql.matchAll(
+ /`verification_tokens`\.`(identifier|token)`\s*=\s*\?/g,
+ ),
+ ].map((match) => match[1] as "identifier" | "token");
+ if (columns.length === 0) {
+ throw new Error(`Unexpected predicate: ${query.sql}`);
+ }
+ return columns.every((column, i) => row[column] === query.params[i]);
+ };
+
+ const waitAtBarrier = async () => {
+ const barrier = mocks.selectBarrier;
+ if (!barrier) return;
+ await new Promise<void>((resolve) => {
+ barrier.waiting.push(resolve);
+ if (barrier.waiting.length >= barrier.size) {
+ for (const release of barrier.waiting) release();
+ }
+ });
+ };
+
+ const client = {
+ select: () => ({
+ from: (table: unknown) => ({
+ where: (condition: SQL) => ({
+ limit: async () => {
+ if (table !== Db.verificationTokens) return [];
+ const row = mocks.tokenRow;
+ const result = row && matches(condition, row) ? [{ ...row }] : [];
+ await waitAtBarrier();
+ return result;
+ },
+ }),
+ }),
+ }),
+ insert: (table: unknown) => ({
+ values: async (value: TokenRow & { id?: string }) => {
+ if (table === Db.verificationTokens) {
+ mocks.tokenRow = {
+ identifier: value.identifier,
+ token: value.token,
+ expires: value.expires,
+ };
+ }
+ if (table === Db.authApiKeys && value.id) mocks.apiKeys.push(value.id);
+ },
+ }),
+ update: (table: unknown) => ({
+ set: (value: Partial<TokenRow>) => ({
+ where: async (condition: SQL) => {
+ const row = mocks.tokenRow;
+ if (
+ table === Db.verificationTokens &&
+ row &&
+ matches(condition, row)
+ ) {
+ mocks.tokenRow = { ...row, ...value };
+ }
+ },
+ }),
+ }),
+ delete: (table: unknown) => ({
+ where: async (condition: SQL) => {
+ await Promise.resolve();
+ if (table !== Db.verificationTokens) return [{ affectedRows: 0 }];
+ const row = mocks.tokenRow;
+ if (row && matches(condition, row)) {
+ mocks.tokenRow = null;
+ return [{ affectedRows: 1 }];
+ }
+ return [{ affectedRows: 0 }];
+ },
+ }),
+ };
+ const clientWithTransaction = {
+ ...client,
+ transaction: async (callback: (tx: typeof client) => Promise<unknown>) =>
+ callback(client),
+ };
+
+ const database = Layer.succeed(
+ Database,
+ Database.make({
+ use: (callback) =>
+ Effect.promise(() =>
+ callback(clientWithTransaction as unknown as DbClient),
+ ),
+ }),
+ );
+ const videos = Layer.succeed(
+ Videos,
+ {} as unknown as Context.Tag.Service<typeof Videos>,
+ );
+ const auth = Layer.succeed(HttpAuthMiddleware, Effect.die("unused"));
+
+ return {
+ apiToHandler: (
+ api: EffectLayer.Layer<
+ HttpApi.Api,
+ never,
+ | Context.Tag.Identifier<typeof Database>
+ | Context.Tag.Identifier<typeof Videos>
+ | Context.Tag.Identifier<typeof HttpAuthMiddleware>
+ >,
+ ) => {
+ const handler = api.pipe(
+ Layer.provideMerge(auth),
+ Layer.provideMerge(database),
+ Layer.provideMerge(videos),
+ Layer.merge(HttpServer.layerContext),
+ HttpApiBuilder.toWebHandler,
+ );
+ mocks.dispose = handler.dispose;
+ return handler.handler;
+ },
+ };
+});
+
+describe("mobile email sessions", () => {
+ let POST: typeof import("@/app/api/mobile/[...route]/route").POST;
+
+ beforeAll(async () => {
+ Object.assign(process.env, {
+ NEXT_PUBLIC_WEB_URL: "http://localhost",
+ WEB_URL: "http://localhost",
+ DATABASE_URL: "mysql://unused:[email protected]:3306/unused",
+ NEXTAUTH_SECRET: "synthetic-test-secret-that-is-long-enough",
+ NEXTAUTH_URL: "http://localhost",
+ CAP_AWS_BUCKET: "synthetic",
+ CAP_AWS_REGION: "us-east-1",
+ CAP_AWS_ACCESS_KEY: "synthetic",
+ CAP_AWS_SECRET_KEY: "synthetic",
+ RESEND_API_KEY: "synthetic",
+ NODE_ENV: "test",
+ });
+ ({ POST } = await import("@/app/api/mobile/[...route]/route"));
+ });
+
+ beforeEach(() => {
+ mocks.isRateLimited.mockReset().mockResolvedValue(false);
+ mocks.sendEmail.mockReset().mockResolvedValue(undefined);
+ mocks.tokenRow = null;
+ mocks.selectBarrier = null;
+ mocks.apiKeys = [];
+ });
+
+ afterAll(() => mocks.dispose());
+
+ const post = (path: string, body: unknown) =>
+ POST(
+ new Request(`http://localhost/api/mobile/session/email/${path}`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ );
+
+ const requestCode = async (email = "[email protected]") => {
+ const response = await post("request", { email });
+ expect(response.status).toBe(200);
+ const code = mocks.sendEmail.mock.calls.at(-1)?.[0].react.code;
+ if (!code) throw new Error("No code was sent");
+ return code;
+ };
+
+ const wrongCode = (code: string) => (code === "123456" ? "654321" : "123456");
+
+ it("sends a code and signs in with it", async () => {
+ const code = await requestCode(" [email protected] ");
+
+ const response = await post("verify", {
+ email: "[email protected]",
+ code,
+ });
+
+ expect(response.status).toBe(200);
+ expect(await response.json()).toMatchObject({
+ type: "api_key",
+ userId: "user-1",
+ });
+ expect(mocks.tokenRow).toBeNull();
+ expect(mocks.isRateLimited.mock.calls.map(([ruleId]) => ruleId)).toEqual([
+ "rl_auth_otp_send",
+ "rl_auth_otp_verify",
+ ]);
+ });
+
+ it("uses one bucket per normalized email", async () => {
+ await requestCode(" [email protected] ");
+ await requestCode("[email protected]");
+
+ const [first, second] = mocks.isRateLimited.mock.calls.map(
+ ([, opts]) => (opts as { key: string }).key,
+ );
+ expect(first).toMatch(/^email-code-send:[0-9a-f]{64}$/);
+ expect(second).toBe(first);
+ });
+
+ it("returns 429 without sending when code requests are limited", async () => {
+ mocks.isRateLimited.mockResolvedValue(true);
+
+ const response = await post("request", { email: "[email protected]" });
+
+ expect(response.status).toBe(429);
+ expect(mocks.sendEmail).not.toHaveBeenCalled();
+ expect(mocks.tokenRow).toBeNull();
+ });
+
+ it("returns 429 and keeps the code when verification is limited", async () => {
+ const code = await requestCode();
+ mocks.isRateLimited.mockResolvedValue(true);
+
+ const response = await post("verify", {
+ email: "[email protected]",
+ code,
+ });
+
+ expect(response.status).toBe(429);
+ expect(mocks.tokenRow).not.toBeNull();
+ expect(mocks.apiKeys).toEqual([]);
+ });
+
+ it("invalidates the code after a wrong attempt", async () => {
+ const code = await requestCode();
+
+ const wrong = await post("verify", {
+ email: "[email protected]",
+ code: wrongCode(code),
+ });
+ const retry = await post("verify", {
+ email: "[email protected]",
+ code,
+ });
+
+ expect(wrong.status).toBe(403);
+ expect(retry.status).toBe(403);
+ expect(mocks.apiKeys).toEqual([]);
+ });
+
+ it("rejects an expired code", async () => {
+ const code = await requestCode();
+ if (!mocks.tokenRow) throw new Error("No stored code");
+ mocks.tokenRow.expires = new Date(Date.now() - 1000);
+
+ const response = await post("verify", {
+ email: "[email protected]",
+ code,
+ });
+
+ expect(response.status).toBe(403);
+ expect(mocks.tokenRow).toBeNull();
+ });
+
+ it("lets only one of two concurrent verifications use a code", async () => {
+ const code = await requestCode();
+ mocks.selectBarrier = { size: 2, waiting: [] };
+
+ const responses = await Promise.all([
+ post("verify", { email: "[email protected]", code }),
+ post("verify", { email: "[email protected]", code }),
+ ]);
+
+ expect(responses.map((response) => response.status).sort()).toEqual([
+ 200, 403,
+ ]);
+ expect(mocks.apiKeys).toHaveLength(1);
+ });
+});
diff --git a/apps/web/__tests__/unit/nextauth-email-route.test.ts b/apps/web/__tests__/unit/nextauth-email-route.test.ts
new file mode 100644
index 000000000..5e747a1a2
--- /dev/null
+++ b/apps/web/__tests__/unit/nextauth-email-route.test.ts
@@ -0,0 +1,180 @@
+import { NextRequest } from "next/server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { GET, POST } from "@/app/api/auth/[...nextauth]/route";
+
+type RouteContext = { params: Promise<{ nextauth: string[] }> };
+
+const mocks = vi.hoisted(() => ({
+ isRateLimited: vi.fn<(ruleId: string, opts?: unknown) => Promise<boolean>>(),
+ nextAuth: vi.fn<(request: NextRequest) => Promise<Response>>(),
+}));
+
+const env = vi.hoisted(() => ({
+ WEB_URL: "https://cap.example",
+ NEXTAUTH_SECRET: "test-email-route-secret-with-sufficient-entropy",
+}));
+
+vi.mock("@cap/env", () => ({ serverEnv: () => env }));
+vi.mock("@cap/database/auth/auth-options", () => ({
+ authOptions: () => ({ providers: [] }),
+ decodeSessionToken: vi.fn(),
+}));
+vi.mock("@cap/database/auth/sso", () => ({ getWorkOS: vi.fn() }));
+vi.mock("next-auth", () => ({ default: mocks.nextAuth }));
+vi.mock("next-auth/jwt", () => ({ getToken: vi.fn(async () => null) }));
+vi.mock("@/lib/rate-limit", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/lib/rate-limit")>()),
+ isRateLimited: mocks.isRateLimited,
+}));
+
+function context(...nextauth: string[]): RouteContext {
+ return { params: Promise.resolve({ nextauth }) };
+}
+
+function emailSignIn(email: string, extra: Record<string, string> = {}) {
+ return new NextRequest(`${env.WEB_URL}/api/auth/signin/email`, {
+ method: "POST",
+ headers: { "content-type": "application/x-www-form-urlencoded" },
+ body: new URLSearchParams({
+ email,
+ csrfToken: "fixture-csrf-token",
+ callbackUrl: "/dashboard",
+ json: "true",
+ ...extra,
+ }),
+ });
+}
+
+function emailCallback(query: Record<string, string>) {
+ const url = new URL("/api/auth/callback/email", env.WEB_URL);
+ url.search = new URLSearchParams(query).toString();
+ return new NextRequest(url);
+}
+
+beforeEach(() => {
+ mocks.isRateLimited.mockReset().mockResolvedValue(false);
+ mocks.nextAuth.mockReset().mockImplementation(async (request) => {
+ const body = request.method === "POST" ? await request.text() : "";
+ return Response.json({ handledBy: "next-auth", body });
+ });
+});
+
+describe("email sign-in requests", () => {
+ it("passes an allowed request to NextAuth with its body intact", async () => {
+ const response = await POST(
+ emailSignIn("[email protected]"),
+ context("signin", "email"),
+ );
+
+ expect(mocks.nextAuth).toHaveBeenCalledTimes(1);
+ const body = (await response.json()) as { body: string };
+ expect(new URLSearchParams(body.body).get("email")).toBe(
+ );
+ expect(mocks.isRateLimited).toHaveBeenCalledTimes(1);
+ const [ruleId, opts] = mocks.isRateLimited.mock.calls[0] ?? [];
+ expect(ruleId).toBe("rl_auth_otp_send");
+ expect((opts as { key: string }).key).toMatch(
+ /^email-code-send:[0-9a-f]{64}$/,
+ );
+ });
+
+ it("uses one bucket per normalized email", async () => {
+ await POST(emailSignIn(" [email protected] "), context("signin", "email"));
+ await POST(emailSignIn("[email protected]"), context("signin", "email"));
+
+ const [first, second] = mocks.isRateLimited.mock.calls.map(
+ ([, opts]) => (opts as { key: string }).key,
+ );
+ expect(second).toBe(first);
+ });
+
+ it("returns the NextAuth email error without sending when limited", async () => {
+ mocks.isRateLimited.mockResolvedValue(true);
+
+ const response = await POST(
+ emailSignIn("[email protected]"),
+ context("signin", "email"),
+ );
+
+ expect(response.status).toBe(429);
+ expect(mocks.nextAuth).not.toHaveBeenCalled();
+ const { url } = (await response.json()) as { url: string };
+ expect(new URL(url).searchParams.get("error")).toBe("EmailSignin");
+ });
+
+ it("redirects non-JSON requests to the error page when limited", async () => {
+ mocks.isRateLimited.mockResolvedValue(true);
+
+ const response = await POST(
+ emailSignIn("[email protected]", { json: "false" }),
+ context("signin", "email"),
+ );
+
+ expect(response.status).toBe(302);
+ expect(mocks.nextAuth).not.toHaveBeenCalled();
+ const location = new URL(response.headers.get("location") ?? "");
+ expect(location.pathname).toBe("/api/auth/error");
+ expect(location.searchParams.get("error")).toBe("EmailSignin");
+ });
+});
+
+describe("email code verification", () => {
+ it("passes an allowed verification to NextAuth", async () => {
+ const response = await GET(
+ emailCallback({ email: "[email protected]", token: "123456" }),
+ context("callback", "email"),
+ );
+
+ expect(mocks.nextAuth).toHaveBeenCalledTimes(1);
+ expect(await response.json()).toMatchObject({ handledBy: "next-auth" });
+ expect(mocks.isRateLimited.mock.calls[0]?.[0]).toBe("rl_auth_otp_verify");
+ });
+
+ it("redirects to the verification error without checking the code when limited", async () => {
+ mocks.isRateLimited.mockResolvedValue(true);
+
+ const response = await GET(
+ emailCallback({ email: "[email protected]", token: "123456" }),
+ context("callback", "email"),
+ );
+
+ expect(response.status).toBe(302);
+ expect(mocks.nextAuth).not.toHaveBeenCalled();
+ const location = new URL(response.headers.get("location") ?? "");
+ expect(location.pathname).toBe("/api/auth/error");
+ expect(location.searchParams.get("error")).toBe("Verification");
+ });
+});
+
+describe("other auth routes", () => {
+ it.each([
+ ["GET", ["session"]],
+ ["GET", ["csrf"]],
+ ["GET", ["providers"]],
+ ["POST", ["signin", "google"]],
+ ["GET", ["callback", "google"]],
+ ["GET", ["signin", "email"]],
+ ["POST", ["signout"]],
+ ] as const)("leaves %s %j untouched", async (method, segments) => {
+ mocks.isRateLimited.mockResolvedValue(true);
+ const request = new NextRequest(
+ `${env.WEB_URL}/api/auth/${segments.join("/")}?email=person%40example.com&token=123456`,
+ {
+ method,
+ ...(method === "POST"
+ ? {
+ headers: { "content-type": "application/x-www-form-urlencoded" },
+ body: new URLSearchParams({ email: "[email protected]" }),
+ }
+ : {}),
+ },
+ );
+
+ const handler = method === "POST" ? POST : GET;
+ await handler(request, context(...segments));
+
+ expect(mocks.isRateLimited).not.toHaveBeenCalled();
+ expect(mocks.nextAuth).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/web/app/api/auth/[...nextauth]/route.ts b/apps/web/app/api/auth/[...nextauth]/route.ts
index 2d5c0d65a..6a3449ac9 100644
--- a/apps/web/app/api/auth/[...nextauth]/route.ts
+++ b/apps/web/app/api/auth/[...nextauth]/route.ts
@@ -13,6 +13,11 @@ import { type NextRequest, NextResponse } from "next/server";
import NextAuth from "next-auth";
import { getToken } from "next-auth/jwt";
import { getSafeNextPath } from "@/app/(org)/safe-next";
+import {
+ isEmailCodeSendLimited,
+ isEmailCodeVerifyLimited,
+ normalizeSignInEmail,
+} from "@/lib/email-code-rate-limit";
import { isRateLimited } from "@/lib/rate-limit";
export const dynamic = "force-dynamic";
@@ -56,6 +61,7 @@ async function readSignInBody(request: NextRequest) {
json: payload.json === "true",
callbackUrl:
typeof payload.callbackUrl === "string" ? payload.callbackUrl : null,
+ email: typeof payload.email === "string" ? payload.email : null,
};
}
if (contentType?.includes("application/x-www-form-urlencoded")) {
@@ -63,6 +69,7 @@ async function readSignInBody(request: NextRequest) {
return {
json: body.get("json") === "true",
callbackUrl: body.get("callbackUrl"),
+ email: body.get("email"),
};
}
} catch {
@@ -71,11 +78,50 @@ async function readSignInBody(request: NextRequest) {
return null;
}
+function authErrorUrl(error: string) {
+ const url = new URL("/api/auth/error", serverEnv().WEB_URL);
+ url.searchParams.set("error", error);
+ return url.toString();
+}
+
+async function emailCodeLimitResponse(
+ request: NextRequest,
+ nextauth: string[],
+) {
+ if (nextauth[1] !== "email") return null;
+ if (nextauth[0] === "signin" && request.method === "POST") {
+ const body = await readSignInBody(request);
+ const email = normalizeSignInEmail(body?.email);
+ if (!email || !(await isEmailCodeSendLimited(email, request.headers))) {
+ return null;
+ }
+ const url = authErrorUrl("EmailSignin");
+ return body?.json
+ ? NextResponse.json({ url }, { status: 429 })
+ : NextResponse.redirect(url, 302);
+ }
+ if (nextauth[0] === "callback") {
+ const query = request.nextUrl.searchParams;
+ const email = normalizeSignInEmail(query.get("email"));
+ if (
+ !email ||
+ !query.get("token") ||
+ !(await isEmailCodeVerifyLimited(email, request.headers))
+ ) {
+ return null;
+ }
+ return NextResponse.redirect(authErrorUrl("Verification"), 302);
+ }
+ return null;
+}
+
async function handler(
request: NextRequest,
context: { params: Promise<{ nextauth: string[] }> },
) {
const { nextauth } = await context.params;
+ const limitedResponse = await emailCodeLimitResponse(request, nextauth);
+ if (limitedResponse) return limitedResponse;
if (nextauth[1] !== "workos") {
return NextAuth(request, context, authOptions());
}
diff --git a/apps/web/app/api/mobile/[...route]/route.ts b/apps/web/app/api/mobile/[...route]/route.ts
index 6c0320d5f..3ebe46202 100644
--- a/apps/web/app/api/mobile/[...route]/route.ts
+++ b/apps/web/app/api/mobile/[...route]/route.ts
@@ -58,6 +58,10 @@ import {
hasPendingAccountDeletion,
} from "@/lib/account-deletion-request";
import { queueDesktopSegmentsFinalization } from "@/lib/desktop-segments-finalization";
+import {
+ isEmailCodeSendLimited,
+ isEmailCodeVerifyLimited,
+} from "@/lib/email-code-rate-limit";
import {
resolveMobileRequestOrigin,
resolveMobileWebResourceUrl,
@@ -472,11 +476,16 @@ const createMobileApiKey = Effect.fn("Mobile.createMobileApiKey")(function* (
const requestEmailSession = Effect.fn("Mobile.requestEmailSession")(function* (
rawEmail: string,
+ headers: Headers,
) {
const email = normalizeEmail(rawEmail);
yield* ensureEmailSignInAllowed(email);
yield* ensureAccountDeletionNotPending({ email });
+ if (yield* Effect.promise(() => isEmailCodeSendLimited(email, headers))) {
+ return yield* Effect.fail(new Mobile.MobileTooManyRequests());
+ }
+
const code = crypto.randomInt(100000, 1000000).toString();
const token = hashEmailCode(code);
const expires = new Date(Date.now() + emailCodeTtlMs);
@@ -513,10 +522,13 @@ const requestEmailSession = Effect.fn("Mobile.requestEmailSession")(function* (
return { success: true as const };
});
-const verifyEmailSession = Effect.fn("Mobile.verifyEmailSession")(function* ({
- email: rawEmail,
- code: rawCode,
-}: (typeof Mobile.MobileEmailSessionVerifyInput)["Type"]) {
+const verifyEmailSession = Effect.fn("Mobile.verifyEmailSession")(function* (
+ {
+ email: rawEmail,
+ code: rawCode,
+ }: (typeof Mobile.MobileEmailSessionVerifyInput)["Type"],
+ headers: Headers,
+) {
const email = normalizeEmail(rawEmail);
const code = rawCode.trim();
@@ -527,6 +539,10 @@ const verifyEmailSession = Effect.fn("Mobile.verifyEmailSession")(function* ({
yield* ensureEmailSignInAllowed(email);
yield* ensureAccountDeletionNotPending({ email });
+ if (yield* Effect.promise(() => isEmailCodeVerifyLimited(email, headers))) {
+ return yield* Effect.fail(new Mobile.MobileTooManyRequests());
+ }
+
const database = yield* Database;
const token = hashEmailCode(code);
const identifier = getMobileEmailVerificationIdentifier(email);
@@ -539,32 +555,21 @@ const verifyEmailSession = Effect.fn("Mobile.verifyEmailSession")(function* ({
if (!verificationToken) return "missing" as const;
- if (verificationToken.expires.valueOf() < Date.now()) {
- await db
- .delete(Db.verificationTokens)
- .where(eq(Db.verificationTokens.identifier, identifier));
- return "expired" as const;
- }
-
- if (verificationToken.token !== token) {
- await db
- .delete(Db.verificationTokens)
- .where(eq(Db.verificationTokens.identifier, identifier));
- return "invalid" as const;
- }
-
- const result = await db
+ const claim = await db
.delete(Db.verificationTokens)
.where(
and(
- eq(Db.verificationTokens.identifier, identifier),
- eq(Db.verificationTokens.token, token),
+ eq(Db.verificationTokens.identifier, verificationToken.identifier),
+ eq(Db.verificationTokens.token, verificationToken.token),
),
);
- return getAffectedRows(result) === 1
- ? ("verified" as const)
- : ("used" as const);
+ if (getAffectedRows(claim) !== 1) return "used" as const;
+ if (verificationToken.expires.valueOf() < Date.now()) {
+ return "expired" as const;
+ }
+ if (verificationToken.token !== token) return "invalid" as const;
+ return "verified" as const;
});
if (verificationStatus !== "verified") {
@@ -2829,11 +2834,15 @@ const ApiLive = HttpApiBuilder.api(Mobile.MobileApiContract).pipe(
}),
),
)
- .handle("requestEmailSession", ({ payload }) =>
- withMappedErrors(requestEmailSession(payload.email)),
+ .handle("requestEmailSession", ({ payload, request }) =>
+ withMappedErrors(
+ requestEmailSession(payload.email, toHeaders(request.headers)),
+ ),
)
- .handle("verifyEmailSession", ({ payload }) =>
- withMappedErrors(verifyEmailSession(payload)),
+ .handle("verifyEmailSession", ({ payload, request }) =>
+ withMappedErrors(
+ verifyEmailSession(payload, toHeaders(request.headers)),
+ ),
)
.handle("revokeSession", ({ headers }) =>
withMappedErrors(
diff --git a/apps/web/lib/email-code-rate-limit.ts b/apps/web/lib/email-code-rate-limit.ts
new file mode 100644
index 000000000..95cb0e7e3
--- /dev/null
+++ b/apps/web/lib/email-code-rate-limit.ts
@@ -0,0 +1,32 @@
+import crypto from "node:crypto";
+import { isRateLimited, RATE_LIMIT_IDS } from "@/lib/rate-limit";
+
+export function normalizeSignInEmail(value: unknown) {
+ if (typeof value !== "string") return null;
+ const trimmed = value.trim();
+ if (trimmed.split("@").length !== 2 || trimmed.includes('"')) return null;
+ const [local, domain] = trimmed.toLowerCase().split("@");
+ const host = domain?.split(",")[0];
+ if (!local || !host || !host.includes(".")) return null;
+ return `${local}@${host}`;
+}
+
+// Verification rows are looked up under MySQL's accent-insensitive default
+// collation, so accented spellings of an address share one bucket.
+const emailCodeRateLimitKey = (scope: string, email: string) =>
+ `${scope}:${crypto
+ .createHash("sha256")
+ .update(email.normalize("NFKD").replace(/\p{M}/gu, ""))
+ .digest("hex")}`;
+
+export const isEmailCodeSendLimited = (email: string, headers?: Headers) =>
+ isRateLimited(RATE_LIMIT_IDS.AUTH_OTP_SEND, {
+ key: emailCodeRateLimitKey("email-code-send", email),
+ headers,
+ });
+
+export const isEmailCodeVerifyLimited = (email: string, headers?: Headers) =>
+ isRateLimited(RATE_LIMIT_IDS.AUTH_OTP_VERIFY, {
+ key: emailCodeRateLimitKey("email-code-verify", email),
+ headers,
+ });
diff --git a/packages/web-domain/src/Mobile.ts b/packages/web-domain/src/Mobile.ts
index 5c4dc4cde..ac922556a 100644
--- a/packages/web-domain/src/Mobile.ts
+++ b/packages/web-domain/src/Mobile.ts
@@ -3,6 +3,7 @@ import {
HttpApiEndpoint,
HttpApiError,
HttpApiGroup,
+ HttpApiSchema,
OpenApi,
} from "@effect/platform";
import { Schema } from "effect";
@@ -152,6 +153,13 @@ export const MobileEmailSessionVerifyInput = Schema.Struct({
code: Schema.String,
});
+export class MobileTooManyRequests extends HttpApiSchema.EmptyError<MobileTooManyRequests>()(
+ {
+ tag: "TooManyRequests",
+ status: 429,
+ },
+) {}
+
export const MobileAccountDeletionInput = Schema.Struct({
confirmation: Schema.Literal("DELETE"),
});
@@ -547,7 +555,8 @@ export class MobileHttpApi extends HttpApiGroup.make("mobile")
.addError(HttpApiError.InternalServerError)
.addError(HttpApiError.BadRequest)
.addError(HttpApiError.Forbidden)
- .addError(HttpApiError.NotFound),
+ .addError(HttpApiError.NotFound)
+ .addError(MobileTooManyRequests),
)
.add(
HttpApiEndpoint.post("verifyEmailSession", "/session/email/verify")
@@ -556,7 +565,8 @@ export class MobileHttpApi extends HttpApiGroup.make("mobile")
.addError(HttpApiError.InternalServerError)
.addError(HttpApiError.BadRequest)
.addError(HttpApiError.Forbidden)
- .addError(HttpApiError.NotFound),
+ .addError(HttpApiError.NotFound)
+ .addError(MobileTooManyRequests),
)
.add(
HttpApiEndpoint.post("revokeSession", "/session/revoke")