-
Notifications
You must be signed in to change notification settings - Fork 1.6k
fix(web): rate-limit and shorten lifetime of login OTP codes #1924
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
richiemcilroy
wants to merge
2
commits into
main
Choose a base branch
from
security/otp-bruteforce-protection
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+144
−2
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,8 +1,70 @@ | ||
| import { authOptions } from "@cap/database/auth/auth-options"; | ||
| import { type NextRequest, NextResponse } from "next/server"; | ||
| import NextAuth from "next-auth"; | ||
| import { isRateLimited, RATE_LIMIT_IDS } from "@/lib/rate-limit"; | ||
|
|
||
| export const dynamic = "force-dynamic"; | ||
|
|
||
| const handler = NextAuth(authOptions()); | ||
|
|
||
| export { handler as GET, handler as POST }; | ||
| /** | ||
| * Per-email rate limit for the email OTP flow. The NextAuth handler itself has | ||
| * no rate limiting and the proxy middleware excludes `/api`, so without this an | ||
| * attacker can brute-force the 6-digit code (`/callback/email`) or mailbomb an | ||
| * address (`/signin/email`). | ||
| * | ||
| * Keying: when the target email is present the bucket is per-email, so guesses | ||
| * and sends are capped per victim regardless of source IP. This is a deliberate | ||
| * trade-off favouring mailbomb / brute-force protection; the short 15-minute | ||
| * code lifetime bounds any victim-targeted bucket exhaustion to that window. If | ||
| * the email is absent we fall back to the firewall's default per-IP bucket | ||
| * rather than lumping all email-less requests into one shared key. | ||
| * | ||
| * Requires the `rl_auth_otp_verify` / `rl_auth_otp_send` rules to be configured | ||
| * in the Vercel Firewall; absent that, this fails open (see `isRateLimited`). | ||
| */ | ||
| async function otpRateLimited(req: NextRequest): Promise<boolean> { | ||
| const path = req.nextUrl.pathname; | ||
| const isVerify = path.endsWith("/callback/email"); | ||
| const isSend = path.endsWith("/signin/email"); | ||
| if (!isVerify && !isSend) return false; | ||
|
|
||
| let email = req.nextUrl.searchParams.get("email"); | ||
| if (!email && isSend) { | ||
| // `signIn("email", …)` posts the address as form data. | ||
| try { | ||
| const form = await req.clone().formData(); | ||
| const value = form.get("email"); | ||
| email = typeof value === "string" ? value : null; | ||
| } catch { | ||
| email = null; | ||
| } | ||
| } | ||
|
|
||
| const ruleId = isVerify | ||
| ? RATE_LIMIT_IDS.AUTH_OTP_VERIFY | ||
| : RATE_LIMIT_IDS.AUTH_OTP_SEND; | ||
|
|
||
| const normalizedEmail = email?.trim().toLowerCase(); | ||
|
|
||
| return isRateLimited(ruleId, { | ||
| key: normalizedEmail ? `${ruleId}:${normalizedEmail}` : undefined, | ||
| headers: req.headers, | ||
| }); | ||
| } | ||
|
|
||
| async function guarded( | ||
| req: NextRequest, | ||
| ctx: RouteContext<"/api/auth/[...nextauth]">, | ||
| ) { | ||
| if (await otpRateLimited(req)) { | ||
| return NextResponse.json( | ||
| { error: "Too many attempts. Please try again later." }, | ||
| { status: 429 }, | ||
| ); | ||
| } | ||
|
|
||
| return handler(req, ctx); | ||
| } | ||
|
|
||
| export { guarded as GET, guarded as POST }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| import { checkRateLimit } from "@vercel/firewall"; | ||
| import { headers as nextHeaders } from "next/headers"; | ||
|
|
||
| /** | ||
| * Best-effort per-key rate limiting backed by the Vercel Firewall. | ||
| * | ||
| * IMPORTANT: each `ruleId` passed here must also be configured as a Rate Limit | ||
| * rule in the Vercel Firewall dashboard (Firewall → Rate Limiting) with a | ||
| * `@vercel/firewall` rule condition whose ID matches `ruleId`, plus the desired | ||
| * window / limit / action. An ID that has no matching dashboard rule fails | ||
| * OPEN (`checkRateLimit` returns `{ rateLimited: false, error: "not-found" }`), | ||
| * so this helper never breaks self-hosted deploys that lack the firewall — but | ||
| * it also provides no protection until the rule exists. | ||
| * | ||
| * Mirrors the existing pattern in `actions/collections/password.ts` and | ||
| * `actions/send-download-link.ts`: | ||
| * - only enforced in production, | ||
| * - best-effort (any error → not limited) so a firewall/IP-header outage can | ||
| * never take down the underlying feature. | ||
| * | ||
| * @param ruleId Stable rule id, also configured in the Vercel Firewall. | ||
| * @param opts.key Optional bucket key (e.g. per-email / per-user). Defaults to | ||
| * the caller IP (the firewall's default behaviour). | ||
| * @param opts.headers Optional request headers (required inside Hono handlers | ||
| * where `next/headers` is unavailable; defaults to the App | ||
| * Router request headers). | ||
| * @returns `true` when the request should be rejected. | ||
| */ | ||
| export async function isRateLimited( | ||
| ruleId: string, | ||
| opts?: { key?: string; headers?: Headers }, | ||
| ): Promise<boolean> { | ||
| if (process.env.NODE_ENV !== "production") return false; | ||
|
|
||
| try { | ||
| const headersList = opts?.headers ?? (await nextHeaders()); | ||
| const request = new Request("https://cap.so/api/rate-limit", { | ||
| method: "POST", | ||
| headers: headersList, | ||
| }); | ||
|
|
||
| const { rateLimited } = await checkRateLimit(ruleId, { | ||
| request, | ||
| ...(opts?.key ? { rateLimitKey: opts.key } : {}), | ||
| }); | ||
|
|
||
| return rateLimited; | ||
| } catch (error) { | ||
| console.warn(`Rate limit check failed for "${ruleId}":`, error); | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Canonical Vercel Firewall rate-limit rule ids introduced by the security | ||
| * hardening pass. Each MUST be created in the Vercel Firewall dashboard for the | ||
| * corresponding protection to take effect (see `isRateLimited`). | ||
| */ | ||
| export const RATE_LIMIT_IDS = { | ||
| /** Email OTP verification attempts (brute-force guard). Suggested: 10 / 10m per key (email). */ | ||
| AUTH_OTP_VERIFY: "rl_auth_otp_verify", | ||
| /** Email OTP / magic-link send (mailbomb + token-reseed guard). Suggested: 5 / 10m per key (email). */ | ||
| AUTH_OTP_SEND: "rl_auth_otp_send", | ||
| /** Unauthed Loom download/convert (ffmpeg + memory DoS). Suggested: 10 / 1m per IP. */ | ||
| LOOM_DOWNLOAD: "rl_loom_download", | ||
| /** Unauthed transcript translation (Groq cost). Suggested: 10 / 1m per IP. */ | ||
| TRANSLATE_TRANSCRIPT: "rl_translate_transcript", | ||
| /** Anonymous support-chat messages (Groq + Supermemory cost). Suggested: 20 / 1m per IP. */ | ||
| MESSENGER_MESSAGE: "rl_messenger_message", | ||
| /** Unauthed analytics view tracking (Tinybird ingest + notifications). Suggested: 60 / 1m per IP. */ | ||
| ANALYTICS_TRACK: "rl_analytics_track", | ||
| /** Unauthed guest checkout (Stripe object/cost abuse). Suggested: 10 / 10m per IP. */ | ||
| GUEST_CHECKOUT: "rl_guest_checkout", | ||
| /** Unauthed desktop log → Discord forwarding (spam). Suggested: 10 / 1m per IP. */ | ||
| DESKTOP_LOGS: "rl_desktop_logs", | ||
| } as const; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.