Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ jobs:
fetch-depth: 0

- uses: pnpm/action-setup@v6
with:
version: 11.14.0

- uses: actions/setup-node@v7
with:
Expand Down Expand Up @@ -134,6 +136,8 @@ jobs:
- uses: actions/checkout@v7

- uses: pnpm/action-setup@v6
with:
version: 11.14.0

- uses: actions/setup-node@v7
with:
Expand Down Expand Up @@ -196,6 +200,8 @@ jobs:
- uses: actions/checkout@v7

- uses: pnpm/action-setup@v6
with:
version: 11.14.0

- uses: actions/setup-node@v7
with:
Expand Down
2 changes: 2 additions & 0 deletions .github/workflows/sentry-alert.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ jobs:
- uses: actions/checkout@v7

- uses: pnpm/action-setup@v6
with:
version: 11.14.0

- uses: actions/setup-node@v7
with:
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,5 +72,5 @@
"eslint --fix"
]
},
"packageManager": "pnpm@11.13.0+sha512.88d94724d8f2e6c186744a5584c6e59ecac869ec7ba15e9cb4cd628e8dc7066820b2481d8ee3b51ea8da323a7378068aa58c556a3720d32b7c20a051d088363a"
"packageManager": "pnpm@11.14.0"
}
10 changes: 5 additions & 5 deletions src/app/actions/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
getSession,
} from '@/lib/auth';
import { logger } from '@/lib/logger';
import { rateLimit } from '@/lib/rate-limit';
import { rateLimitDual } from '@/lib/rate-limit';
import {
hashClaimToken,
PLACEHOLDER_PASSWORD_PREFIX,
Expand All @@ -32,7 +32,7 @@ import {
// ---------------------------------------------------------------------------

export const signUpAction = createSafeAction(signUpSchema, async (data) => {
const rl = rateLimit(`signup:${data.email.toLowerCase()}`, 5, 60_000);
const rl = await rateLimitDual('signup', data.email.toLowerCase());
if (!rl.allowed) {
throw new Error(`Too many attempts. Try again in ${rl.retryAfterSeconds}s.`);
}
Expand Down Expand Up @@ -123,9 +123,9 @@ export const signUpAction = createSafeAction(signUpSchema, async (data) => {
// ---------------------------------------------------------------------------

export const signInAction = createSafeAction(signInSchema, async (data) => {
// Rate-limit BEFORE any DB or scrypt work β€” the sync scrypt verify is
// exactly what an attacker would use to burn the event loop.
const rl = rateLimit(`signin:${data.email.toLowerCase()}`, 5, 60_000);
// Rate-limit BEFORE any DB or scrypt work β€” dual rate limit checks IP first,
// then target email, blunting brute force, account lockout DoS, and loop abuse.
const rl = await rateLimitDual('signin', data.email.toLowerCase());
if (!rl.allowed) {
throw new Error(`Too many attempts. Try again in ${rl.retryAfterSeconds}s.`);
}
Expand Down
53 changes: 53 additions & 0 deletions src/lib/__tests__/rate-limit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { rateLimit, rateLimitDual, resetRateLimits } from '../rate-limit';

// Mock next/headers
vi.mock('next/headers', () => ({
headers: vi.fn().mockResolvedValue({
get: (header: string) => {
if (header === 'x-forwarded-for') return '192.168.1.100, 10.0.0.1';
if (header === 'x-real-ip') return '192.168.1.100';
return null;
},
}),
}));

describe('rate-limit module', () => {
beforeEach(() => {
resetRateLimits();
});

describe('rateLimit', () => {
it('allows hits up to limit and blocks subsequent hits', () => {
for (let i = 0; i < 3; i++) {
const res = rateLimit('test-key', 3, 60_000);
expect(res.allowed).toBe(true);
}
const blocked = rateLimit('test-key', 3, 60_000);
expect(blocked.allowed).toBe(false);
expect(blocked.retryAfterSeconds).toBeGreaterThan(0);
});
});

describe('rateLimitDual', () => {
it('enforces target rate limit when IP is within bounds', async () => {
const email = 'user@example.com';
for (let i = 0; i < 5; i++) {
const res = await rateLimitDual('signin', email, { limit: 5, ipLimit: 10 });
expect(res.allowed).toBe(true);
}
const blocked = await rateLimitDual('signin', email, { limit: 5, ipLimit: 10 });
expect(blocked.allowed).toBe(false);
});

it('enforces IP rate limit prior to target limit', async () => {
for (let i = 0; i < 3; i++) {
const res = await rateLimitDual('signin', `user${i}@example.com`, { limit: 5, ipLimit: 3 });
expect(res.allowed).toBe(true);
}
// IP limit reached (3 hits from 192.168.1.100)
const blockedByIp = await rateLimitDual('signin', 'newuser@example.com', { limit: 5, ipLimit: 3 });
expect(blockedByIp.allowed).toBe(false);
});
});
});
61 changes: 61 additions & 0 deletions src/lib/rate-limit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
*/

import 'server-only';
import { headers } from 'next/headers';

const buckets = new Map<string, number[]>();

Expand All @@ -17,6 +18,41 @@ export interface RateLimitResult {
retryAfterSeconds: number;
}

export interface RateLimitOptions {
/** Maximum hits for the target key (default: 5) */
limit?: number;
/** Maximum hits for the client IP (default: 10) */
ipLimit?: number;
/** Sliding window duration in ms (default: 60,000 / 1 min) */
windowMs?: number;
}

/**
* Resets all rate-limiting buckets. Intended for unit tests.
*/
export function resetRateLimits(): void {
buckets.clear();
}

/**
* Retrieve client IP address from incoming HTTP headers safely.
*/
export async function getClientIp(): Promise<string | null> {
try {
const reqHeaders = await headers();
const xff = reqHeaders.get('x-forwarded-for');
if (xff) {
const clientIp = xff.split(',')[0]?.trim();
if (clientIp) return clientIp;
}
const realIp = reqHeaders.get('x-real-ip');
if (realIp) return realIp.trim();
} catch {
// headers() throws if called outside request context
}
return null;
}

/**
* Record a hit for `key` and report whether it stays within `limit` hits
* per `windowMs`. Denied hits are not recorded (a blocked attacker doesn't
Expand Down Expand Up @@ -47,3 +83,28 @@ export function rateLimit(key: string, limit = 5, windowMs = 60_000): RateLimitR

return { allowed: true, retryAfterSeconds: 0 };
}

/**
* Dual rate-limiter that checks both client IP and target key (e.g. email).
* Crucially, IP limit is evaluated FIRST to prevent an IP-blocked attacker
* from consuming or polluting target-based buckets (preventing Account Lockout DoS).
*/
export async function rateLimitDual(
actionPrefix: string,
targetKey: string,
options: RateLimitOptions = {},
): Promise<RateLimitResult> {
const windowMs = options.windowMs ?? 60_000;
const targetLimit = options.limit ?? 5;
const ipLimit = options.ipLimit ?? 10;

const ip = await getClientIp();
if (ip) {
const ipRes = rateLimit(`${actionPrefix}:ip:${ip}`, ipLimit, windowMs);
if (!ipRes.allowed) {
return ipRes;
}
}

return rateLimit(`${actionPrefix}:target:${targetKey}`, targetLimit, windowMs);
}