security: enhance authentication rate limiting and add comprehensive security tests

- Add rate limiting middleware for NextAuth login endpoints
- Implement authRateLimitMiddleware for /api/auth/* routes
- Add comprehensive security tests covering:
  - Rate limiter functionality (5 tests)
  - IP extraction from headers (5 tests)
  - Input validation and sanitization (10 tests)
  - Password strength requirements
  - XSS and SQL injection prevention
- All 21 security tests passing
- Rate limits configured: 5 login attempts per 15 minutes
This commit is contained in:
2025-07-05 15:14:40 +02:00
committed by Kaj Kowalski
parent 25f6625c4f
commit 7cc5cad14f
3 changed files with 369 additions and 0 deletions

View File

@ -0,0 +1,41 @@
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { extractClientIP, InMemoryRateLimiter } from "../lib/rateLimiter";
// Rate limiting for login attempts
const loginRateLimiter = new InMemoryRateLimiter({
maxAttempts: 5, // 5 login attempts
windowMs: 15 * 60 * 1000, // 15 minutes
maxEntries: 10000,
cleanupIntervalMs: 5 * 60 * 1000, // 5 minutes
});
/**
* Apply rate limiting to authentication endpoints
*/
export function authRateLimitMiddleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Only apply to NextAuth signin endpoint
if (pathname.startsWith("/api/auth/signin") || pathname.startsWith("/api/auth/callback/credentials")) {
const ip = extractClientIP(request);
const rateLimitResult = loginRateLimiter.checkRateLimit(ip);
if (!rateLimitResult.allowed) {
return NextResponse.json(
{
success: false,
error: "Too many login attempts. Please try again later.",
},
{
status: 429,
headers: {
"Retry-After": String(Math.ceil((rateLimitResult.resetTime! - Date.now()) / 1000)),
},
}
);
}
}
return NextResponse.next();
}