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
5 changes: 3 additions & 2 deletions middleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ describe('middleware', () => {
expect(rateLimit).toHaveBeenCalledWith('127.0.0.1', 60, 60000);
});

it('prefers x-forwarded-for over x-real-ip', async () => {
it('prefers x-real-ip over x-forwarded-for to prevent spoofing', async () => {
vi.mocked(rateLimit).mockResolvedValue({
success: true,
limit: 60,
Expand All @@ -156,7 +156,8 @@ describe('middleware', () => {

await middleware(request);

expect(rateLimit).toHaveBeenCalledWith('1.2.3.4', 60, 60000);
// Expect 9.9.9.9 instead of 1.2.3.4 because x-real-ip is more secure
expect(rateLimit).toHaveBeenCalledWith('9.9.9.9', 60, 60000);
});

it('handles multiple IPs with whitespace', async () => {
Expand Down
17 changes: 4 additions & 13 deletions middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,18 @@ import { rateLimit } from './lib/rate-limit';

/**
* Middleware to enforce rate limiting on specific API routes.
*
* Protected Routes:
* - /api/streak
* - /api/github
* - /api/track-user
* - /api/stats
* - /api/og
*
* Limit: 60 requests per minute per IP.
*/
export async function middleware(request: NextRequest) {
// Use Vercel's ip property if available, fallback to headers, then localhost
// 1. Fallback to `x-real-ip` (securely set by reverse proxies like Nginx/Vercel).
// 2. Fallback to `x-forwarded-for` properly parsed, or localhost.
const ip =
request.headers.get('x-forwarded-for')?.split(',')[0] ??
request.headers.get('x-real-ip') ??
request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ??
'127.0.0.1';

// Apply rate limiting
Expand Down Expand Up @@ -54,11 +51,5 @@ export async function middleware(request: NextRequest) {
* Using a matcher is more efficient than checking pathnames inside the middleware.
*/
export const config = {
matcher: [
'/api/streak/:path*',
'/api/github/:path*',
'/api/track-user/:path*',
'/api/stats/:path*',
'/api/og/:path*',
],
matcher: ['/api/streak/:path*', '/api/github/:path*', '/api/track-user/:path*'],
};
31 changes: 29 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading