feat: add auth email rate limit - #220

Merged
KMKoushik merged 4 commits into
mainfrom
codex/implement-rate-limit-on-signup/signin-forms
Sep 9, 2025
Merged

feat: add auth email rate limit#220
KMKoushik merged 4 commits into
mainfrom
codex/implement-rate-limit-on-signup/signin-forms

Conversation

@KMKoushik

@KMKoushikKMKoushik commented Sep 9, 2025

Copy link
Copy Markdown
Member

Summary

  • add Redis-backed rate limiting for auth email sign-in requests
  • add AUTH_EMAIL_RATE_LIMIT env var and document in examples

Testing

  • pnpm format
  • pnpm lint(fails: ESLint found too many warnings)
  • npx eslint src/app/api/auth/[...nextauth]/route.ts
  • pnpm build(fails: Invalid environment variables)

https://chatgpt.com/codex/tasks/task_e_68bfda4f4da4832994ca3aec44f385fc

Summary by CodeRabbit

  • New Features
    • Per-IP rate limiting for email sign-in: repeated attempts from the same IP may receive a “Too Many Requests” (429) response to curb abuse; inactive by default unless configured.
  • Chores
    • Environment samples and server runtime config updated to add AUTH_EMAIL_RATE_LIMIT (default 0) for straightforward setup and enabling of the rate limit.

@vercel

vercelBot commented Sep 9, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
unsend-marketingReadyReadyPreviewCommentSep 9, 2025 1:08pm

@coderabbitai

coderabbitaiBot commented Sep 9, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Adds AUTH_EMAIL_RATE_LIMIT to .env.example and .env.selfhost.example and to the server env schema and runtime mapping in apps/web/src/env.js. Replaces the blanket POST export in apps/web/src/app/api/auth/[...nextauth]/route.ts with a new export async function POST(req, ctx) that enforces Redis-backed per-IP rate limiting for POST /signin/email by incrementing auth-rl:<ip> with a 60s TTL and returning 429 when the configured limit is exceeded; non-rate-limited requests delegate to the existing NextAuth handler. GET remains exported as the original handler.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 59ced7a and 98dce11.

📒 Files selected for processing (1)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Cloudflare Pages

Pre-merge checks (2 passed, 1 warning)

❌ Failed checks (1 warning)
Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%.You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check nameStatusExplanation
Title Check✅ PassedThe title “feat: add auth email rate limit” concisely and accurately summarizes the primary change of the pull request, namely introducing rate limiting for authentication email sign-in, without extraneous detail or unrelated context.
Description Check✅ PassedThe description outlines the key enhancements—adding Redis-backed rate limiting and the new AUTH_EMAIL_RATE_LIMIT environment variable—and includes relevant testing steps, making it clearly related to the changeset.
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/implement-rate-limit-on-signup/signin-forms

Comment @coderabbitai help to get the list of available commands and usage tips.

@cloudflare-workers-and-pages

cloudflare-workers-and-pagesBot commented Sep 9, 2025

Copy link
Copy Markdown

Deploying usesend with Cloudflare Pages Cloudflare Pages

Latest commit:98dce11
Status: ✅ Deploy successful!
Preview URL:https://a7f0d9f7.usesend.pages.dev
Branch Preview URL:https://codex-implement-rate-limit-o.usesend.pages.dev

View logs

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (4)
.env.selfhost.example (1)

37-37: Alphabetize keys to satisfy dotenv-linter (and keep examples consistent).

Place AUTH_EMAIL_RATE_LIMIT before DOCKER_OUTPUT (and next to API_RATE_LIMIT).

Apply:

-DOCKER_OUTPUT=1-API_RATE_LIMIT=1-AUTH_EMAIL_RATE_LIMIT=5+API_RATE_LIMIT=1+AUTH_EMAIL_RATE_LIMIT=5+DOCKER_OUTPUT=1
apps/web/src/app/api/auth/[...nextauth]/route.ts (3)

21-26: Atomic TTL set (optional): use EXPIRE NX in a pipeline.

Your pattern is fine; using EXPIRE with NX ensures TTL is attached only on first creation without relying on count === 1.

- const count = await redis.incr(key);- if (count === 1) await redis.expire(key, ttl);+ const [[, count]] = await redis+ .multi()+ .incr(key)+ // Redis >=7 supports EXPIRE key seconds NX+ .expire(key, ttl, "NX")+ .exec();

27-29: Include rate-limit headers and a Retry-After hint.

Improves client/backoff behavior and observability.

- return new Response("Too many requests", { status: 429 });+ const retryAfter = "60";+ return new Response(+ JSON.stringify({ error: "Too many requests" }),+ {+ status: 429,+ headers: {+ "Content-Type": "application/json",+ "Retry-After": retryAfter,+ "X-RateLimit-Limit": String(env.AUTH_EMAIL_RATE_LIMIT),+ "X-RateLimit-Remaining": "0",+ "X-RateLimit-Reset": retryAfter,+ },+ },+ );

30-32: Log with consistent shape and include IP for failures.

Add ip to error context for parity with the warn path.

- logger.error({ err: error }, "Auth email rate limit failed");+ logger.error({ err: error, ip: (req.headers.get("x-forwarded-for") ?? req.headers.get("x-real-ip") ?? "").split(",")[0]?.trim() }, "Auth email rate limit failed");
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7cf4610 and bd5bde8.

📒 Files selected for processing (4)
  • .env.example (1 hunks)
  • .env.selfhost.example (1 hunks)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts (1 hunks)
  • apps/web/src/env.js (2 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
.env*

📄 CodeRabbit inference engine (AGENTS.md)

Environment configuration files must live at the repository root and be named .env*

Files:

  • .env.selfhost.example
  • .env.example
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/env.js
  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use 2-space indentation in TypeScript code (enforced by Prettier)
Use semicolons in TypeScript code (enforced by Prettier)
Do not use dynamic imports

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code with Prettier 3 via pnpm format for TypeScript and Markdown files

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

In apps/web, use the / alias for src imports (e.g., import { x } from "/utils/x")

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
🧬 Code graph analysis (1)
apps/web/src/app/api/auth/[...nextauth]/route.ts (3)
apps/web/src/env.js (2)
  • env (5-130)
  • env (5-130)
apps/web/src/server/redis.ts (1)
  • getRedis (6-13)
apps/web/src/server/logger/log.ts (1)
  • logger (31-63)
🪛 dotenv-linter (3.3.0)
.env.selfhost.example

[warning] 37-37: [UnorderedKey] The AUTH_EMAIL_RATE_LIMIT key should go before the DOCKER_OUTPUT key

(UnorderedKey)

🔇 Additional comments (3)
.env.example (1)

23-23: LGTM: new variable documented.

AUTH_EMAIL_RATE_LIMIT is added and grouped with API_RATE_LIMIT; matches env.js schema.

apps/web/src/env.js (1)

102-102: Runtime mapping present.

AUTH_EMAIL_RATE_LIMIT is wired into runtimeEnv correctly.

apps/web/src/app/api/auth/[...nextauth]/route.ts (1)

35-36: LGTM: delegate to NextAuth when not rate-limited.

Flow is preserved for all other requests.

Comment on lines 1 to +6
import NextAuth from "next-auth";

import { authOptions } from "~/server/auth";
import { env } from "~/env";
import { getRedis } from "~/server/redis";
import { logger } from "~/server/logger/log";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Force Node.js runtime to avoid Edge/ioredis incompatibility.

This route uses ioredis via getRedis(); ensure it never runs on the Edge runtime.

 import NextAuth from "next-auth";
import { authOptions } from "~/server/auth";
import { env } from "~/env";
import { getRedis } from "~/server/redis";
import { logger } from "~/server/logger/log";
++// ioredis requires Node.js runtime+export const runtime = "nodejs";
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
importNextAuthfrom"next-auth";
import{authOptions}from"~/server/auth";
import{env}from"~/env";
import{getRedis}from"~/server/redis";
import{logger}from"~/server/logger/log";
importNextAuthfrom"next-auth";
import{authOptions}from"~/server/auth";
import{env}from"~/env";
import{getRedis}from"~/server/redis";
import{logger}from"~/server/logger/log";
// ioredis requires Node.js runtime
exportconstruntime="nodejs";
🤖 Prompt for AI Agents
In apps/web/src/app/api/auth/[...nextauth]/route.ts around lines 1-6, this
Next.js route uses ioredis via getRedis and must not run on the Edge runtime;
add an exported runtime declaration at the top of the file that sets the runtime
to Node (e.g., export a constant named runtime with value 'node') so the route
always runs on the Node.js runtime, then verify imports remain unchanged and
redeploy.

Comment threadapps/web/src/app/api/auth/[...nextauth]/route.ts Outdated
Comment threadapps/web/src/env.js
Comment on lines +47 to +50
AUTH_EMAIL_RATE_LIMIT: z
.string()
.default("0")
.transform((str) => parseInt(str, 10)),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Harden numeric validation for AUTH_EMAIL_RATE_LIMIT (avoid NaN, catch bad input).

Current z.string().transform(parseInt) allows non-numeric strings to become NaN, silently disabling rate limiting. Coerce to a non-negative int.

- AUTH_EMAIL_RATE_LIMIT: z- .string()- .default("0")- .transform((str) => parseInt(str, 10)),+ AUTH_EMAIL_RATE_LIMIT: z.coerce.number().int().nonnegative().default(0),
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
AUTH_EMAIL_RATE_LIMIT: z
.string()
.default("0")
.transform((str)=>parseInt(str,10)),
AUTH_EMAIL_RATE_LIMIT: z.coerce.number().int().nonnegative().default(0),
🤖 Prompt for AI Agents
In apps/web/src/env.js around lines 47 to 50, the current AUTH_EMAIL_RATE_LIMIT
uses z.string().transform(parseInt) which can produce NaN for bad input; change
it to parse and validate as a non-negative integer: preprocess the raw string
into a Number (e.g., with Number(str) or parseInt but guard against NaN), then
validate with z.number().int().nonnegative().default(0) (or add a refine to
reject NaN) so invalid values fail validation or fall back to 0 instead of
becoming NaN.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (1)
apps/web/src/app/api/auth/[...nextauth]/route.ts (1)

1-6: Force Node runtime to avoid ioredis/Edge crash.

This route uses ioredis; without forcing Node.js runtime it can deploy to Edge and fail at runtime.

 import NextAuth from "next-auth";
import { authOptions } from "~/server/auth";
import { env } from "~/env";
import { getRedis } from "~/server/redis";
import { logger } from "~/server/logger/log";
++// ioredis requires Node.js runtime+export const runtime = "nodejs";

Run to confirm the runtime export exists:

#!/bin/bash
rg -nP 'export\\s+const\\s+runtime\\s*=\\s*"nodejs"' apps/web/src/app/api/auth/\.\.\.nextauth/route\.ts
🧹 Nitpick comments (2)
apps/web/src/app/api/auth/[...nextauth]/route.ts (2)

57-59: Handle trailing slash on pathname.

Support both /signin/email and /signin/email/.

- const url = new URL(req.url);- if (url.pathname.endsWith("/signin/email")) {+ const url = new URL(req.url);+ const pathname = url.pathname.replace(/\/+$/, "");+ if (pathname.endsWith("/signin/email")) {

72-80: Include Retry-After and no-store headers on 429.

Improves client/backoff behavior and caching semantics.

- return Response.json(+ return Response.json(
{
error: {
code: "RATE_LIMITED",
message: "Too many requests",
},
},
- { status: 429 }+ {+ status: 429,+ headers: {+ "Retry-After": String(ttl),+ "Cache-Control": "no-store",+ },+ }
);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8879ab7 and 59ced7a.

📒 Files selected for processing (1)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use 2-space indentation in TypeScript code (enforced by Prettier)
Use semicolons in TypeScript code (enforced by Prettier)
Do not use dynamic imports

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code with Prettier 3 via pnpm format for TypeScript and Markdown files

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

In apps/web, use the / alias for src imports (e.g., import { x } from "/utils/x")

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
🧬 Code graph analysis (1)
apps/web/src/app/api/auth/[...nextauth]/route.ts (3)
apps/web/src/env.js (2)
  • env (5-130)
  • env (5-130)
apps/web/src/server/logger/log.ts (1)
  • logger (31-63)
apps/web/src/server/redis.ts (1)
  • getRedis (6-13)
🔇 Additional comments (2)
apps/web/src/app/api/auth/[...nextauth]/route.ts (2)

10-10: GET re-export: LGTM.

Re-exporting GET to NextAuth handler is correct.


56-86: Overall POST flow: solid.

Gated on env flag, scoped to email sign-in, uses atomic INCR+EXPIRE, logs and gracefully degrades on RL errors. Nice.

Comment on lines +12 to +50
function getClientIp(req: Request): string | null {
const h = req.headers;
const direct =
h.get("x-forwarded-for") ??
h.get("x-real-ip") ??
h.get("cf-connecting-ip") ??
h.get("x-client-ip") ??
h.get("true-client-ip") ??
h.get("fastly-client-ip") ??
h.get("x-cluster-client-ip") ??
null;

let ip = direct?.split(",")[0]?.trim() ?? "";

if (!ip) {
const fwd = h.get("forwarded");
if (fwd) {
const first = fwd.split(",")[0];
const match = first?.match(/for=([^;]+)/i);
if (match && match[1]) {
const raw = match[1].trim().replace(/^"|"$/g, "");
if (raw.startsWith("[")) {
const end = raw.indexOf("]");
ip = end !== -1 ? raw.slice(1, end) : raw;
} else {
const parts = raw.split(":");
if (parts.length > 0 && parts[0]) {
ip =
parts.length === 2 && /^\d+(?:\.\d+){3}$/.test(parts[0])
? parts[0]
: raw;
}
}
}
}
}

return ip || null;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Harden client IP parsing and validate before use.

Unvalidated header values can include ports/garbage and create unbounded Redis keys. Normalize and validate as IP; skip RL if invalid.

 function getClientIp(req: Request): string | null {
const h = req.headers;
@@
- let ip = direct?.split(",")[0]?.trim() ?? "";+ let ip = direct?.split(",")[0]?.trim() ?? "";+ // Strip IPv4 port if present in XFF: "1.2.3.4:5678" -> "1.2.3.4"+ const colon = ip.lastIndexOf(":");+ if (ip && colon > -1 && ip.includes(".")) ip = ip.slice(0, colon);
@@
- return ip || null;+ // Validate; treat non-IP as missing+ // (isIP returns 0 for invalid, 4 for IPv4, 6 for IPv6)+ return ip && isIP(ip) !== 0 ? ip : null;
}

Add import (top of file):

import{isIP}from"node:net";
🤖 Prompt for AI Agents
In apps/web/src/app/api/auth/[...nextauth]/route.ts around lines 12 to 50, the
client IP parsing accepts unvalidated header values (including ports/garbage)
which can produce unbounded Redis keys; import isIP from node:net and after
extracting the candidate IP normalize it (strip surrounding quotes, remove IPv6
brackets, remove appended port if present), then validate it with
isIP(candidate) and only return the IP when isIP(...) > 0; otherwise return null
so downstream logic (rate limiting) is skipped for invalid values.

Comment on lines +66 to +67
const key = `auth-rl:${ip}`;
const ttl = 60;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Hash the key to prevent header-driven key explosion and key injection.

Using raw header text as part of the key allows unbounded cardinality and odd bytes. Hashing stabilizes size and characters.

- const key = `auth-rl:${ip}`;+ const key = `auth-rl:${createHash("sha256").update(ip).digest("hex")}`;

Add import (top of file):

import{createHash}from"node:crypto";
🤖 Prompt for AI Agents
In apps/web/src/app/api/auth/[...nextauth]/route.ts around lines 66 to 67, the
rate-limit key is built from the raw IP/header which can lead to unbounded
cardinality and strange bytes; replace that with a stable hashed value: add an
import for createHash from node:crypto at the top of the file, compute a
deterministic hex (or base64) hash of the ip/header before composing the key,
and use the hashed value in place of the raw ip when building the `auth-rl:` key
so the key size/charset is fixed and safe.

@KMKoushik
KMKoushik merged commit 9723c78 into mainSep 9, 2025
4 checks passed
@KMKoushik
KMKoushik deleted the codex/implement-rate-limit-on-signup/signin-forms branch September 9, 2025 13:09
@coderabbitaicoderabbitaiBot mentioned this pull request Dec 19, 2025
10 tasks
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@KMKoushik
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

feat: add auth email rate limit - #220

Merged
KMKoushik merged 4 commits into
mainfrom
codex/implement-rate-limit-on-signup/signin-forms
Sep 9, 2025
Merged

feat: add auth email rate limit#220
KMKoushik merged 4 commits into
mainfrom
codex/implement-rate-limit-on-signup/signin-forms

Conversation

@KMKoushik

@KMKoushikKMKoushik commented Sep 9, 2025

Copy link
Copy Markdown
Member

Summary

  • add Redis-backed rate limiting for auth email sign-in requests
  • add AUTH_EMAIL_RATE_LIMIT env var and document in examples

Testing

  • pnpm format
  • pnpm lint(fails: ESLint found too many warnings)
  • npx eslint src/app/api/auth/[...nextauth]/route.ts
  • pnpm build(fails: Invalid environment variables)

https://chatgpt.com/codex/tasks/task_e_68bfda4f4da4832994ca3aec44f385fc

Summary by CodeRabbit

  • New Features
    • Per-IP rate limiting for email sign-in: repeated attempts from the same IP may receive a “Too Many Requests” (429) response to curb abuse; inactive by default unless configured.
  • Chores
    • Environment samples and server runtime config updated to add AUTH_EMAIL_RATE_LIMIT (default 0) for straightforward setup and enabling of the rate limit.

@vercel

vercelBot commented Sep 9, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
unsend-marketingReadyReadyPreviewCommentSep 9, 2025 1:08pm

@coderabbitai

coderabbitaiBot commented Sep 9, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Adds AUTH_EMAIL_RATE_LIMIT to .env.example and .env.selfhost.example and to the server env schema and runtime mapping in apps/web/src/env.js. Replaces the blanket POST export in apps/web/src/app/api/auth/[...nextauth]/route.ts with a new export async function POST(req, ctx) that enforces Redis-backed per-IP rate limiting for POST /signin/email by incrementing auth-rl:<ip> with a 60s TTL and returning 429 when the configured limit is exceeded; non-rate-limited requests delegate to the existing NextAuth handler. GET remains exported as the original handler.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 59ced7a and 98dce11.

📒 Files selected for processing (1)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Cloudflare Pages

Pre-merge checks (2 passed, 1 warning)

❌ Failed checks (1 warning)
Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%.You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check nameStatusExplanation
Title Check✅ PassedThe title “feat: add auth email rate limit” concisely and accurately summarizes the primary change of the pull request, namely introducing rate limiting for authentication email sign-in, without extraneous detail or unrelated context.
Description Check✅ PassedThe description outlines the key enhancements—adding Redis-backed rate limiting and the new AUTH_EMAIL_RATE_LIMIT environment variable—and includes relevant testing steps, making it clearly related to the changeset.
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/implement-rate-limit-on-signup/signin-forms

Comment @coderabbitai help to get the list of available commands and usage tips.

@cloudflare-workers-and-pages

cloudflare-workers-and-pagesBot commented Sep 9, 2025

Copy link
Copy Markdown

Deploying usesend with Cloudflare Pages Cloudflare Pages

Latest commit:98dce11
Status: ✅ Deploy successful!
Preview URL:https://a7f0d9f7.usesend.pages.dev
Branch Preview URL:https://codex-implement-rate-limit-o.usesend.pages.dev

View logs

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (4)
.env.selfhost.example (1)

37-37: Alphabetize keys to satisfy dotenv-linter (and keep examples consistent).

Place AUTH_EMAIL_RATE_LIMIT before DOCKER_OUTPUT (and next to API_RATE_LIMIT).

Apply:

-DOCKER_OUTPUT=1-API_RATE_LIMIT=1-AUTH_EMAIL_RATE_LIMIT=5+API_RATE_LIMIT=1+AUTH_EMAIL_RATE_LIMIT=5+DOCKER_OUTPUT=1
apps/web/src/app/api/auth/[...nextauth]/route.ts (3)

21-26: Atomic TTL set (optional): use EXPIRE NX in a pipeline.

Your pattern is fine; using EXPIRE with NX ensures TTL is attached only on first creation without relying on count === 1.

- const count = await redis.incr(key);- if (count === 1) await redis.expire(key, ttl);+ const [[, count]] = await redis+ .multi()+ .incr(key)+ // Redis >=7 supports EXPIRE key seconds NX+ .expire(key, ttl, "NX")+ .exec();

27-29: Include rate-limit headers and a Retry-After hint.

Improves client/backoff behavior and observability.

- return new Response("Too many requests", { status: 429 });+ const retryAfter = "60";+ return new Response(+ JSON.stringify({ error: "Too many requests" }),+ {+ status: 429,+ headers: {+ "Content-Type": "application/json",+ "Retry-After": retryAfter,+ "X-RateLimit-Limit": String(env.AUTH_EMAIL_RATE_LIMIT),+ "X-RateLimit-Remaining": "0",+ "X-RateLimit-Reset": retryAfter,+ },+ },+ );

30-32: Log with consistent shape and include IP for failures.

Add ip to error context for parity with the warn path.

- logger.error({ err: error }, "Auth email rate limit failed");+ logger.error({ err: error, ip: (req.headers.get("x-forwarded-for") ?? req.headers.get("x-real-ip") ?? "").split(",")[0]?.trim() }, "Auth email rate limit failed");
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7cf4610 and bd5bde8.

📒 Files selected for processing (4)
  • .env.example (1 hunks)
  • .env.selfhost.example (1 hunks)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts (1 hunks)
  • apps/web/src/env.js (2 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
.env*

📄 CodeRabbit inference engine (AGENTS.md)

Environment configuration files must live at the repository root and be named .env*

Files:

  • .env.selfhost.example
  • .env.example
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/env.js
  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use 2-space indentation in TypeScript code (enforced by Prettier)
Use semicolons in TypeScript code (enforced by Prettier)
Do not use dynamic imports

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code with Prettier 3 via pnpm format for TypeScript and Markdown files

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

In apps/web, use the / alias for src imports (e.g., import { x } from "/utils/x")

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
🧬 Code graph analysis (1)
apps/web/src/app/api/auth/[...nextauth]/route.ts (3)
apps/web/src/env.js (2)
  • env (5-130)
  • env (5-130)
apps/web/src/server/redis.ts (1)
  • getRedis (6-13)
apps/web/src/server/logger/log.ts (1)
  • logger (31-63)
🪛 dotenv-linter (3.3.0)
.env.selfhost.example

[warning] 37-37: [UnorderedKey] The AUTH_EMAIL_RATE_LIMIT key should go before the DOCKER_OUTPUT key

(UnorderedKey)

🔇 Additional comments (3)
.env.example (1)

23-23: LGTM: new variable documented.

AUTH_EMAIL_RATE_LIMIT is added and grouped with API_RATE_LIMIT; matches env.js schema.

apps/web/src/env.js (1)

102-102: Runtime mapping present.

AUTH_EMAIL_RATE_LIMIT is wired into runtimeEnv correctly.

apps/web/src/app/api/auth/[...nextauth]/route.ts (1)

35-36: LGTM: delegate to NextAuth when not rate-limited.

Flow is preserved for all other requests.

Comment on lines 1 to +6
import NextAuth from "next-auth";

import { authOptions } from "~/server/auth";
import { env } from "~/env";
import { getRedis } from "~/server/redis";
import { logger } from "~/server/logger/log";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Force Node.js runtime to avoid Edge/ioredis incompatibility.

This route uses ioredis via getRedis(); ensure it never runs on the Edge runtime.

 import NextAuth from "next-auth";
import { authOptions } from "~/server/auth";
import { env } from "~/env";
import { getRedis } from "~/server/redis";
import { logger } from "~/server/logger/log";
++// ioredis requires Node.js runtime+export const runtime = "nodejs";
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
importNextAuthfrom"next-auth";
import{authOptions}from"~/server/auth";
import{env}from"~/env";
import{getRedis}from"~/server/redis";
import{logger}from"~/server/logger/log";
importNextAuthfrom"next-auth";
import{authOptions}from"~/server/auth";
import{env}from"~/env";
import{getRedis}from"~/server/redis";
import{logger}from"~/server/logger/log";
// ioredis requires Node.js runtime
exportconstruntime="nodejs";
🤖 Prompt for AI Agents
In apps/web/src/app/api/auth/[...nextauth]/route.ts around lines 1-6, this
Next.js route uses ioredis via getRedis and must not run on the Edge runtime;
add an exported runtime declaration at the top of the file that sets the runtime
to Node (e.g., export a constant named runtime with value 'node') so the route
always runs on the Node.js runtime, then verify imports remain unchanged and
redeploy.

Comment threadapps/web/src/app/api/auth/[...nextauth]/route.ts Outdated
Comment threadapps/web/src/env.js
Comment on lines +47 to +50
AUTH_EMAIL_RATE_LIMIT: z
.string()
.default("0")
.transform((str) => parseInt(str, 10)),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Harden numeric validation for AUTH_EMAIL_RATE_LIMIT (avoid NaN, catch bad input).

Current z.string().transform(parseInt) allows non-numeric strings to become NaN, silently disabling rate limiting. Coerce to a non-negative int.

- AUTH_EMAIL_RATE_LIMIT: z- .string()- .default("0")- .transform((str) => parseInt(str, 10)),+ AUTH_EMAIL_RATE_LIMIT: z.coerce.number().int().nonnegative().default(0),
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
AUTH_EMAIL_RATE_LIMIT: z
.string()
.default("0")
.transform((str)=>parseInt(str,10)),
AUTH_EMAIL_RATE_LIMIT: z.coerce.number().int().nonnegative().default(0),
🤖 Prompt for AI Agents
In apps/web/src/env.js around lines 47 to 50, the current AUTH_EMAIL_RATE_LIMIT
uses z.string().transform(parseInt) which can produce NaN for bad input; change
it to parse and validate as a non-negative integer: preprocess the raw string
into a Number (e.g., with Number(str) or parseInt but guard against NaN), then
validate with z.number().int().nonnegative().default(0) (or add a refine to
reject NaN) so invalid values fail validation or fall back to 0 instead of
becoming NaN.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (1)
apps/web/src/app/api/auth/[...nextauth]/route.ts (1)

1-6: Force Node runtime to avoid ioredis/Edge crash.

This route uses ioredis; without forcing Node.js runtime it can deploy to Edge and fail at runtime.

 import NextAuth from "next-auth";
import { authOptions } from "~/server/auth";
import { env } from "~/env";
import { getRedis } from "~/server/redis";
import { logger } from "~/server/logger/log";
++// ioredis requires Node.js runtime+export const runtime = "nodejs";

Run to confirm the runtime export exists:

#!/bin/bash
rg -nP 'export\\s+const\\s+runtime\\s*=\\s*"nodejs"' apps/web/src/app/api/auth/\.\.\.nextauth/route\.ts
🧹 Nitpick comments (2)
apps/web/src/app/api/auth/[...nextauth]/route.ts (2)

57-59: Handle trailing slash on pathname.

Support both /signin/email and /signin/email/.

- const url = new URL(req.url);- if (url.pathname.endsWith("/signin/email")) {+ const url = new URL(req.url);+ const pathname = url.pathname.replace(/\/+$/, "");+ if (pathname.endsWith("/signin/email")) {

72-80: Include Retry-After and no-store headers on 429.

Improves client/backoff behavior and caching semantics.

- return Response.json(+ return Response.json(
{
error: {
code: "RATE_LIMITED",
message: "Too many requests",
},
},
- { status: 429 }+ {+ status: 429,+ headers: {+ "Retry-After": String(ttl),+ "Cache-Control": "no-store",+ },+ }
);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8879ab7 and 59ced7a.

📒 Files selected for processing (1)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use 2-space indentation in TypeScript code (enforced by Prettier)
Use semicolons in TypeScript code (enforced by Prettier)
Do not use dynamic imports

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code with Prettier 3 via pnpm format for TypeScript and Markdown files

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

In apps/web, use the / alias for src imports (e.g., import { x } from "/utils/x")

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
🧬 Code graph analysis (1)
apps/web/src/app/api/auth/[...nextauth]/route.ts (3)
apps/web/src/env.js (2)
  • env (5-130)
  • env (5-130)
apps/web/src/server/logger/log.ts (1)
  • logger (31-63)
apps/web/src/server/redis.ts (1)
  • getRedis (6-13)
🔇 Additional comments (2)
apps/web/src/app/api/auth/[...nextauth]/route.ts (2)

10-10: GET re-export: LGTM.

Re-exporting GET to NextAuth handler is correct.


56-86: Overall POST flow: solid.

Gated on env flag, scoped to email sign-in, uses atomic INCR+EXPIRE, logs and gracefully degrades on RL errors. Nice.

Comment on lines +12 to +50
function getClientIp(req: Request): string | null {
const h = req.headers;
const direct =
h.get("x-forwarded-for") ??
h.get("x-real-ip") ??
h.get("cf-connecting-ip") ??
h.get("x-client-ip") ??
h.get("true-client-ip") ??
h.get("fastly-client-ip") ??
h.get("x-cluster-client-ip") ??
null;

let ip = direct?.split(",")[0]?.trim() ?? "";

if (!ip) {
const fwd = h.get("forwarded");
if (fwd) {
const first = fwd.split(",")[0];
const match = first?.match(/for=([^;]+)/i);
if (match && match[1]) {
const raw = match[1].trim().replace(/^"|"$/g, "");
if (raw.startsWith("[")) {
const end = raw.indexOf("]");
ip = end !== -1 ? raw.slice(1, end) : raw;
} else {
const parts = raw.split(":");
if (parts.length > 0 && parts[0]) {
ip =
parts.length === 2 && /^\d+(?:\.\d+){3}$/.test(parts[0])
? parts[0]
: raw;
}
}
}
}
}

return ip || null;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Harden client IP parsing and validate before use.

Unvalidated header values can include ports/garbage and create unbounded Redis keys. Normalize and validate as IP; skip RL if invalid.

 function getClientIp(req: Request): string | null {
const h = req.headers;
@@
- let ip = direct?.split(",")[0]?.trim() ?? "";+ let ip = direct?.split(",")[0]?.trim() ?? "";+ // Strip IPv4 port if present in XFF: "1.2.3.4:5678" -> "1.2.3.4"+ const colon = ip.lastIndexOf(":");+ if (ip && colon > -1 && ip.includes(".")) ip = ip.slice(0, colon);
@@
- return ip || null;+ // Validate; treat non-IP as missing+ // (isIP returns 0 for invalid, 4 for IPv4, 6 for IPv6)+ return ip && isIP(ip) !== 0 ? ip : null;
}

Add import (top of file):

import{isIP}from"node:net";
🤖 Prompt for AI Agents
In apps/web/src/app/api/auth/[...nextauth]/route.ts around lines 12 to 50, the
client IP parsing accepts unvalidated header values (including ports/garbage)
which can produce unbounded Redis keys; import isIP from node:net and after
extracting the candidate IP normalize it (strip surrounding quotes, remove IPv6
brackets, remove appended port if present), then validate it with
isIP(candidate) and only return the IP when isIP(...) > 0; otherwise return null
so downstream logic (rate limiting) is skipped for invalid values.

Comment on lines +66 to +67
const key = `auth-rl:${ip}`;
const ttl = 60;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Hash the key to prevent header-driven key explosion and key injection.

Using raw header text as part of the key allows unbounded cardinality and odd bytes. Hashing stabilizes size and characters.

- const key = `auth-rl:${ip}`;+ const key = `auth-rl:${createHash("sha256").update(ip).digest("hex")}`;

Add import (top of file):

import{createHash}from"node:crypto";
🤖 Prompt for AI Agents
In apps/web/src/app/api/auth/[...nextauth]/route.ts around lines 66 to 67, the
rate-limit key is built from the raw IP/header which can lead to unbounded
cardinality and strange bytes; replace that with a stable hashed value: add an
import for createHash from node:crypto at the top of the file, compute a
deterministic hex (or base64) hash of the ip/header before composing the key,
and use the hashed value in place of the raw ip when building the `auth-rl:` key
so the key size/charset is fixed and safe.

@KMKoushik
KMKoushik merged commit 9723c78 into mainSep 9, 2025
4 checks passed
@KMKoushik
KMKoushik deleted the codex/implement-rate-limit-on-signup/signin-forms branch September 9, 2025 13:09
@coderabbitaicoderabbitaiBot mentioned this pull request Dec 19, 2025
10 tasks
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@KMKoushik
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat: add auth email rate limit - #220

Merged
KMKoushik merged 4 commits into
mainfrom
codex/implement-rate-limit-on-signup/signin-forms
Sep 9, 2025
Merged

feat: add auth email rate limit#220
KMKoushik merged 4 commits into
mainfrom
codex/implement-rate-limit-on-signup/signin-forms

Conversation

@KMKoushik

@KMKoushikKMKoushik commented Sep 9, 2025

Copy link
Copy Markdown
Member

Summary

  • add Redis-backed rate limiting for auth email sign-in requests
  • add AUTH_EMAIL_RATE_LIMIT env var and document in examples

Testing

  • pnpm format
  • pnpm lint(fails: ESLint found too many warnings)
  • npx eslint src/app/api/auth/[...nextauth]/route.ts
  • pnpm build(fails: Invalid environment variables)

https://chatgpt.com/codex/tasks/task_e_68bfda4f4da4832994ca3aec44f385fc

Summary by CodeRabbit

  • New Features
    • Per-IP rate limiting for email sign-in: repeated attempts from the same IP may receive a “Too Many Requests” (429) response to curb abuse; inactive by default unless configured.
  • Chores
    • Environment samples and server runtime config updated to add AUTH_EMAIL_RATE_LIMIT (default 0) for straightforward setup and enabling of the rate limit.

@vercel

vercelBot commented Sep 9, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
unsend-marketingReadyReadyPreviewCommentSep 9, 2025 1:08pm

@coderabbitai

coderabbitaiBot commented Sep 9, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Adds AUTH_EMAIL_RATE_LIMIT to .env.example and .env.selfhost.example and to the server env schema and runtime mapping in apps/web/src/env.js. Replaces the blanket POST export in apps/web/src/app/api/auth/[...nextauth]/route.ts with a new export async function POST(req, ctx) that enforces Redis-backed per-IP rate limiting for POST /signin/email by incrementing auth-rl:<ip> with a 60s TTL and returning 429 when the configured limit is exceeded; non-rate-limited requests delegate to the existing NextAuth handler. GET remains exported as the original handler.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 59ced7a and 98dce11.

📒 Files selected for processing (1)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Cloudflare Pages

Pre-merge checks (2 passed, 1 warning)

❌ Failed checks (1 warning)
Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%.You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check nameStatusExplanation
Title Check✅ PassedThe title “feat: add auth email rate limit” concisely and accurately summarizes the primary change of the pull request, namely introducing rate limiting for authentication email sign-in, without extraneous detail or unrelated context.
Description Check✅ PassedThe description outlines the key enhancements—adding Redis-backed rate limiting and the new AUTH_EMAIL_RATE_LIMIT environment variable—and includes relevant testing steps, making it clearly related to the changeset.
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/implement-rate-limit-on-signup/signin-forms

Comment @coderabbitai help to get the list of available commands and usage tips.

@cloudflare-workers-and-pages

cloudflare-workers-and-pagesBot commented Sep 9, 2025

Copy link
Copy Markdown

Deploying usesend with Cloudflare Pages Cloudflare Pages

Latest commit:98dce11
Status: ✅ Deploy successful!
Preview URL:https://a7f0d9f7.usesend.pages.dev
Branch Preview URL:https://codex-implement-rate-limit-o.usesend.pages.dev

View logs

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (4)
.env.selfhost.example (1)

37-37: Alphabetize keys to satisfy dotenv-linter (and keep examples consistent).

Place AUTH_EMAIL_RATE_LIMIT before DOCKER_OUTPUT (and next to API_RATE_LIMIT).

Apply:

-DOCKER_OUTPUT=1-API_RATE_LIMIT=1-AUTH_EMAIL_RATE_LIMIT=5+API_RATE_LIMIT=1+AUTH_EMAIL_RATE_LIMIT=5+DOCKER_OUTPUT=1
apps/web/src/app/api/auth/[...nextauth]/route.ts (3)

21-26: Atomic TTL set (optional): use EXPIRE NX in a pipeline.

Your pattern is fine; using EXPIRE with NX ensures TTL is attached only on first creation without relying on count === 1.

- const count = await redis.incr(key);- if (count === 1) await redis.expire(key, ttl);+ const [[, count]] = await redis+ .multi()+ .incr(key)+ // Redis >=7 supports EXPIRE key seconds NX+ .expire(key, ttl, "NX")+ .exec();

27-29: Include rate-limit headers and a Retry-After hint.

Improves client/backoff behavior and observability.

- return new Response("Too many requests", { status: 429 });+ const retryAfter = "60";+ return new Response(+ JSON.stringify({ error: "Too many requests" }),+ {+ status: 429,+ headers: {+ "Content-Type": "application/json",+ "Retry-After": retryAfter,+ "X-RateLimit-Limit": String(env.AUTH_EMAIL_RATE_LIMIT),+ "X-RateLimit-Remaining": "0",+ "X-RateLimit-Reset": retryAfter,+ },+ },+ );

30-32: Log with consistent shape and include IP for failures.

Add ip to error context for parity with the warn path.

- logger.error({ err: error }, "Auth email rate limit failed");+ logger.error({ err: error, ip: (req.headers.get("x-forwarded-for") ?? req.headers.get("x-real-ip") ?? "").split(",")[0]?.trim() }, "Auth email rate limit failed");
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7cf4610 and bd5bde8.

📒 Files selected for processing (4)
  • .env.example (1 hunks)
  • .env.selfhost.example (1 hunks)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts (1 hunks)
  • apps/web/src/env.js (2 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
.env*

📄 CodeRabbit inference engine (AGENTS.md)

Environment configuration files must live at the repository root and be named .env*

Files:

  • .env.selfhost.example
  • .env.example
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/env.js
  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use 2-space indentation in TypeScript code (enforced by Prettier)
Use semicolons in TypeScript code (enforced by Prettier)
Do not use dynamic imports

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code with Prettier 3 via pnpm format for TypeScript and Markdown files

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

In apps/web, use the / alias for src imports (e.g., import { x } from "/utils/x")

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
🧬 Code graph analysis (1)
apps/web/src/app/api/auth/[...nextauth]/route.ts (3)
apps/web/src/env.js (2)
  • env (5-130)
  • env (5-130)
apps/web/src/server/redis.ts (1)
  • getRedis (6-13)
apps/web/src/server/logger/log.ts (1)
  • logger (31-63)
🪛 dotenv-linter (3.3.0)
.env.selfhost.example

[warning] 37-37: [UnorderedKey] The AUTH_EMAIL_RATE_LIMIT key should go before the DOCKER_OUTPUT key

(UnorderedKey)

🔇 Additional comments (3)
.env.example (1)

23-23: LGTM: new variable documented.

AUTH_EMAIL_RATE_LIMIT is added and grouped with API_RATE_LIMIT; matches env.js schema.

apps/web/src/env.js (1)

102-102: Runtime mapping present.

AUTH_EMAIL_RATE_LIMIT is wired into runtimeEnv correctly.

apps/web/src/app/api/auth/[...nextauth]/route.ts (1)

35-36: LGTM: delegate to NextAuth when not rate-limited.

Flow is preserved for all other requests.

Comment on lines 1 to +6
import NextAuth from "next-auth";

import { authOptions } from "~/server/auth";
import { env } from "~/env";
import { getRedis } from "~/server/redis";
import { logger } from "~/server/logger/log";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Force Node.js runtime to avoid Edge/ioredis incompatibility.

This route uses ioredis via getRedis(); ensure it never runs on the Edge runtime.

 import NextAuth from "next-auth";
import { authOptions } from "~/server/auth";
import { env } from "~/env";
import { getRedis } from "~/server/redis";
import { logger } from "~/server/logger/log";
++// ioredis requires Node.js runtime+export const runtime = "nodejs";
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
importNextAuthfrom"next-auth";
import{authOptions}from"~/server/auth";
import{env}from"~/env";
import{getRedis}from"~/server/redis";
import{logger}from"~/server/logger/log";
importNextAuthfrom"next-auth";
import{authOptions}from"~/server/auth";
import{env}from"~/env";
import{getRedis}from"~/server/redis";
import{logger}from"~/server/logger/log";
// ioredis requires Node.js runtime
exportconstruntime="nodejs";
🤖 Prompt for AI Agents
In apps/web/src/app/api/auth/[...nextauth]/route.ts around lines 1-6, this
Next.js route uses ioredis via getRedis and must not run on the Edge runtime;
add an exported runtime declaration at the top of the file that sets the runtime
to Node (e.g., export a constant named runtime with value 'node') so the route
always runs on the Node.js runtime, then verify imports remain unchanged and
redeploy.

Comment threadapps/web/src/app/api/auth/[...nextauth]/route.ts Outdated
Comment threadapps/web/src/env.js
Comment on lines +47 to +50
AUTH_EMAIL_RATE_LIMIT: z
.string()
.default("0")
.transform((str) => parseInt(str, 10)),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Harden numeric validation for AUTH_EMAIL_RATE_LIMIT (avoid NaN, catch bad input).

Current z.string().transform(parseInt) allows non-numeric strings to become NaN, silently disabling rate limiting. Coerce to a non-negative int.

- AUTH_EMAIL_RATE_LIMIT: z- .string()- .default("0")- .transform((str) => parseInt(str, 10)),+ AUTH_EMAIL_RATE_LIMIT: z.coerce.number().int().nonnegative().default(0),
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
AUTH_EMAIL_RATE_LIMIT: z
.string()
.default("0")
.transform((str)=>parseInt(str,10)),
AUTH_EMAIL_RATE_LIMIT: z.coerce.number().int().nonnegative().default(0),
🤖 Prompt for AI Agents
In apps/web/src/env.js around lines 47 to 50, the current AUTH_EMAIL_RATE_LIMIT
uses z.string().transform(parseInt) which can produce NaN for bad input; change
it to parse and validate as a non-negative integer: preprocess the raw string
into a Number (e.g., with Number(str) or parseInt but guard against NaN), then
validate with z.number().int().nonnegative().default(0) (or add a refine to
reject NaN) so invalid values fail validation or fall back to 0 instead of
becoming NaN.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (1)
apps/web/src/app/api/auth/[...nextauth]/route.ts (1)

1-6: Force Node runtime to avoid ioredis/Edge crash.

This route uses ioredis; without forcing Node.js runtime it can deploy to Edge and fail at runtime.

 import NextAuth from "next-auth";
import { authOptions } from "~/server/auth";
import { env } from "~/env";
import { getRedis } from "~/server/redis";
import { logger } from "~/server/logger/log";
++// ioredis requires Node.js runtime+export const runtime = "nodejs";

Run to confirm the runtime export exists:

#!/bin/bash
rg -nP 'export\\s+const\\s+runtime\\s*=\\s*"nodejs"' apps/web/src/app/api/auth/\.\.\.nextauth/route\.ts
🧹 Nitpick comments (2)
apps/web/src/app/api/auth/[...nextauth]/route.ts (2)

57-59: Handle trailing slash on pathname.

Support both /signin/email and /signin/email/.

- const url = new URL(req.url);- if (url.pathname.endsWith("/signin/email")) {+ const url = new URL(req.url);+ const pathname = url.pathname.replace(/\/+$/, "");+ if (pathname.endsWith("/signin/email")) {

72-80: Include Retry-After and no-store headers on 429.

Improves client/backoff behavior and caching semantics.

- return Response.json(+ return Response.json(
{
error: {
code: "RATE_LIMITED",
message: "Too many requests",
},
},
- { status: 429 }+ {+ status: 429,+ headers: {+ "Retry-After": String(ttl),+ "Cache-Control": "no-store",+ },+ }
);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8879ab7 and 59ced7a.

📒 Files selected for processing (1)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use 2-space indentation in TypeScript code (enforced by Prettier)
Use semicolons in TypeScript code (enforced by Prettier)
Do not use dynamic imports

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code with Prettier 3 via pnpm format for TypeScript and Markdown files

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

In apps/web, use the / alias for src imports (e.g., import { x } from "/utils/x")

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
🧬 Code graph analysis (1)
apps/web/src/app/api/auth/[...nextauth]/route.ts (3)
apps/web/src/env.js (2)
  • env (5-130)
  • env (5-130)
apps/web/src/server/logger/log.ts (1)
  • logger (31-63)
apps/web/src/server/redis.ts (1)
  • getRedis (6-13)
🔇 Additional comments (2)
apps/web/src/app/api/auth/[...nextauth]/route.ts (2)

10-10: GET re-export: LGTM.

Re-exporting GET to NextAuth handler is correct.


56-86: Overall POST flow: solid.

Gated on env flag, scoped to email sign-in, uses atomic INCR+EXPIRE, logs and gracefully degrades on RL errors. Nice.

Comment on lines +12 to +50
function getClientIp(req: Request): string | null {
const h = req.headers;
const direct =
h.get("x-forwarded-for") ??
h.get("x-real-ip") ??
h.get("cf-connecting-ip") ??
h.get("x-client-ip") ??
h.get("true-client-ip") ??
h.get("fastly-client-ip") ??
h.get("x-cluster-client-ip") ??
null;

let ip = direct?.split(",")[0]?.trim() ?? "";

if (!ip) {
const fwd = h.get("forwarded");
if (fwd) {
const first = fwd.split(",")[0];
const match = first?.match(/for=([^;]+)/i);
if (match && match[1]) {
const raw = match[1].trim().replace(/^"|"$/g, "");
if (raw.startsWith("[")) {
const end = raw.indexOf("]");
ip = end !== -1 ? raw.slice(1, end) : raw;
} else {
const parts = raw.split(":");
if (parts.length > 0 && parts[0]) {
ip =
parts.length === 2 && /^\d+(?:\.\d+){3}$/.test(parts[0])
? parts[0]
: raw;
}
}
}
}
}

return ip || null;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Harden client IP parsing and validate before use.

Unvalidated header values can include ports/garbage and create unbounded Redis keys. Normalize and validate as IP; skip RL if invalid.

 function getClientIp(req: Request): string | null {
const h = req.headers;
@@
- let ip = direct?.split(",")[0]?.trim() ?? "";+ let ip = direct?.split(",")[0]?.trim() ?? "";+ // Strip IPv4 port if present in XFF: "1.2.3.4:5678" -> "1.2.3.4"+ const colon = ip.lastIndexOf(":");+ if (ip && colon > -1 && ip.includes(".")) ip = ip.slice(0, colon);
@@
- return ip || null;+ // Validate; treat non-IP as missing+ // (isIP returns 0 for invalid, 4 for IPv4, 6 for IPv6)+ return ip && isIP(ip) !== 0 ? ip : null;
}

Add import (top of file):

import{isIP}from"node:net";
🤖 Prompt for AI Agents
In apps/web/src/app/api/auth/[...nextauth]/route.ts around lines 12 to 50, the
client IP parsing accepts unvalidated header values (including ports/garbage)
which can produce unbounded Redis keys; import isIP from node:net and after
extracting the candidate IP normalize it (strip surrounding quotes, remove IPv6
brackets, remove appended port if present), then validate it with
isIP(candidate) and only return the IP when isIP(...) > 0; otherwise return null
so downstream logic (rate limiting) is skipped for invalid values.

Comment on lines +66 to +67
const key = `auth-rl:${ip}`;
const ttl = 60;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Hash the key to prevent header-driven key explosion and key injection.

Using raw header text as part of the key allows unbounded cardinality and odd bytes. Hashing stabilizes size and characters.

- const key = `auth-rl:${ip}`;+ const key = `auth-rl:${createHash("sha256").update(ip).digest("hex")}`;

Add import (top of file):

import{createHash}from"node:crypto";
🤖 Prompt for AI Agents
In apps/web/src/app/api/auth/[...nextauth]/route.ts around lines 66 to 67, the
rate-limit key is built from the raw IP/header which can lead to unbounded
cardinality and strange bytes; replace that with a stable hashed value: add an
import for createHash from node:crypto at the top of the file, compute a
deterministic hex (or base64) hash of the ip/header before composing the key,
and use the hashed value in place of the raw ip when building the `auth-rl:` key
so the key size/charset is fixed and safe.

@KMKoushik
KMKoushik merged commit 9723c78 into mainSep 9, 2025
4 checks passed
@KMKoushik
KMKoushik deleted the codex/implement-rate-limit-on-signup/signin-forms branch September 9, 2025 13:09
@coderabbitaicoderabbitaiBot mentioned this pull request Dec 19, 2025
10 tasks
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@KMKoushik
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat: add auth email rate limit - #220

Merged
KMKoushik merged 4 commits into
mainfrom
codex/implement-rate-limit-on-signup/signin-forms
Sep 9, 2025
Merged

feat: add auth email rate limit#220
KMKoushik merged 4 commits into
mainfrom
codex/implement-rate-limit-on-signup/signin-forms

Conversation

@KMKoushik

@KMKoushikKMKoushik commented Sep 9, 2025

Copy link
Copy Markdown
Member

Summary

  • add Redis-backed rate limiting for auth email sign-in requests
  • add AUTH_EMAIL_RATE_LIMIT env var and document in examples

Testing

  • pnpm format
  • pnpm lint(fails: ESLint found too many warnings)
  • npx eslint src/app/api/auth/[...nextauth]/route.ts
  • pnpm build(fails: Invalid environment variables)

https://chatgpt.com/codex/tasks/task_e_68bfda4f4da4832994ca3aec44f385fc

Summary by CodeRabbit

  • New Features
    • Per-IP rate limiting for email sign-in: repeated attempts from the same IP may receive a “Too Many Requests” (429) response to curb abuse; inactive by default unless configured.
  • Chores
    • Environment samples and server runtime config updated to add AUTH_EMAIL_RATE_LIMIT (default 0) for straightforward setup and enabling of the rate limit.

@vercel

vercelBot commented Sep 9, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
unsend-marketingReadyReadyPreviewCommentSep 9, 2025 1:08pm

@coderabbitai

coderabbitaiBot commented Sep 9, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Adds AUTH_EMAIL_RATE_LIMIT to .env.example and .env.selfhost.example and to the server env schema and runtime mapping in apps/web/src/env.js. Replaces the blanket POST export in apps/web/src/app/api/auth/[...nextauth]/route.ts with a new export async function POST(req, ctx) that enforces Redis-backed per-IP rate limiting for POST /signin/email by incrementing auth-rl:<ip> with a 60s TTL and returning 429 when the configured limit is exceeded; non-rate-limited requests delegate to the existing NextAuth handler. GET remains exported as the original handler.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 59ced7a and 98dce11.

📒 Files selected for processing (1)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Cloudflare Pages

Pre-merge checks (2 passed, 1 warning)

❌ Failed checks (1 warning)
Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%.You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check nameStatusExplanation
Title Check✅ PassedThe title “feat: add auth email rate limit” concisely and accurately summarizes the primary change of the pull request, namely introducing rate limiting for authentication email sign-in, without extraneous detail or unrelated context.
Description Check✅ PassedThe description outlines the key enhancements—adding Redis-backed rate limiting and the new AUTH_EMAIL_RATE_LIMIT environment variable—and includes relevant testing steps, making it clearly related to the changeset.
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/implement-rate-limit-on-signup/signin-forms

Comment @coderabbitai help to get the list of available commands and usage tips.

@cloudflare-workers-and-pages

cloudflare-workers-and-pagesBot commented Sep 9, 2025

Copy link
Copy Markdown

Deploying usesend with Cloudflare Pages Cloudflare Pages

Latest commit:98dce11
Status: ✅ Deploy successful!
Preview URL:https://a7f0d9f7.usesend.pages.dev
Branch Preview URL:https://codex-implement-rate-limit-o.usesend.pages.dev

View logs

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (4)
.env.selfhost.example (1)

37-37: Alphabetize keys to satisfy dotenv-linter (and keep examples consistent).

Place AUTH_EMAIL_RATE_LIMIT before DOCKER_OUTPUT (and next to API_RATE_LIMIT).

Apply:

-DOCKER_OUTPUT=1-API_RATE_LIMIT=1-AUTH_EMAIL_RATE_LIMIT=5+API_RATE_LIMIT=1+AUTH_EMAIL_RATE_LIMIT=5+DOCKER_OUTPUT=1
apps/web/src/app/api/auth/[...nextauth]/route.ts (3)

21-26: Atomic TTL set (optional): use EXPIRE NX in a pipeline.

Your pattern is fine; using EXPIRE with NX ensures TTL is attached only on first creation without relying on count === 1.

- const count = await redis.incr(key);- if (count === 1) await redis.expire(key, ttl);+ const [[, count]] = await redis+ .multi()+ .incr(key)+ // Redis >=7 supports EXPIRE key seconds NX+ .expire(key, ttl, "NX")+ .exec();

27-29: Include rate-limit headers and a Retry-After hint.

Improves client/backoff behavior and observability.

- return new Response("Too many requests", { status: 429 });+ const retryAfter = "60";+ return new Response(+ JSON.stringify({ error: "Too many requests" }),+ {+ status: 429,+ headers: {+ "Content-Type": "application/json",+ "Retry-After": retryAfter,+ "X-RateLimit-Limit": String(env.AUTH_EMAIL_RATE_LIMIT),+ "X-RateLimit-Remaining": "0",+ "X-RateLimit-Reset": retryAfter,+ },+ },+ );

30-32: Log with consistent shape and include IP for failures.

Add ip to error context for parity with the warn path.

- logger.error({ err: error }, "Auth email rate limit failed");+ logger.error({ err: error, ip: (req.headers.get("x-forwarded-for") ?? req.headers.get("x-real-ip") ?? "").split(",")[0]?.trim() }, "Auth email rate limit failed");
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7cf4610 and bd5bde8.

📒 Files selected for processing (4)
  • .env.example (1 hunks)
  • .env.selfhost.example (1 hunks)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts (1 hunks)
  • apps/web/src/env.js (2 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
.env*

📄 CodeRabbit inference engine (AGENTS.md)

Environment configuration files must live at the repository root and be named .env*

Files:

  • .env.selfhost.example
  • .env.example
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/env.js
  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use 2-space indentation in TypeScript code (enforced by Prettier)
Use semicolons in TypeScript code (enforced by Prettier)
Do not use dynamic imports

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code with Prettier 3 via pnpm format for TypeScript and Markdown files

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

In apps/web, use the / alias for src imports (e.g., import { x } from "/utils/x")

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
🧬 Code graph analysis (1)
apps/web/src/app/api/auth/[...nextauth]/route.ts (3)
apps/web/src/env.js (2)
  • env (5-130)
  • env (5-130)
apps/web/src/server/redis.ts (1)
  • getRedis (6-13)
apps/web/src/server/logger/log.ts (1)
  • logger (31-63)
🪛 dotenv-linter (3.3.0)
.env.selfhost.example

[warning] 37-37: [UnorderedKey] The AUTH_EMAIL_RATE_LIMIT key should go before the DOCKER_OUTPUT key

(UnorderedKey)

🔇 Additional comments (3)
.env.example (1)

23-23: LGTM: new variable documented.

AUTH_EMAIL_RATE_LIMIT is added and grouped with API_RATE_LIMIT; matches env.js schema.

apps/web/src/env.js (1)

102-102: Runtime mapping present.

AUTH_EMAIL_RATE_LIMIT is wired into runtimeEnv correctly.

apps/web/src/app/api/auth/[...nextauth]/route.ts (1)

35-36: LGTM: delegate to NextAuth when not rate-limited.

Flow is preserved for all other requests.

Comment on lines 1 to +6
import NextAuth from "next-auth";

import { authOptions } from "~/server/auth";
import { env } from "~/env";
import { getRedis } from "~/server/redis";
import { logger } from "~/server/logger/log";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Force Node.js runtime to avoid Edge/ioredis incompatibility.

This route uses ioredis via getRedis(); ensure it never runs on the Edge runtime.

 import NextAuth from "next-auth";
import { authOptions } from "~/server/auth";
import { env } from "~/env";
import { getRedis } from "~/server/redis";
import { logger } from "~/server/logger/log";
++// ioredis requires Node.js runtime+export const runtime = "nodejs";
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
importNextAuthfrom"next-auth";
import{authOptions}from"~/server/auth";
import{env}from"~/env";
import{getRedis}from"~/server/redis";
import{logger}from"~/server/logger/log";
importNextAuthfrom"next-auth";
import{authOptions}from"~/server/auth";
import{env}from"~/env";
import{getRedis}from"~/server/redis";
import{logger}from"~/server/logger/log";
// ioredis requires Node.js runtime
exportconstruntime="nodejs";
🤖 Prompt for AI Agents
In apps/web/src/app/api/auth/[...nextauth]/route.ts around lines 1-6, this
Next.js route uses ioredis via getRedis and must not run on the Edge runtime;
add an exported runtime declaration at the top of the file that sets the runtime
to Node (e.g., export a constant named runtime with value 'node') so the route
always runs on the Node.js runtime, then verify imports remain unchanged and
redeploy.

Comment threadapps/web/src/app/api/auth/[...nextauth]/route.ts Outdated
Comment threadapps/web/src/env.js
Comment on lines +47 to +50
AUTH_EMAIL_RATE_LIMIT: z
.string()
.default("0")
.transform((str) => parseInt(str, 10)),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Harden numeric validation for AUTH_EMAIL_RATE_LIMIT (avoid NaN, catch bad input).

Current z.string().transform(parseInt) allows non-numeric strings to become NaN, silently disabling rate limiting. Coerce to a non-negative int.

- AUTH_EMAIL_RATE_LIMIT: z- .string()- .default("0")- .transform((str) => parseInt(str, 10)),+ AUTH_EMAIL_RATE_LIMIT: z.coerce.number().int().nonnegative().default(0),
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
AUTH_EMAIL_RATE_LIMIT: z
.string()
.default("0")
.transform((str)=>parseInt(str,10)),
AUTH_EMAIL_RATE_LIMIT: z.coerce.number().int().nonnegative().default(0),
🤖 Prompt for AI Agents
In apps/web/src/env.js around lines 47 to 50, the current AUTH_EMAIL_RATE_LIMIT
uses z.string().transform(parseInt) which can produce NaN for bad input; change
it to parse and validate as a non-negative integer: preprocess the raw string
into a Number (e.g., with Number(str) or parseInt but guard against NaN), then
validate with z.number().int().nonnegative().default(0) (or add a refine to
reject NaN) so invalid values fail validation or fall back to 0 instead of
becoming NaN.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (1)
apps/web/src/app/api/auth/[...nextauth]/route.ts (1)

1-6: Force Node runtime to avoid ioredis/Edge crash.

This route uses ioredis; without forcing Node.js runtime it can deploy to Edge and fail at runtime.

 import NextAuth from "next-auth";
import { authOptions } from "~/server/auth";
import { env } from "~/env";
import { getRedis } from "~/server/redis";
import { logger } from "~/server/logger/log";
++// ioredis requires Node.js runtime+export const runtime = "nodejs";

Run to confirm the runtime export exists:

#!/bin/bash
rg -nP 'export\\s+const\\s+runtime\\s*=\\s*"nodejs"' apps/web/src/app/api/auth/\.\.\.nextauth/route\.ts
🧹 Nitpick comments (2)
apps/web/src/app/api/auth/[...nextauth]/route.ts (2)

57-59: Handle trailing slash on pathname.

Support both /signin/email and /signin/email/.

- const url = new URL(req.url);- if (url.pathname.endsWith("/signin/email")) {+ const url = new URL(req.url);+ const pathname = url.pathname.replace(/\/+$/, "");+ if (pathname.endsWith("/signin/email")) {

72-80: Include Retry-After and no-store headers on 429.

Improves client/backoff behavior and caching semantics.

- return Response.json(+ return Response.json(
{
error: {
code: "RATE_LIMITED",
message: "Too many requests",
},
},
- { status: 429 }+ {+ status: 429,+ headers: {+ "Retry-After": String(ttl),+ "Cache-Control": "no-store",+ },+ }
);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8879ab7 and 59ced7a.

📒 Files selected for processing (1)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use 2-space indentation in TypeScript code (enforced by Prettier)
Use semicolons in TypeScript code (enforced by Prettier)
Do not use dynamic imports

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code with Prettier 3 via pnpm format for TypeScript and Markdown files

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

In apps/web, use the / alias for src imports (e.g., import { x } from "/utils/x")

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
🧬 Code graph analysis (1)
apps/web/src/app/api/auth/[...nextauth]/route.ts (3)
apps/web/src/env.js (2)
  • env (5-130)
  • env (5-130)
apps/web/src/server/logger/log.ts (1)
  • logger (31-63)
apps/web/src/server/redis.ts (1)
  • getRedis (6-13)
🔇 Additional comments (2)
apps/web/src/app/api/auth/[...nextauth]/route.ts (2)

10-10: GET re-export: LGTM.

Re-exporting GET to NextAuth handler is correct.


56-86: Overall POST flow: solid.

Gated on env flag, scoped to email sign-in, uses atomic INCR+EXPIRE, logs and gracefully degrades on RL errors. Nice.

Comment on lines +12 to +50
function getClientIp(req: Request): string | null {
const h = req.headers;
const direct =
h.get("x-forwarded-for") ??
h.get("x-real-ip") ??
h.get("cf-connecting-ip") ??
h.get("x-client-ip") ??
h.get("true-client-ip") ??
h.get("fastly-client-ip") ??
h.get("x-cluster-client-ip") ??
null;

let ip = direct?.split(",")[0]?.trim() ?? "";

if (!ip) {
const fwd = h.get("forwarded");
if (fwd) {
const first = fwd.split(",")[0];
const match = first?.match(/for=([^;]+)/i);
if (match && match[1]) {
const raw = match[1].trim().replace(/^"|"$/g, "");
if (raw.startsWith("[")) {
const end = raw.indexOf("]");
ip = end !== -1 ? raw.slice(1, end) : raw;
} else {
const parts = raw.split(":");
if (parts.length > 0 && parts[0]) {
ip =
parts.length === 2 && /^\d+(?:\.\d+){3}$/.test(parts[0])
? parts[0]
: raw;
}
}
}
}
}

return ip || null;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Harden client IP parsing and validate before use.

Unvalidated header values can include ports/garbage and create unbounded Redis keys. Normalize and validate as IP; skip RL if invalid.

 function getClientIp(req: Request): string | null {
const h = req.headers;
@@
- let ip = direct?.split(",")[0]?.trim() ?? "";+ let ip = direct?.split(",")[0]?.trim() ?? "";+ // Strip IPv4 port if present in XFF: "1.2.3.4:5678" -> "1.2.3.4"+ const colon = ip.lastIndexOf(":");+ if (ip && colon > -1 && ip.includes(".")) ip = ip.slice(0, colon);
@@
- return ip || null;+ // Validate; treat non-IP as missing+ // (isIP returns 0 for invalid, 4 for IPv4, 6 for IPv6)+ return ip && isIP(ip) !== 0 ? ip : null;
}

Add import (top of file):

import{isIP}from"node:net";
🤖 Prompt for AI Agents
In apps/web/src/app/api/auth/[...nextauth]/route.ts around lines 12 to 50, the
client IP parsing accepts unvalidated header values (including ports/garbage)
which can produce unbounded Redis keys; import isIP from node:net and after
extracting the candidate IP normalize it (strip surrounding quotes, remove IPv6
brackets, remove appended port if present), then validate it with
isIP(candidate) and only return the IP when isIP(...) > 0; otherwise return null
so downstream logic (rate limiting) is skipped for invalid values.

Comment on lines +66 to +67
const key = `auth-rl:${ip}`;
const ttl = 60;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Hash the key to prevent header-driven key explosion and key injection.

Using raw header text as part of the key allows unbounded cardinality and odd bytes. Hashing stabilizes size and characters.

- const key = `auth-rl:${ip}`;+ const key = `auth-rl:${createHash("sha256").update(ip).digest("hex")}`;

Add import (top of file):

import{createHash}from"node:crypto";
🤖 Prompt for AI Agents
In apps/web/src/app/api/auth/[...nextauth]/route.ts around lines 66 to 67, the
rate-limit key is built from the raw IP/header which can lead to unbounded
cardinality and strange bytes; replace that with a stable hashed value: add an
import for createHash from node:crypto at the top of the file, compute a
deterministic hex (or base64) hash of the ip/header before composing the key,
and use the hashed value in place of the raw ip when building the `auth-rl:` key
so the key size/charset is fixed and safe.

@KMKoushik
KMKoushik merged commit 9723c78 into mainSep 9, 2025
4 checks passed
@KMKoushik
KMKoushik deleted the codex/implement-rate-limit-on-signup/signin-forms branch September 9, 2025 13:09
@coderabbitaicoderabbitaiBot mentioned this pull request Dec 19, 2025
10 tasks
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@KMKoushik
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

feat: add auth email rate limit - #220

Merged
KMKoushik merged 4 commits into
mainfrom
codex/implement-rate-limit-on-signup/signin-forms
Sep 9, 2025
Merged

feat: add auth email rate limit#220
KMKoushik merged 4 commits into
mainfrom
codex/implement-rate-limit-on-signup/signin-forms

Conversation

@KMKoushik

@KMKoushikKMKoushik commented Sep 9, 2025

Copy link
Copy Markdown
Member

Summary

  • add Redis-backed rate limiting for auth email sign-in requests
  • add AUTH_EMAIL_RATE_LIMIT env var and document in examples

Testing

  • pnpm format
  • pnpm lint(fails: ESLint found too many warnings)
  • npx eslint src/app/api/auth/[...nextauth]/route.ts
  • pnpm build(fails: Invalid environment variables)

https://chatgpt.com/codex/tasks/task_e_68bfda4f4da4832994ca3aec44f385fc

Summary by CodeRabbit

  • New Features
    • Per-IP rate limiting for email sign-in: repeated attempts from the same IP may receive a “Too Many Requests” (429) response to curb abuse; inactive by default unless configured.
  • Chores
    • Environment samples and server runtime config updated to add AUTH_EMAIL_RATE_LIMIT (default 0) for straightforward setup and enabling of the rate limit.

@vercel

vercelBot commented Sep 9, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
unsend-marketingReadyReadyPreviewCommentSep 9, 2025 1:08pm

@coderabbitai

coderabbitaiBot commented Sep 9, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Adds AUTH_EMAIL_RATE_LIMIT to .env.example and .env.selfhost.example and to the server env schema and runtime mapping in apps/web/src/env.js. Replaces the blanket POST export in apps/web/src/app/api/auth/[...nextauth]/route.ts with a new export async function POST(req, ctx) that enforces Redis-backed per-IP rate limiting for POST /signin/email by incrementing auth-rl:<ip> with a 60s TTL and returning 429 when the configured limit is exceeded; non-rate-limited requests delegate to the existing NextAuth handler. GET remains exported as the original handler.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 59ced7a and 98dce11.

📒 Files selected for processing (1)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Cloudflare Pages

Pre-merge checks (2 passed, 1 warning)

❌ Failed checks (1 warning)
Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%.You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check nameStatusExplanation
Title Check✅ PassedThe title “feat: add auth email rate limit” concisely and accurately summarizes the primary change of the pull request, namely introducing rate limiting for authentication email sign-in, without extraneous detail or unrelated context.
Description Check✅ PassedThe description outlines the key enhancements—adding Redis-backed rate limiting and the new AUTH_EMAIL_RATE_LIMIT environment variable—and includes relevant testing steps, making it clearly related to the changeset.
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/implement-rate-limit-on-signup/signin-forms

Comment @coderabbitai help to get the list of available commands and usage tips.

@cloudflare-workers-and-pages

cloudflare-workers-and-pagesBot commented Sep 9, 2025

Copy link
Copy Markdown

Deploying usesend with Cloudflare Pages Cloudflare Pages

Latest commit:98dce11
Status: ✅ Deploy successful!
Preview URL:https://a7f0d9f7.usesend.pages.dev
Branch Preview URL:https://codex-implement-rate-limit-o.usesend.pages.dev

View logs

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (4)
.env.selfhost.example (1)

37-37: Alphabetize keys to satisfy dotenv-linter (and keep examples consistent).

Place AUTH_EMAIL_RATE_LIMIT before DOCKER_OUTPUT (and next to API_RATE_LIMIT).

Apply:

-DOCKER_OUTPUT=1-API_RATE_LIMIT=1-AUTH_EMAIL_RATE_LIMIT=5+API_RATE_LIMIT=1+AUTH_EMAIL_RATE_LIMIT=5+DOCKER_OUTPUT=1
apps/web/src/app/api/auth/[...nextauth]/route.ts (3)

21-26: Atomic TTL set (optional): use EXPIRE NX in a pipeline.

Your pattern is fine; using EXPIRE with NX ensures TTL is attached only on first creation without relying on count === 1.

- const count = await redis.incr(key);- if (count === 1) await redis.expire(key, ttl);+ const [[, count]] = await redis+ .multi()+ .incr(key)+ // Redis >=7 supports EXPIRE key seconds NX+ .expire(key, ttl, "NX")+ .exec();

27-29: Include rate-limit headers and a Retry-After hint.

Improves client/backoff behavior and observability.

- return new Response("Too many requests", { status: 429 });+ const retryAfter = "60";+ return new Response(+ JSON.stringify({ error: "Too many requests" }),+ {+ status: 429,+ headers: {+ "Content-Type": "application/json",+ "Retry-After": retryAfter,+ "X-RateLimit-Limit": String(env.AUTH_EMAIL_RATE_LIMIT),+ "X-RateLimit-Remaining": "0",+ "X-RateLimit-Reset": retryAfter,+ },+ },+ );

30-32: Log with consistent shape and include IP for failures.

Add ip to error context for parity with the warn path.

- logger.error({ err: error }, "Auth email rate limit failed");+ logger.error({ err: error, ip: (req.headers.get("x-forwarded-for") ?? req.headers.get("x-real-ip") ?? "").split(",")[0]?.trim() }, "Auth email rate limit failed");
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7cf4610 and bd5bde8.

📒 Files selected for processing (4)
  • .env.example (1 hunks)
  • .env.selfhost.example (1 hunks)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts (1 hunks)
  • apps/web/src/env.js (2 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
.env*

📄 CodeRabbit inference engine (AGENTS.md)

Environment configuration files must live at the repository root and be named .env*

Files:

  • .env.selfhost.example
  • .env.example
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/env.js
  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use 2-space indentation in TypeScript code (enforced by Prettier)
Use semicolons in TypeScript code (enforced by Prettier)
Do not use dynamic imports

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code with Prettier 3 via pnpm format for TypeScript and Markdown files

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

In apps/web, use the / alias for src imports (e.g., import { x } from "/utils/x")

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
🧬 Code graph analysis (1)
apps/web/src/app/api/auth/[...nextauth]/route.ts (3)
apps/web/src/env.js (2)
  • env (5-130)
  • env (5-130)
apps/web/src/server/redis.ts (1)
  • getRedis (6-13)
apps/web/src/server/logger/log.ts (1)
  • logger (31-63)
🪛 dotenv-linter (3.3.0)
.env.selfhost.example

[warning] 37-37: [UnorderedKey] The AUTH_EMAIL_RATE_LIMIT key should go before the DOCKER_OUTPUT key

(UnorderedKey)

🔇 Additional comments (3)
.env.example (1)

23-23: LGTM: new variable documented.

AUTH_EMAIL_RATE_LIMIT is added and grouped with API_RATE_LIMIT; matches env.js schema.

apps/web/src/env.js (1)

102-102: Runtime mapping present.

AUTH_EMAIL_RATE_LIMIT is wired into runtimeEnv correctly.

apps/web/src/app/api/auth/[...nextauth]/route.ts (1)

35-36: LGTM: delegate to NextAuth when not rate-limited.

Flow is preserved for all other requests.

Comment on lines 1 to +6
import NextAuth from "next-auth";

import { authOptions } from "~/server/auth";
import { env } from "~/env";
import { getRedis } from "~/server/redis";
import { logger } from "~/server/logger/log";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Force Node.js runtime to avoid Edge/ioredis incompatibility.

This route uses ioredis via getRedis(); ensure it never runs on the Edge runtime.

 import NextAuth from "next-auth";
import { authOptions } from "~/server/auth";
import { env } from "~/env";
import { getRedis } from "~/server/redis";
import { logger } from "~/server/logger/log";
++// ioredis requires Node.js runtime+export const runtime = "nodejs";
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
importNextAuthfrom"next-auth";
import{authOptions}from"~/server/auth";
import{env}from"~/env";
import{getRedis}from"~/server/redis";
import{logger}from"~/server/logger/log";
importNextAuthfrom"next-auth";
import{authOptions}from"~/server/auth";
import{env}from"~/env";
import{getRedis}from"~/server/redis";
import{logger}from"~/server/logger/log";
// ioredis requires Node.js runtime
exportconstruntime="nodejs";
🤖 Prompt for AI Agents
In apps/web/src/app/api/auth/[...nextauth]/route.ts around lines 1-6, this
Next.js route uses ioredis via getRedis and must not run on the Edge runtime;
add an exported runtime declaration at the top of the file that sets the runtime
to Node (e.g., export a constant named runtime with value 'node') so the route
always runs on the Node.js runtime, then verify imports remain unchanged and
redeploy.

Comment threadapps/web/src/app/api/auth/[...nextauth]/route.ts Outdated
Comment threadapps/web/src/env.js
Comment on lines +47 to +50
AUTH_EMAIL_RATE_LIMIT: z
.string()
.default("0")
.transform((str) => parseInt(str, 10)),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Harden numeric validation for AUTH_EMAIL_RATE_LIMIT (avoid NaN, catch bad input).

Current z.string().transform(parseInt) allows non-numeric strings to become NaN, silently disabling rate limiting. Coerce to a non-negative int.

- AUTH_EMAIL_RATE_LIMIT: z- .string()- .default("0")- .transform((str) => parseInt(str, 10)),+ AUTH_EMAIL_RATE_LIMIT: z.coerce.number().int().nonnegative().default(0),
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
AUTH_EMAIL_RATE_LIMIT: z
.string()
.default("0")
.transform((str)=>parseInt(str,10)),
AUTH_EMAIL_RATE_LIMIT: z.coerce.number().int().nonnegative().default(0),
🤖 Prompt for AI Agents
In apps/web/src/env.js around lines 47 to 50, the current AUTH_EMAIL_RATE_LIMIT
uses z.string().transform(parseInt) which can produce NaN for bad input; change
it to parse and validate as a non-negative integer: preprocess the raw string
into a Number (e.g., with Number(str) or parseInt but guard against NaN), then
validate with z.number().int().nonnegative().default(0) (or add a refine to
reject NaN) so invalid values fail validation or fall back to 0 instead of
becoming NaN.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (1)
apps/web/src/app/api/auth/[...nextauth]/route.ts (1)

1-6: Force Node runtime to avoid ioredis/Edge crash.

This route uses ioredis; without forcing Node.js runtime it can deploy to Edge and fail at runtime.

 import NextAuth from "next-auth";
import { authOptions } from "~/server/auth";
import { env } from "~/env";
import { getRedis } from "~/server/redis";
import { logger } from "~/server/logger/log";
++// ioredis requires Node.js runtime+export const runtime = "nodejs";

Run to confirm the runtime export exists:

#!/bin/bash
rg -nP 'export\\s+const\\s+runtime\\s*=\\s*"nodejs"' apps/web/src/app/api/auth/\.\.\.nextauth/route\.ts
🧹 Nitpick comments (2)
apps/web/src/app/api/auth/[...nextauth]/route.ts (2)

57-59: Handle trailing slash on pathname.

Support both /signin/email and /signin/email/.

- const url = new URL(req.url);- if (url.pathname.endsWith("/signin/email")) {+ const url = new URL(req.url);+ const pathname = url.pathname.replace(/\/+$/, "");+ if (pathname.endsWith("/signin/email")) {

72-80: Include Retry-After and no-store headers on 429.

Improves client/backoff behavior and caching semantics.

- return Response.json(+ return Response.json(
{
error: {
code: "RATE_LIMITED",
message: "Too many requests",
},
},
- { status: 429 }+ {+ status: 429,+ headers: {+ "Retry-After": String(ttl),+ "Cache-Control": "no-store",+ },+ }
);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8879ab7 and 59ced7a.

📒 Files selected for processing (1)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use 2-space indentation in TypeScript code (enforced by Prettier)
Use semicolons in TypeScript code (enforced by Prettier)
Do not use dynamic imports

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code with Prettier 3 via pnpm format for TypeScript and Markdown files

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

In apps/web, use the / alias for src imports (e.g., import { x } from "/utils/x")

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
🧬 Code graph analysis (1)
apps/web/src/app/api/auth/[...nextauth]/route.ts (3)
apps/web/src/env.js (2)
  • env (5-130)
  • env (5-130)
apps/web/src/server/logger/log.ts (1)
  • logger (31-63)
apps/web/src/server/redis.ts (1)
  • getRedis (6-13)
🔇 Additional comments (2)
apps/web/src/app/api/auth/[...nextauth]/route.ts (2)

10-10: GET re-export: LGTM.

Re-exporting GET to NextAuth handler is correct.


56-86: Overall POST flow: solid.

Gated on env flag, scoped to email sign-in, uses atomic INCR+EXPIRE, logs and gracefully degrades on RL errors. Nice.

Comment on lines +12 to +50
function getClientIp(req: Request): string | null {
const h = req.headers;
const direct =
h.get("x-forwarded-for") ??
h.get("x-real-ip") ??
h.get("cf-connecting-ip") ??
h.get("x-client-ip") ??
h.get("true-client-ip") ??
h.get("fastly-client-ip") ??
h.get("x-cluster-client-ip") ??
null;

let ip = direct?.split(",")[0]?.trim() ?? "";

if (!ip) {
const fwd = h.get("forwarded");
if (fwd) {
const first = fwd.split(",")[0];
const match = first?.match(/for=([^;]+)/i);
if (match && match[1]) {
const raw = match[1].trim().replace(/^"|"$/g, "");
if (raw.startsWith("[")) {
const end = raw.indexOf("]");
ip = end !== -1 ? raw.slice(1, end) : raw;
} else {
const parts = raw.split(":");
if (parts.length > 0 && parts[0]) {
ip =
parts.length === 2 && /^\d+(?:\.\d+){3}$/.test(parts[0])
? parts[0]
: raw;
}
}
}
}
}

return ip || null;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Harden client IP parsing and validate before use.

Unvalidated header values can include ports/garbage and create unbounded Redis keys. Normalize and validate as IP; skip RL if invalid.

 function getClientIp(req: Request): string | null {
const h = req.headers;
@@
- let ip = direct?.split(",")[0]?.trim() ?? "";+ let ip = direct?.split(",")[0]?.trim() ?? "";+ // Strip IPv4 port if present in XFF: "1.2.3.4:5678" -> "1.2.3.4"+ const colon = ip.lastIndexOf(":");+ if (ip && colon > -1 && ip.includes(".")) ip = ip.slice(0, colon);
@@
- return ip || null;+ // Validate; treat non-IP as missing+ // (isIP returns 0 for invalid, 4 for IPv4, 6 for IPv6)+ return ip && isIP(ip) !== 0 ? ip : null;
}

Add import (top of file):

import{isIP}from"node:net";
🤖 Prompt for AI Agents
In apps/web/src/app/api/auth/[...nextauth]/route.ts around lines 12 to 50, the
client IP parsing accepts unvalidated header values (including ports/garbage)
which can produce unbounded Redis keys; import isIP from node:net and after
extracting the candidate IP normalize it (strip surrounding quotes, remove IPv6
brackets, remove appended port if present), then validate it with
isIP(candidate) and only return the IP when isIP(...) > 0; otherwise return null
so downstream logic (rate limiting) is skipped for invalid values.

Comment on lines +66 to +67
const key = `auth-rl:${ip}`;
const ttl = 60;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Hash the key to prevent header-driven key explosion and key injection.

Using raw header text as part of the key allows unbounded cardinality and odd bytes. Hashing stabilizes size and characters.

- const key = `auth-rl:${ip}`;+ const key = `auth-rl:${createHash("sha256").update(ip).digest("hex")}`;

Add import (top of file):

import{createHash}from"node:crypto";
🤖 Prompt for AI Agents
In apps/web/src/app/api/auth/[...nextauth]/route.ts around lines 66 to 67, the
rate-limit key is built from the raw IP/header which can lead to unbounded
cardinality and strange bytes; replace that with a stable hashed value: add an
import for createHash from node:crypto at the top of the file, compute a
deterministic hex (or base64) hash of the ip/header before composing the key,
and use the hashed value in place of the raw ip when building the `auth-rl:` key
so the key size/charset is fixed and safe.

@KMKoushik
KMKoushik merged commit 9723c78 into mainSep 9, 2025
4 checks passed
@KMKoushik
KMKoushik deleted the codex/implement-rate-limit-on-signup/signin-forms branch September 9, 2025 13:09
@coderabbitaicoderabbitaiBot mentioned this pull request Dec 19, 2025
10 tasks
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@KMKoushik
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat: add auth email rate limit - #220

Merged
KMKoushik merged 4 commits into
mainfrom
codex/implement-rate-limit-on-signup/signin-forms
Sep 9, 2025
Merged

feat: add auth email rate limit#220
KMKoushik merged 4 commits into
mainfrom
codex/implement-rate-limit-on-signup/signin-forms

Conversation

@KMKoushik

@KMKoushikKMKoushik commented Sep 9, 2025

Copy link
Copy Markdown
Member

Summary

  • add Redis-backed rate limiting for auth email sign-in requests
  • add AUTH_EMAIL_RATE_LIMIT env var and document in examples

Testing

  • pnpm format
  • pnpm lint(fails: ESLint found too many warnings)
  • npx eslint src/app/api/auth/[...nextauth]/route.ts
  • pnpm build(fails: Invalid environment variables)

https://chatgpt.com/codex/tasks/task_e_68bfda4f4da4832994ca3aec44f385fc

Summary by CodeRabbit

  • New Features
    • Per-IP rate limiting for email sign-in: repeated attempts from the same IP may receive a “Too Many Requests” (429) response to curb abuse; inactive by default unless configured.
  • Chores
    • Environment samples and server runtime config updated to add AUTH_EMAIL_RATE_LIMIT (default 0) for straightforward setup and enabling of the rate limit.

@vercel

vercelBot commented Sep 9, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
unsend-marketingReadyReadyPreviewCommentSep 9, 2025 1:08pm

@coderabbitai

coderabbitaiBot commented Sep 9, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Adds AUTH_EMAIL_RATE_LIMIT to .env.example and .env.selfhost.example and to the server env schema and runtime mapping in apps/web/src/env.js. Replaces the blanket POST export in apps/web/src/app/api/auth/[...nextauth]/route.ts with a new export async function POST(req, ctx) that enforces Redis-backed per-IP rate limiting for POST /signin/email by incrementing auth-rl:<ip> with a 60s TTL and returning 429 when the configured limit is exceeded; non-rate-limited requests delegate to the existing NextAuth handler. GET remains exported as the original handler.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 59ced7a and 98dce11.

📒 Files selected for processing (1)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Cloudflare Pages

Pre-merge checks (2 passed, 1 warning)

❌ Failed checks (1 warning)
Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%.You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check nameStatusExplanation
Title Check✅ PassedThe title “feat: add auth email rate limit” concisely and accurately summarizes the primary change of the pull request, namely introducing rate limiting for authentication email sign-in, without extraneous detail or unrelated context.
Description Check✅ PassedThe description outlines the key enhancements—adding Redis-backed rate limiting and the new AUTH_EMAIL_RATE_LIMIT environment variable—and includes relevant testing steps, making it clearly related to the changeset.
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/implement-rate-limit-on-signup/signin-forms

Comment @coderabbitai help to get the list of available commands and usage tips.

@cloudflare-workers-and-pages

cloudflare-workers-and-pagesBot commented Sep 9, 2025

Copy link
Copy Markdown

Deploying usesend with Cloudflare Pages Cloudflare Pages

Latest commit:98dce11
Status: ✅ Deploy successful!
Preview URL:https://a7f0d9f7.usesend.pages.dev
Branch Preview URL:https://codex-implement-rate-limit-o.usesend.pages.dev

View logs

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (4)
.env.selfhost.example (1)

37-37: Alphabetize keys to satisfy dotenv-linter (and keep examples consistent).

Place AUTH_EMAIL_RATE_LIMIT before DOCKER_OUTPUT (and next to API_RATE_LIMIT).

Apply:

-DOCKER_OUTPUT=1-API_RATE_LIMIT=1-AUTH_EMAIL_RATE_LIMIT=5+API_RATE_LIMIT=1+AUTH_EMAIL_RATE_LIMIT=5+DOCKER_OUTPUT=1
apps/web/src/app/api/auth/[...nextauth]/route.ts (3)

21-26: Atomic TTL set (optional): use EXPIRE NX in a pipeline.

Your pattern is fine; using EXPIRE with NX ensures TTL is attached only on first creation without relying on count === 1.

- const count = await redis.incr(key);- if (count === 1) await redis.expire(key, ttl);+ const [[, count]] = await redis+ .multi()+ .incr(key)+ // Redis >=7 supports EXPIRE key seconds NX+ .expire(key, ttl, "NX")+ .exec();

27-29: Include rate-limit headers and a Retry-After hint.

Improves client/backoff behavior and observability.

- return new Response("Too many requests", { status: 429 });+ const retryAfter = "60";+ return new Response(+ JSON.stringify({ error: "Too many requests" }),+ {+ status: 429,+ headers: {+ "Content-Type": "application/json",+ "Retry-After": retryAfter,+ "X-RateLimit-Limit": String(env.AUTH_EMAIL_RATE_LIMIT),+ "X-RateLimit-Remaining": "0",+ "X-RateLimit-Reset": retryAfter,+ },+ },+ );

30-32: Log with consistent shape and include IP for failures.

Add ip to error context for parity with the warn path.

- logger.error({ err: error }, "Auth email rate limit failed");+ logger.error({ err: error, ip: (req.headers.get("x-forwarded-for") ?? req.headers.get("x-real-ip") ?? "").split(",")[0]?.trim() }, "Auth email rate limit failed");
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7cf4610 and bd5bde8.

📒 Files selected for processing (4)
  • .env.example (1 hunks)
  • .env.selfhost.example (1 hunks)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts (1 hunks)
  • apps/web/src/env.js (2 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
.env*

📄 CodeRabbit inference engine (AGENTS.md)

Environment configuration files must live at the repository root and be named .env*

Files:

  • .env.selfhost.example
  • .env.example
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/env.js
  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use 2-space indentation in TypeScript code (enforced by Prettier)
Use semicolons in TypeScript code (enforced by Prettier)
Do not use dynamic imports

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code with Prettier 3 via pnpm format for TypeScript and Markdown files

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

In apps/web, use the / alias for src imports (e.g., import { x } from "/utils/x")

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
🧬 Code graph analysis (1)
apps/web/src/app/api/auth/[...nextauth]/route.ts (3)
apps/web/src/env.js (2)
  • env (5-130)
  • env (5-130)
apps/web/src/server/redis.ts (1)
  • getRedis (6-13)
apps/web/src/server/logger/log.ts (1)
  • logger (31-63)
🪛 dotenv-linter (3.3.0)
.env.selfhost.example

[warning] 37-37: [UnorderedKey] The AUTH_EMAIL_RATE_LIMIT key should go before the DOCKER_OUTPUT key

(UnorderedKey)

🔇 Additional comments (3)
.env.example (1)

23-23: LGTM: new variable documented.

AUTH_EMAIL_RATE_LIMIT is added and grouped with API_RATE_LIMIT; matches env.js schema.

apps/web/src/env.js (1)

102-102: Runtime mapping present.

AUTH_EMAIL_RATE_LIMIT is wired into runtimeEnv correctly.

apps/web/src/app/api/auth/[...nextauth]/route.ts (1)

35-36: LGTM: delegate to NextAuth when not rate-limited.

Flow is preserved for all other requests.

Comment on lines 1 to +6
import NextAuth from "next-auth";

import { authOptions } from "~/server/auth";
import { env } from "~/env";
import { getRedis } from "~/server/redis";
import { logger } from "~/server/logger/log";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Force Node.js runtime to avoid Edge/ioredis incompatibility.

This route uses ioredis via getRedis(); ensure it never runs on the Edge runtime.

 import NextAuth from "next-auth";
import { authOptions } from "~/server/auth";
import { env } from "~/env";
import { getRedis } from "~/server/redis";
import { logger } from "~/server/logger/log";
++// ioredis requires Node.js runtime+export const runtime = "nodejs";
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
importNextAuthfrom"next-auth";
import{authOptions}from"~/server/auth";
import{env}from"~/env";
import{getRedis}from"~/server/redis";
import{logger}from"~/server/logger/log";
importNextAuthfrom"next-auth";
import{authOptions}from"~/server/auth";
import{env}from"~/env";
import{getRedis}from"~/server/redis";
import{logger}from"~/server/logger/log";
// ioredis requires Node.js runtime
exportconstruntime="nodejs";
🤖 Prompt for AI Agents
In apps/web/src/app/api/auth/[...nextauth]/route.ts around lines 1-6, this
Next.js route uses ioredis via getRedis and must not run on the Edge runtime;
add an exported runtime declaration at the top of the file that sets the runtime
to Node (e.g., export a constant named runtime with value 'node') so the route
always runs on the Node.js runtime, then verify imports remain unchanged and
redeploy.

Comment threadapps/web/src/app/api/auth/[...nextauth]/route.ts Outdated
Comment threadapps/web/src/env.js
Comment on lines +47 to +50
AUTH_EMAIL_RATE_LIMIT: z
.string()
.default("0")
.transform((str) => parseInt(str, 10)),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Harden numeric validation for AUTH_EMAIL_RATE_LIMIT (avoid NaN, catch bad input).

Current z.string().transform(parseInt) allows non-numeric strings to become NaN, silently disabling rate limiting. Coerce to a non-negative int.

- AUTH_EMAIL_RATE_LIMIT: z- .string()- .default("0")- .transform((str) => parseInt(str, 10)),+ AUTH_EMAIL_RATE_LIMIT: z.coerce.number().int().nonnegative().default(0),
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
AUTH_EMAIL_RATE_LIMIT: z
.string()
.default("0")
.transform((str)=>parseInt(str,10)),
AUTH_EMAIL_RATE_LIMIT: z.coerce.number().int().nonnegative().default(0),
🤖 Prompt for AI Agents
In apps/web/src/env.js around lines 47 to 50, the current AUTH_EMAIL_RATE_LIMIT
uses z.string().transform(parseInt) which can produce NaN for bad input; change
it to parse and validate as a non-negative integer: preprocess the raw string
into a Number (e.g., with Number(str) or parseInt but guard against NaN), then
validate with z.number().int().nonnegative().default(0) (or add a refine to
reject NaN) so invalid values fail validation or fall back to 0 instead of
becoming NaN.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (1)
apps/web/src/app/api/auth/[...nextauth]/route.ts (1)

1-6: Force Node runtime to avoid ioredis/Edge crash.

This route uses ioredis; without forcing Node.js runtime it can deploy to Edge and fail at runtime.

 import NextAuth from "next-auth";
import { authOptions } from "~/server/auth";
import { env } from "~/env";
import { getRedis } from "~/server/redis";
import { logger } from "~/server/logger/log";
++// ioredis requires Node.js runtime+export const runtime = "nodejs";

Run to confirm the runtime export exists:

#!/bin/bash
rg -nP 'export\\s+const\\s+runtime\\s*=\\s*"nodejs"' apps/web/src/app/api/auth/\.\.\.nextauth/route\.ts
🧹 Nitpick comments (2)
apps/web/src/app/api/auth/[...nextauth]/route.ts (2)

57-59: Handle trailing slash on pathname.

Support both /signin/email and /signin/email/.

- const url = new URL(req.url);- if (url.pathname.endsWith("/signin/email")) {+ const url = new URL(req.url);+ const pathname = url.pathname.replace(/\/+$/, "");+ if (pathname.endsWith("/signin/email")) {

72-80: Include Retry-After and no-store headers on 429.

Improves client/backoff behavior and caching semantics.

- return Response.json(+ return Response.json(
{
error: {
code: "RATE_LIMITED",
message: "Too many requests",
},
},
- { status: 429 }+ {+ status: 429,+ headers: {+ "Retry-After": String(ttl),+ "Cache-Control": "no-store",+ },+ }
);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8879ab7 and 59ced7a.

📒 Files selected for processing (1)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use 2-space indentation in TypeScript code (enforced by Prettier)
Use semicolons in TypeScript code (enforced by Prettier)
Do not use dynamic imports

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code with Prettier 3 via pnpm format for TypeScript and Markdown files

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

In apps/web, use the / alias for src imports (e.g., import { x } from "/utils/x")

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
🧬 Code graph analysis (1)
apps/web/src/app/api/auth/[...nextauth]/route.ts (3)
apps/web/src/env.js (2)
  • env (5-130)
  • env (5-130)
apps/web/src/server/logger/log.ts (1)
  • logger (31-63)
apps/web/src/server/redis.ts (1)
  • getRedis (6-13)
🔇 Additional comments (2)
apps/web/src/app/api/auth/[...nextauth]/route.ts (2)

10-10: GET re-export: LGTM.

Re-exporting GET to NextAuth handler is correct.


56-86: Overall POST flow: solid.

Gated on env flag, scoped to email sign-in, uses atomic INCR+EXPIRE, logs and gracefully degrades on RL errors. Nice.

Comment on lines +12 to +50
function getClientIp(req: Request): string | null {
const h = req.headers;
const direct =
h.get("x-forwarded-for") ??
h.get("x-real-ip") ??
h.get("cf-connecting-ip") ??
h.get("x-client-ip") ??
h.get("true-client-ip") ??
h.get("fastly-client-ip") ??
h.get("x-cluster-client-ip") ??
null;

let ip = direct?.split(",")[0]?.trim() ?? "";

if (!ip) {
const fwd = h.get("forwarded");
if (fwd) {
const first = fwd.split(",")[0];
const match = first?.match(/for=([^;]+)/i);
if (match && match[1]) {
const raw = match[1].trim().replace(/^"|"$/g, "");
if (raw.startsWith("[")) {
const end = raw.indexOf("]");
ip = end !== -1 ? raw.slice(1, end) : raw;
} else {
const parts = raw.split(":");
if (parts.length > 0 && parts[0]) {
ip =
parts.length === 2 && /^\d+(?:\.\d+){3}$/.test(parts[0])
? parts[0]
: raw;
}
}
}
}
}

return ip || null;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Harden client IP parsing and validate before use.

Unvalidated header values can include ports/garbage and create unbounded Redis keys. Normalize and validate as IP; skip RL if invalid.

 function getClientIp(req: Request): string | null {
const h = req.headers;
@@
- let ip = direct?.split(",")[0]?.trim() ?? "";+ let ip = direct?.split(",")[0]?.trim() ?? "";+ // Strip IPv4 port if present in XFF: "1.2.3.4:5678" -> "1.2.3.4"+ const colon = ip.lastIndexOf(":");+ if (ip && colon > -1 && ip.includes(".")) ip = ip.slice(0, colon);
@@
- return ip || null;+ // Validate; treat non-IP as missing+ // (isIP returns 0 for invalid, 4 for IPv4, 6 for IPv6)+ return ip && isIP(ip) !== 0 ? ip : null;
}

Add import (top of file):

import{isIP}from"node:net";
🤖 Prompt for AI Agents
In apps/web/src/app/api/auth/[...nextauth]/route.ts around lines 12 to 50, the
client IP parsing accepts unvalidated header values (including ports/garbage)
which can produce unbounded Redis keys; import isIP from node:net and after
extracting the candidate IP normalize it (strip surrounding quotes, remove IPv6
brackets, remove appended port if present), then validate it with
isIP(candidate) and only return the IP when isIP(...) > 0; otherwise return null
so downstream logic (rate limiting) is skipped for invalid values.

Comment on lines +66 to +67
const key = `auth-rl:${ip}`;
const ttl = 60;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Hash the key to prevent header-driven key explosion and key injection.

Using raw header text as part of the key allows unbounded cardinality and odd bytes. Hashing stabilizes size and characters.

- const key = `auth-rl:${ip}`;+ const key = `auth-rl:${createHash("sha256").update(ip).digest("hex")}`;

Add import (top of file):

import{createHash}from"node:crypto";
🤖 Prompt for AI Agents
In apps/web/src/app/api/auth/[...nextauth]/route.ts around lines 66 to 67, the
rate-limit key is built from the raw IP/header which can lead to unbounded
cardinality and strange bytes; replace that with a stable hashed value: add an
import for createHash from node:crypto at the top of the file, compute a
deterministic hex (or base64) hash of the ip/header before composing the key,
and use the hashed value in place of the raw ip when building the `auth-rl:` key
so the key size/charset is fixed and safe.

@KMKoushik
KMKoushik merged commit 9723c78 into mainSep 9, 2025
4 checks passed
@KMKoushik
KMKoushik deleted the codex/implement-rate-limit-on-signup/signin-forms branch September 9, 2025 13:09
@coderabbitaicoderabbitaiBot mentioned this pull request Dec 19, 2025
10 tasks
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@KMKoushik
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat: add auth email rate limit - #220

Merged
KMKoushik merged 4 commits into
mainfrom
codex/implement-rate-limit-on-signup/signin-forms
Sep 9, 2025
Merged

feat: add auth email rate limit#220
KMKoushik merged 4 commits into
mainfrom
codex/implement-rate-limit-on-signup/signin-forms

Conversation

@KMKoushik

@KMKoushikKMKoushik commented Sep 9, 2025

Copy link
Copy Markdown
Member

Summary

  • add Redis-backed rate limiting for auth email sign-in requests
  • add AUTH_EMAIL_RATE_LIMIT env var and document in examples

Testing

  • pnpm format
  • pnpm lint(fails: ESLint found too many warnings)
  • npx eslint src/app/api/auth/[...nextauth]/route.ts
  • pnpm build(fails: Invalid environment variables)

https://chatgpt.com/codex/tasks/task_e_68bfda4f4da4832994ca3aec44f385fc

Summary by CodeRabbit

  • New Features
    • Per-IP rate limiting for email sign-in: repeated attempts from the same IP may receive a “Too Many Requests” (429) response to curb abuse; inactive by default unless configured.
  • Chores
    • Environment samples and server runtime config updated to add AUTH_EMAIL_RATE_LIMIT (default 0) for straightforward setup and enabling of the rate limit.

@vercel

vercelBot commented Sep 9, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
unsend-marketingReadyReadyPreviewCommentSep 9, 2025 1:08pm

@coderabbitai

coderabbitaiBot commented Sep 9, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Adds AUTH_EMAIL_RATE_LIMIT to .env.example and .env.selfhost.example and to the server env schema and runtime mapping in apps/web/src/env.js. Replaces the blanket POST export in apps/web/src/app/api/auth/[...nextauth]/route.ts with a new export async function POST(req, ctx) that enforces Redis-backed per-IP rate limiting for POST /signin/email by incrementing auth-rl:<ip> with a 60s TTL and returning 429 when the configured limit is exceeded; non-rate-limited requests delegate to the existing NextAuth handler. GET remains exported as the original handler.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 59ced7a and 98dce11.

📒 Files selected for processing (1)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Cloudflare Pages

Pre-merge checks (2 passed, 1 warning)

❌ Failed checks (1 warning)
Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%.You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check nameStatusExplanation
Title Check✅ PassedThe title “feat: add auth email rate limit” concisely and accurately summarizes the primary change of the pull request, namely introducing rate limiting for authentication email sign-in, without extraneous detail or unrelated context.
Description Check✅ PassedThe description outlines the key enhancements—adding Redis-backed rate limiting and the new AUTH_EMAIL_RATE_LIMIT environment variable—and includes relevant testing steps, making it clearly related to the changeset.
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/implement-rate-limit-on-signup/signin-forms

Comment @coderabbitai help to get the list of available commands and usage tips.

@cloudflare-workers-and-pages

cloudflare-workers-and-pagesBot commented Sep 9, 2025

Copy link
Copy Markdown

Deploying usesend with Cloudflare Pages Cloudflare Pages

Latest commit:98dce11
Status: ✅ Deploy successful!
Preview URL:https://a7f0d9f7.usesend.pages.dev
Branch Preview URL:https://codex-implement-rate-limit-o.usesend.pages.dev

View logs

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (4)
.env.selfhost.example (1)

37-37: Alphabetize keys to satisfy dotenv-linter (and keep examples consistent).

Place AUTH_EMAIL_RATE_LIMIT before DOCKER_OUTPUT (and next to API_RATE_LIMIT).

Apply:

-DOCKER_OUTPUT=1-API_RATE_LIMIT=1-AUTH_EMAIL_RATE_LIMIT=5+API_RATE_LIMIT=1+AUTH_EMAIL_RATE_LIMIT=5+DOCKER_OUTPUT=1
apps/web/src/app/api/auth/[...nextauth]/route.ts (3)

21-26: Atomic TTL set (optional): use EXPIRE NX in a pipeline.

Your pattern is fine; using EXPIRE with NX ensures TTL is attached only on first creation without relying on count === 1.

- const count = await redis.incr(key);- if (count === 1) await redis.expire(key, ttl);+ const [[, count]] = await redis+ .multi()+ .incr(key)+ // Redis >=7 supports EXPIRE key seconds NX+ .expire(key, ttl, "NX")+ .exec();

27-29: Include rate-limit headers and a Retry-After hint.

Improves client/backoff behavior and observability.

- return new Response("Too many requests", { status: 429 });+ const retryAfter = "60";+ return new Response(+ JSON.stringify({ error: "Too many requests" }),+ {+ status: 429,+ headers: {+ "Content-Type": "application/json",+ "Retry-After": retryAfter,+ "X-RateLimit-Limit": String(env.AUTH_EMAIL_RATE_LIMIT),+ "X-RateLimit-Remaining": "0",+ "X-RateLimit-Reset": retryAfter,+ },+ },+ );

30-32: Log with consistent shape and include IP for failures.

Add ip to error context for parity with the warn path.

- logger.error({ err: error }, "Auth email rate limit failed");+ logger.error({ err: error, ip: (req.headers.get("x-forwarded-for") ?? req.headers.get("x-real-ip") ?? "").split(",")[0]?.trim() }, "Auth email rate limit failed");
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7cf4610 and bd5bde8.

📒 Files selected for processing (4)
  • .env.example (1 hunks)
  • .env.selfhost.example (1 hunks)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts (1 hunks)
  • apps/web/src/env.js (2 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
.env*

📄 CodeRabbit inference engine (AGENTS.md)

Environment configuration files must live at the repository root and be named .env*

Files:

  • .env.selfhost.example
  • .env.example
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/env.js
  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use 2-space indentation in TypeScript code (enforced by Prettier)
Use semicolons in TypeScript code (enforced by Prettier)
Do not use dynamic imports

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code with Prettier 3 via pnpm format for TypeScript and Markdown files

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

In apps/web, use the / alias for src imports (e.g., import { x } from "/utils/x")

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
🧬 Code graph analysis (1)
apps/web/src/app/api/auth/[...nextauth]/route.ts (3)
apps/web/src/env.js (2)
  • env (5-130)
  • env (5-130)
apps/web/src/server/redis.ts (1)
  • getRedis (6-13)
apps/web/src/server/logger/log.ts (1)
  • logger (31-63)
🪛 dotenv-linter (3.3.0)
.env.selfhost.example

[warning] 37-37: [UnorderedKey] The AUTH_EMAIL_RATE_LIMIT key should go before the DOCKER_OUTPUT key

(UnorderedKey)

🔇 Additional comments (3)
.env.example (1)

23-23: LGTM: new variable documented.

AUTH_EMAIL_RATE_LIMIT is added and grouped with API_RATE_LIMIT; matches env.js schema.

apps/web/src/env.js (1)

102-102: Runtime mapping present.

AUTH_EMAIL_RATE_LIMIT is wired into runtimeEnv correctly.

apps/web/src/app/api/auth/[...nextauth]/route.ts (1)

35-36: LGTM: delegate to NextAuth when not rate-limited.

Flow is preserved for all other requests.

Comment on lines 1 to +6
import NextAuth from "next-auth";

import { authOptions } from "~/server/auth";
import { env } from "~/env";
import { getRedis } from "~/server/redis";
import { logger } from "~/server/logger/log";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Force Node.js runtime to avoid Edge/ioredis incompatibility.

This route uses ioredis via getRedis(); ensure it never runs on the Edge runtime.

 import NextAuth from "next-auth";
import { authOptions } from "~/server/auth";
import { env } from "~/env";
import { getRedis } from "~/server/redis";
import { logger } from "~/server/logger/log";
++// ioredis requires Node.js runtime+export const runtime = "nodejs";
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
importNextAuthfrom"next-auth";
import{authOptions}from"~/server/auth";
import{env}from"~/env";
import{getRedis}from"~/server/redis";
import{logger}from"~/server/logger/log";
importNextAuthfrom"next-auth";
import{authOptions}from"~/server/auth";
import{env}from"~/env";
import{getRedis}from"~/server/redis";
import{logger}from"~/server/logger/log";
// ioredis requires Node.js runtime
exportconstruntime="nodejs";
🤖 Prompt for AI Agents
In apps/web/src/app/api/auth/[...nextauth]/route.ts around lines 1-6, this
Next.js route uses ioredis via getRedis and must not run on the Edge runtime;
add an exported runtime declaration at the top of the file that sets the runtime
to Node (e.g., export a constant named runtime with value 'node') so the route
always runs on the Node.js runtime, then verify imports remain unchanged and
redeploy.

Comment threadapps/web/src/app/api/auth/[...nextauth]/route.ts Outdated
Comment threadapps/web/src/env.js
Comment on lines +47 to +50
AUTH_EMAIL_RATE_LIMIT: z
.string()
.default("0")
.transform((str) => parseInt(str, 10)),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Harden numeric validation for AUTH_EMAIL_RATE_LIMIT (avoid NaN, catch bad input).

Current z.string().transform(parseInt) allows non-numeric strings to become NaN, silently disabling rate limiting. Coerce to a non-negative int.

- AUTH_EMAIL_RATE_LIMIT: z- .string()- .default("0")- .transform((str) => parseInt(str, 10)),+ AUTH_EMAIL_RATE_LIMIT: z.coerce.number().int().nonnegative().default(0),
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
AUTH_EMAIL_RATE_LIMIT: z
.string()
.default("0")
.transform((str)=>parseInt(str,10)),
AUTH_EMAIL_RATE_LIMIT: z.coerce.number().int().nonnegative().default(0),
🤖 Prompt for AI Agents
In apps/web/src/env.js around lines 47 to 50, the current AUTH_EMAIL_RATE_LIMIT
uses z.string().transform(parseInt) which can produce NaN for bad input; change
it to parse and validate as a non-negative integer: preprocess the raw string
into a Number (e.g., with Number(str) or parseInt but guard against NaN), then
validate with z.number().int().nonnegative().default(0) (or add a refine to
reject NaN) so invalid values fail validation or fall back to 0 instead of
becoming NaN.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (1)
apps/web/src/app/api/auth/[...nextauth]/route.ts (1)

1-6: Force Node runtime to avoid ioredis/Edge crash.

This route uses ioredis; without forcing Node.js runtime it can deploy to Edge and fail at runtime.

 import NextAuth from "next-auth";
import { authOptions } from "~/server/auth";
import { env } from "~/env";
import { getRedis } from "~/server/redis";
import { logger } from "~/server/logger/log";
++// ioredis requires Node.js runtime+export const runtime = "nodejs";

Run to confirm the runtime export exists:

#!/bin/bash
rg -nP 'export\\s+const\\s+runtime\\s*=\\s*"nodejs"' apps/web/src/app/api/auth/\.\.\.nextauth/route\.ts
🧹 Nitpick comments (2)
apps/web/src/app/api/auth/[...nextauth]/route.ts (2)

57-59: Handle trailing slash on pathname.

Support both /signin/email and /signin/email/.

- const url = new URL(req.url);- if (url.pathname.endsWith("/signin/email")) {+ const url = new URL(req.url);+ const pathname = url.pathname.replace(/\/+$/, "");+ if (pathname.endsWith("/signin/email")) {

72-80: Include Retry-After and no-store headers on 429.

Improves client/backoff behavior and caching semantics.

- return Response.json(+ return Response.json(
{
error: {
code: "RATE_LIMITED",
message: "Too many requests",
},
},
- { status: 429 }+ {+ status: 429,+ headers: {+ "Retry-After": String(ttl),+ "Cache-Control": "no-store",+ },+ }
);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8879ab7 and 59ced7a.

📒 Files selected for processing (1)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use 2-space indentation in TypeScript code (enforced by Prettier)
Use semicolons in TypeScript code (enforced by Prettier)
Do not use dynamic imports

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code with Prettier 3 via pnpm format for TypeScript and Markdown files

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

In apps/web, use the / alias for src imports (e.g., import { x } from "/utils/x")

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
🧬 Code graph analysis (1)
apps/web/src/app/api/auth/[...nextauth]/route.ts (3)
apps/web/src/env.js (2)
  • env (5-130)
  • env (5-130)
apps/web/src/server/logger/log.ts (1)
  • logger (31-63)
apps/web/src/server/redis.ts (1)
  • getRedis (6-13)
🔇 Additional comments (2)
apps/web/src/app/api/auth/[...nextauth]/route.ts (2)

10-10: GET re-export: LGTM.

Re-exporting GET to NextAuth handler is correct.


56-86: Overall POST flow: solid.

Gated on env flag, scoped to email sign-in, uses atomic INCR+EXPIRE, logs and gracefully degrades on RL errors. Nice.

Comment on lines +12 to +50
function getClientIp(req: Request): string | null {
const h = req.headers;
const direct =
h.get("x-forwarded-for") ??
h.get("x-real-ip") ??
h.get("cf-connecting-ip") ??
h.get("x-client-ip") ??
h.get("true-client-ip") ??
h.get("fastly-client-ip") ??
h.get("x-cluster-client-ip") ??
null;

let ip = direct?.split(",")[0]?.trim() ?? "";

if (!ip) {
const fwd = h.get("forwarded");
if (fwd) {
const first = fwd.split(",")[0];
const match = first?.match(/for=([^;]+)/i);
if (match && match[1]) {
const raw = match[1].trim().replace(/^"|"$/g, "");
if (raw.startsWith("[")) {
const end = raw.indexOf("]");
ip = end !== -1 ? raw.slice(1, end) : raw;
} else {
const parts = raw.split(":");
if (parts.length > 0 && parts[0]) {
ip =
parts.length === 2 && /^\d+(?:\.\d+){3}$/.test(parts[0])
? parts[0]
: raw;
}
}
}
}
}

return ip || null;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Harden client IP parsing and validate before use.

Unvalidated header values can include ports/garbage and create unbounded Redis keys. Normalize and validate as IP; skip RL if invalid.

 function getClientIp(req: Request): string | null {
const h = req.headers;
@@
- let ip = direct?.split(",")[0]?.trim() ?? "";+ let ip = direct?.split(",")[0]?.trim() ?? "";+ // Strip IPv4 port if present in XFF: "1.2.3.4:5678" -> "1.2.3.4"+ const colon = ip.lastIndexOf(":");+ if (ip && colon > -1 && ip.includes(".")) ip = ip.slice(0, colon);
@@
- return ip || null;+ // Validate; treat non-IP as missing+ // (isIP returns 0 for invalid, 4 for IPv4, 6 for IPv6)+ return ip && isIP(ip) !== 0 ? ip : null;
}

Add import (top of file):

import{isIP}from"node:net";
🤖 Prompt for AI Agents
In apps/web/src/app/api/auth/[...nextauth]/route.ts around lines 12 to 50, the
client IP parsing accepts unvalidated header values (including ports/garbage)
which can produce unbounded Redis keys; import isIP from node:net and after
extracting the candidate IP normalize it (strip surrounding quotes, remove IPv6
brackets, remove appended port if present), then validate it with
isIP(candidate) and only return the IP when isIP(...) > 0; otherwise return null
so downstream logic (rate limiting) is skipped for invalid values.

Comment on lines +66 to +67
const key = `auth-rl:${ip}`;
const ttl = 60;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Hash the key to prevent header-driven key explosion and key injection.

Using raw header text as part of the key allows unbounded cardinality and odd bytes. Hashing stabilizes size and characters.

- const key = `auth-rl:${ip}`;+ const key = `auth-rl:${createHash("sha256").update(ip).digest("hex")}`;

Add import (top of file):

import{createHash}from"node:crypto";
🤖 Prompt for AI Agents
In apps/web/src/app/api/auth/[...nextauth]/route.ts around lines 66 to 67, the
rate-limit key is built from the raw IP/header which can lead to unbounded
cardinality and strange bytes; replace that with a stable hashed value: add an
import for createHash from node:crypto at the top of the file, compute a
deterministic hex (or base64) hash of the ip/header before composing the key,
and use the hashed value in place of the raw ip when building the `auth-rl:` key
so the key size/charset is fixed and safe.

@KMKoushik
KMKoushik merged commit 9723c78 into mainSep 9, 2025
4 checks passed
@KMKoushik
KMKoushik deleted the codex/implement-rate-limit-on-signup/signin-forms branch September 9, 2025 13:09
@coderabbitaicoderabbitaiBot mentioned this pull request Dec 19, 2025
10 tasks
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@KMKoushik
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

feat: add auth email rate limit - #220

Merged
KMKoushik merged 4 commits into
mainfrom
codex/implement-rate-limit-on-signup/signin-forms
Sep 9, 2025
Merged

feat: add auth email rate limit#220
KMKoushik merged 4 commits into
mainfrom
codex/implement-rate-limit-on-signup/signin-forms

Conversation

@KMKoushik

@KMKoushikKMKoushik commented Sep 9, 2025

Copy link
Copy Markdown
Member

Summary

  • add Redis-backed rate limiting for auth email sign-in requests
  • add AUTH_EMAIL_RATE_LIMIT env var and document in examples

Testing

  • pnpm format
  • pnpm lint(fails: ESLint found too many warnings)
  • npx eslint src/app/api/auth/[...nextauth]/route.ts
  • pnpm build(fails: Invalid environment variables)

https://chatgpt.com/codex/tasks/task_e_68bfda4f4da4832994ca3aec44f385fc

Summary by CodeRabbit

  • New Features
    • Per-IP rate limiting for email sign-in: repeated attempts from the same IP may receive a “Too Many Requests” (429) response to curb abuse; inactive by default unless configured.
  • Chores
    • Environment samples and server runtime config updated to add AUTH_EMAIL_RATE_LIMIT (default 0) for straightforward setup and enabling of the rate limit.

@vercel

vercelBot commented Sep 9, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
unsend-marketingReadyReadyPreviewCommentSep 9, 2025 1:08pm

@coderabbitai

coderabbitaiBot commented Sep 9, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Adds AUTH_EMAIL_RATE_LIMIT to .env.example and .env.selfhost.example and to the server env schema and runtime mapping in apps/web/src/env.js. Replaces the blanket POST export in apps/web/src/app/api/auth/[...nextauth]/route.ts with a new export async function POST(req, ctx) that enforces Redis-backed per-IP rate limiting for POST /signin/email by incrementing auth-rl:<ip> with a 60s TTL and returning 429 when the configured limit is exceeded; non-rate-limited requests delegate to the existing NextAuth handler. GET remains exported as the original handler.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 59ced7a and 98dce11.

📒 Files selected for processing (1)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Cloudflare Pages

Pre-merge checks (2 passed, 1 warning)

❌ Failed checks (1 warning)
Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%.You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check nameStatusExplanation
Title Check✅ PassedThe title “feat: add auth email rate limit” concisely and accurately summarizes the primary change of the pull request, namely introducing rate limiting for authentication email sign-in, without extraneous detail or unrelated context.
Description Check✅ PassedThe description outlines the key enhancements—adding Redis-backed rate limiting and the new AUTH_EMAIL_RATE_LIMIT environment variable—and includes relevant testing steps, making it clearly related to the changeset.
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/implement-rate-limit-on-signup/signin-forms

Comment @coderabbitai help to get the list of available commands and usage tips.

@cloudflare-workers-and-pages

cloudflare-workers-and-pagesBot commented Sep 9, 2025

Copy link
Copy Markdown

Deploying usesend with Cloudflare Pages Cloudflare Pages

Latest commit:98dce11
Status: ✅ Deploy successful!
Preview URL:https://a7f0d9f7.usesend.pages.dev
Branch Preview URL:https://codex-implement-rate-limit-o.usesend.pages.dev

View logs

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (4)
.env.selfhost.example (1)

37-37: Alphabetize keys to satisfy dotenv-linter (and keep examples consistent).

Place AUTH_EMAIL_RATE_LIMIT before DOCKER_OUTPUT (and next to API_RATE_LIMIT).

Apply:

-DOCKER_OUTPUT=1-API_RATE_LIMIT=1-AUTH_EMAIL_RATE_LIMIT=5+API_RATE_LIMIT=1+AUTH_EMAIL_RATE_LIMIT=5+DOCKER_OUTPUT=1
apps/web/src/app/api/auth/[...nextauth]/route.ts (3)

21-26: Atomic TTL set (optional): use EXPIRE NX in a pipeline.

Your pattern is fine; using EXPIRE with NX ensures TTL is attached only on first creation without relying on count === 1.

- const count = await redis.incr(key);- if (count === 1) await redis.expire(key, ttl);+ const [[, count]] = await redis+ .multi()+ .incr(key)+ // Redis >=7 supports EXPIRE key seconds NX+ .expire(key, ttl, "NX")+ .exec();

27-29: Include rate-limit headers and a Retry-After hint.

Improves client/backoff behavior and observability.

- return new Response("Too many requests", { status: 429 });+ const retryAfter = "60";+ return new Response(+ JSON.stringify({ error: "Too many requests" }),+ {+ status: 429,+ headers: {+ "Content-Type": "application/json",+ "Retry-After": retryAfter,+ "X-RateLimit-Limit": String(env.AUTH_EMAIL_RATE_LIMIT),+ "X-RateLimit-Remaining": "0",+ "X-RateLimit-Reset": retryAfter,+ },+ },+ );

30-32: Log with consistent shape and include IP for failures.

Add ip to error context for parity with the warn path.

- logger.error({ err: error }, "Auth email rate limit failed");+ logger.error({ err: error, ip: (req.headers.get("x-forwarded-for") ?? req.headers.get("x-real-ip") ?? "").split(",")[0]?.trim() }, "Auth email rate limit failed");
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7cf4610 and bd5bde8.

📒 Files selected for processing (4)
  • .env.example (1 hunks)
  • .env.selfhost.example (1 hunks)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts (1 hunks)
  • apps/web/src/env.js (2 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
.env*

📄 CodeRabbit inference engine (AGENTS.md)

Environment configuration files must live at the repository root and be named .env*

Files:

  • .env.selfhost.example
  • .env.example
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/env.js
  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use 2-space indentation in TypeScript code (enforced by Prettier)
Use semicolons in TypeScript code (enforced by Prettier)
Do not use dynamic imports

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code with Prettier 3 via pnpm format for TypeScript and Markdown files

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

In apps/web, use the / alias for src imports (e.g., import { x } from "/utils/x")

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
🧬 Code graph analysis (1)
apps/web/src/app/api/auth/[...nextauth]/route.ts (3)
apps/web/src/env.js (2)
  • env (5-130)
  • env (5-130)
apps/web/src/server/redis.ts (1)
  • getRedis (6-13)
apps/web/src/server/logger/log.ts (1)
  • logger (31-63)
🪛 dotenv-linter (3.3.0)
.env.selfhost.example

[warning] 37-37: [UnorderedKey] The AUTH_EMAIL_RATE_LIMIT key should go before the DOCKER_OUTPUT key

(UnorderedKey)

🔇 Additional comments (3)
.env.example (1)

23-23: LGTM: new variable documented.

AUTH_EMAIL_RATE_LIMIT is added and grouped with API_RATE_LIMIT; matches env.js schema.

apps/web/src/env.js (1)

102-102: Runtime mapping present.

AUTH_EMAIL_RATE_LIMIT is wired into runtimeEnv correctly.

apps/web/src/app/api/auth/[...nextauth]/route.ts (1)

35-36: LGTM: delegate to NextAuth when not rate-limited.

Flow is preserved for all other requests.

Comment on lines 1 to +6
import NextAuth from "next-auth";

import { authOptions } from "~/server/auth";
import { env } from "~/env";
import { getRedis } from "~/server/redis";
import { logger } from "~/server/logger/log";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Force Node.js runtime to avoid Edge/ioredis incompatibility.

This route uses ioredis via getRedis(); ensure it never runs on the Edge runtime.

 import NextAuth from "next-auth";
import { authOptions } from "~/server/auth";
import { env } from "~/env";
import { getRedis } from "~/server/redis";
import { logger } from "~/server/logger/log";
++// ioredis requires Node.js runtime+export const runtime = "nodejs";
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
importNextAuthfrom"next-auth";
import{authOptions}from"~/server/auth";
import{env}from"~/env";
import{getRedis}from"~/server/redis";
import{logger}from"~/server/logger/log";
importNextAuthfrom"next-auth";
import{authOptions}from"~/server/auth";
import{env}from"~/env";
import{getRedis}from"~/server/redis";
import{logger}from"~/server/logger/log";
// ioredis requires Node.js runtime
exportconstruntime="nodejs";
🤖 Prompt for AI Agents
In apps/web/src/app/api/auth/[...nextauth]/route.ts around lines 1-6, this
Next.js route uses ioredis via getRedis and must not run on the Edge runtime;
add an exported runtime declaration at the top of the file that sets the runtime
to Node (e.g., export a constant named runtime with value 'node') so the route
always runs on the Node.js runtime, then verify imports remain unchanged and
redeploy.

Comment threadapps/web/src/app/api/auth/[...nextauth]/route.ts Outdated
Comment threadapps/web/src/env.js
Comment on lines +47 to +50
AUTH_EMAIL_RATE_LIMIT: z
.string()
.default("0")
.transform((str) => parseInt(str, 10)),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Harden numeric validation for AUTH_EMAIL_RATE_LIMIT (avoid NaN, catch bad input).

Current z.string().transform(parseInt) allows non-numeric strings to become NaN, silently disabling rate limiting. Coerce to a non-negative int.

- AUTH_EMAIL_RATE_LIMIT: z- .string()- .default("0")- .transform((str) => parseInt(str, 10)),+ AUTH_EMAIL_RATE_LIMIT: z.coerce.number().int().nonnegative().default(0),
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
AUTH_EMAIL_RATE_LIMIT: z
.string()
.default("0")
.transform((str)=>parseInt(str,10)),
AUTH_EMAIL_RATE_LIMIT: z.coerce.number().int().nonnegative().default(0),
🤖 Prompt for AI Agents
In apps/web/src/env.js around lines 47 to 50, the current AUTH_EMAIL_RATE_LIMIT
uses z.string().transform(parseInt) which can produce NaN for bad input; change
it to parse and validate as a non-negative integer: preprocess the raw string
into a Number (e.g., with Number(str) or parseInt but guard against NaN), then
validate with z.number().int().nonnegative().default(0) (or add a refine to
reject NaN) so invalid values fail validation or fall back to 0 instead of
becoming NaN.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (1)
apps/web/src/app/api/auth/[...nextauth]/route.ts (1)

1-6: Force Node runtime to avoid ioredis/Edge crash.

This route uses ioredis; without forcing Node.js runtime it can deploy to Edge and fail at runtime.

 import NextAuth from "next-auth";
import { authOptions } from "~/server/auth";
import { env } from "~/env";
import { getRedis } from "~/server/redis";
import { logger } from "~/server/logger/log";
++// ioredis requires Node.js runtime+export const runtime = "nodejs";

Run to confirm the runtime export exists:

#!/bin/bash
rg -nP 'export\\s+const\\s+runtime\\s*=\\s*"nodejs"' apps/web/src/app/api/auth/\.\.\.nextauth/route\.ts
🧹 Nitpick comments (2)
apps/web/src/app/api/auth/[...nextauth]/route.ts (2)

57-59: Handle trailing slash on pathname.

Support both /signin/email and /signin/email/.

- const url = new URL(req.url);- if (url.pathname.endsWith("/signin/email")) {+ const url = new URL(req.url);+ const pathname = url.pathname.replace(/\/+$/, "");+ if (pathname.endsWith("/signin/email")) {

72-80: Include Retry-After and no-store headers on 429.

Improves client/backoff behavior and caching semantics.

- return Response.json(+ return Response.json(
{
error: {
code: "RATE_LIMITED",
message: "Too many requests",
},
},
- { status: 429 }+ {+ status: 429,+ headers: {+ "Retry-After": String(ttl),+ "Cache-Control": "no-store",+ },+ }
);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8879ab7 and 59ced7a.

📒 Files selected for processing (1)
  • apps/web/src/app/api/auth/[...nextauth]/route.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Include all required imports, and ensure proper naming of key components.

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use 2-space indentation in TypeScript code (enforced by Prettier)
Use semicolons in TypeScript code (enforced by Prettier)
Do not use dynamic imports

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
**/*.{ts,tsx,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code with Prettier 3 via pnpm format for TypeScript and Markdown files

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

In apps/web, use the / alias for src imports (e.g., import { x } from "/utils/x")

Files:

  • apps/web/src/app/api/auth/[...nextauth]/route.ts
🧬 Code graph analysis (1)
apps/web/src/app/api/auth/[...nextauth]/route.ts (3)
apps/web/src/env.js (2)
  • env (5-130)
  • env (5-130)
apps/web/src/server/logger/log.ts (1)
  • logger (31-63)
apps/web/src/server/redis.ts (1)
  • getRedis (6-13)
🔇 Additional comments (2)
apps/web/src/app/api/auth/[...nextauth]/route.ts (2)

10-10: GET re-export: LGTM.

Re-exporting GET to NextAuth handler is correct.


56-86: Overall POST flow: solid.

Gated on env flag, scoped to email sign-in, uses atomic INCR+EXPIRE, logs and gracefully degrades on RL errors. Nice.

Comment on lines +12 to +50
function getClientIp(req: Request): string | null {
const h = req.headers;
const direct =
h.get("x-forwarded-for") ??
h.get("x-real-ip") ??
h.get("cf-connecting-ip") ??
h.get("x-client-ip") ??
h.get("true-client-ip") ??
h.get("fastly-client-ip") ??
h.get("x-cluster-client-ip") ??
null;

let ip = direct?.split(",")[0]?.trim() ?? "";

if (!ip) {
const fwd = h.get("forwarded");
if (fwd) {
const first = fwd.split(",")[0];
const match = first?.match(/for=([^;]+)/i);
if (match && match[1]) {
const raw = match[1].trim().replace(/^"|"$/g, "");
if (raw.startsWith("[")) {
const end = raw.indexOf("]");
ip = end !== -1 ? raw.slice(1, end) : raw;
} else {
const parts = raw.split(":");
if (parts.length > 0 && parts[0]) {
ip =
parts.length === 2 && /^\d+(?:\.\d+){3}$/.test(parts[0])
? parts[0]
: raw;
}
}
}
}
}

return ip || null;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Harden client IP parsing and validate before use.

Unvalidated header values can include ports/garbage and create unbounded Redis keys. Normalize and validate as IP; skip RL if invalid.

 function getClientIp(req: Request): string | null {
const h = req.headers;
@@
- let ip = direct?.split(",")[0]?.trim() ?? "";+ let ip = direct?.split(",")[0]?.trim() ?? "";+ // Strip IPv4 port if present in XFF: "1.2.3.4:5678" -> "1.2.3.4"+ const colon = ip.lastIndexOf(":");+ if (ip && colon > -1 && ip.includes(".")) ip = ip.slice(0, colon);
@@
- return ip || null;+ // Validate; treat non-IP as missing+ // (isIP returns 0 for invalid, 4 for IPv4, 6 for IPv6)+ return ip && isIP(ip) !== 0 ? ip : null;
}

Add import (top of file):

import{isIP}from"node:net";
🤖 Prompt for AI Agents
In apps/web/src/app/api/auth/[...nextauth]/route.ts around lines 12 to 50, the
client IP parsing accepts unvalidated header values (including ports/garbage)
which can produce unbounded Redis keys; import isIP from node:net and after
extracting the candidate IP normalize it (strip surrounding quotes, remove IPv6
brackets, remove appended port if present), then validate it with
isIP(candidate) and only return the IP when isIP(...) > 0; otherwise return null
so downstream logic (rate limiting) is skipped for invalid values.

Comment on lines +66 to +67
const key = `auth-rl:${ip}`;
const ttl = 60;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Hash the key to prevent header-driven key explosion and key injection.

Using raw header text as part of the key allows unbounded cardinality and odd bytes. Hashing stabilizes size and characters.

- const key = `auth-rl:${ip}`;+ const key = `auth-rl:${createHash("sha256").update(ip).digest("hex")}`;

Add import (top of file):

import{createHash}from"node:crypto";
🤖 Prompt for AI Agents
In apps/web/src/app/api/auth/[...nextauth]/route.ts around lines 66 to 67, the
rate-limit key is built from the raw IP/header which can lead to unbounded
cardinality and strange bytes; replace that with a stable hashed value: add an
import for createHash from node:crypto at the top of the file, compute a
deterministic hex (or base64) hash of the ip/header before composing the key,
and use the hashed value in place of the raw ip when building the `auth-rl:` key
so the key size/charset is fixed and safe.

@KMKoushik
KMKoushik merged commit 9723c78 into mainSep 9, 2025
4 checks passed
@KMKoushik
KMKoushik deleted the codex/implement-rate-limit-on-signup/signin-forms branch September 9, 2025 13:09
@coderabbitaicoderabbitaiBot mentioned this pull request Dec 19, 2025
10 tasks
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@KMKoushik