-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathmiddleware.ts
More file actions
114 lines (97 loc) · 3.45 KB
/
middleware.ts
File metadata and controls
114 lines (97 loc) · 3.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import { NextRequest, NextResponse } from "next/server"
import { validateRequest } from "@/lib/auth"
const PUBLIC_PATHS = [
"/login",
"/db-sync",
"/api/auth/login",
"/api/auth/verify-totp",
"/api/auth/check-users",
"/api/auth/register-first-user",
"/api/db-sync",
"/api/v1", // API v1 uses API key authentication, not JWT
"/_next",
"/favicon.ico"
]
// SECURITY: Rate limiting for auth endpoints to prevent brute force attacks
// Simple in-memory rate limiter for middleware (Edge-compatible)
const authRateLimitMap = new Map<string, { count: number; resetTime: number }>()
function getClientIP(request: NextRequest): string {
const forwarded = request.headers.get('x-forwarded-for')
const realIp = request.headers.get('x-real-ip')
return forwarded?.split(',')[0]?.trim() || realIp || 'anonymous'
}
function checkAuthRateLimit(request: NextRequest): { allowed: boolean; remaining: number } {
const clientIP = getClientIP(request)
const now = Date.now()
const windowMs = 15 * 60 * 1000 // 15 minutes
const maxAttempts = 10 // Max 10 login/TOTP attempts per 15 minutes
// Cleanup expired entries periodically
if (authRateLimitMap.size > 10000) {
for (const [key, value] of authRateLimitMap.entries()) {
if (now > value.resetTime) {
authRateLimitMap.delete(key)
}
}
}
const current = authRateLimitMap.get(clientIP)
if (!current || now > current.resetTime) {
authRateLimitMap.set(clientIP, { count: 1, resetTime: now + windowMs })
return { allowed: true, remaining: maxAttempts - 1 }
}
if (current.count >= maxAttempts) {
return { allowed: false, remaining: 0 }
}
current.count++
return { allowed: true, remaining: maxAttempts - current.count }
}
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl
// SECURITY: Rate limit auth endpoints to prevent brute force attacks
if (pathname === '/api/auth/login' || pathname === '/api/auth/verify-totp') {
const rateLimit = checkAuthRateLimit(request)
if (!rateLimit.allowed) {
return NextResponse.json(
{ success: false, error: "Too many login attempts. Please try again in 15 minutes." },
{
status: 429,
headers: {
'Retry-After': '900', // 15 minutes in seconds
'X-RateLimit-Remaining': '0'
}
}
)
}
}
// Allow public paths
if (PUBLIC_PATHS.some((p) => pathname === p || pathname.startsWith(p + "/"))) {
return NextResponse.next()
}
// Allow static files
if (pathname.match(/\.(png|svg|jpg|jpeg|ico|css|js)$/)) {
return NextResponse.next()
}
// Validate JWT token
const user = await validateRequest(request)
if (!user) {
const loginUrl = new URL("/login", request.url)
loginUrl.searchParams.set("redirect", pathname)
return NextResponse.redirect(loginUrl)
}
// Add user info to request context for API routes (internal use only)
const response = NextResponse.next()
// SECURITY: User identity headers removed from response to prevent information leakage
// User context is available via validateRequest() in API routes instead
return response
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
'/((?!_next/static|_next/image|favicon.ico).*)',
],
};