forked from JhaSourav07/commitpulse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
170 lines (153 loc) · 4.87 KB
/
Copy pathmiddleware.ts
File metadata and controls
170 lines (153 loc) · 4.87 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { rateLimit, getRateLimitHeaders } from './lib/rate-limit';
import { getClientIp } from './utils/getClientIp';
import { auth } from './auth';
const securityHeaders = {
'Content-Security-Policy':
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https: blob:; font-src 'self' data:; connect-src 'self' https:;",
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'Strict-Transport-Security': 'max-age=63072000; includeSubDomains; preload',
'Referrer-Policy': 'strict-origin-when-cross-origin',
'Permissions-Policy': 'camera=(), microphone=(), geolocation=()',
};
interface RouteRule {
pattern: string;
auth?: 'admin' | 'user' | false;
rateLimit?:
| {
limit: number;
windowMs: number;
namespace: string;
}
| false;
}
const routeRules: RouteRule[] = [
{
pattern: '/api/enterprise',
auth: 'admin',
rateLimit: { limit: 60, windowMs: 60000, namespace: 'api' },
},
{
pattern: '/api/architecture',
auth: 'user',
rateLimit: { limit: 60, windowMs: 60000, namespace: 'api' },
},
{
pattern: '/api/track-user',
rateLimit: { limit: 5, windowMs: 60000, namespace: 'track-user' },
},
{
pattern: '/api/notify',
rateLimit: { limit: 5, windowMs: 60000, namespace: 'notify' },
},
];
function addSecurityHeaders(response: NextResponse): NextResponse {
Object.entries(securityHeaders).forEach(([key, value]) => {
response.headers.set(key, value);
});
return response;
}
/**
* Centralized middleware to handle authentication, rate limiting, and security headers.
*/
export async function middleware(request: NextRequest) {
const ip = getClientIp(request);
const path = request.nextUrl.pathname;
// Find matching route rule
const rule = routeRules.find((r) => path.startsWith(r.pattern));
// 1. Authentication and Authorization Check
if (rule?.auth) {
const session = await auth();
if (!session?.user) {
return addSecurityHeaders(
NextResponse.json({ error: 'Authentication required' }, { status: 401 })
);
}
if (rule.auth === 'admin') {
const adminIds = (process.env.ENTERPRISE_ADMIN_GITHUB_IDS ?? '')
.split(',')
.map((id) => id.trim())
.filter(Boolean);
if (adminIds.length === 0) {
return addSecurityHeaders(
NextResponse.json({ error: 'Enterprise admin access not configured' }, { status: 503 })
);
}
const userId = session.user.id;
if (!userId || !adminIds.includes(userId)) {
return addSecurityHeaders(
NextResponse.json(
{ error: 'Forbidden: enterprise admin access required' },
{ status: 403 }
)
);
}
}
}
// 2. Configurable Rate Limiting
let limitResult;
if (rule?.rateLimit !== false) {
// Determine if this is a hard-refresh request (bypasses cache/hits GitHub API)
const isRefreshRequest =
request.nextUrl.searchParams.get('refresh') === 'true' ||
request.nextUrl.searchParams.get('bypassCache') === 'true';
if (isRefreshRequest) {
// Strict rate limit for explicit refresh requests: 3 requests per 10 minutes (600,000ms)
limitResult = await rateLimit(`refresh_limiter:${ip}`, 3, 600000, 'api');
} else if (rule?.rateLimit) {
limitResult = await rateLimit(
ip,
rule.rateLimit.limit,
rule.rateLimit.windowMs,
rule.rateLimit.namespace
);
} else {
// Default rate limit: 60 requests per 1 minute (60,000ms)
limitResult = await rateLimit(ip, 60, 60000, 'api');
}
if (!limitResult.success) {
return addSecurityHeaders(
NextResponse.json(
{ error: 'Too many requests' },
{
status: 429,
headers: {
'Content-Type': 'application/json',
...getRateLimitHeaders(limitResult),
},
}
)
);
}
}
const response = NextResponse.next();
// Apply Rate Limit Headers if rate limiting was executed
if (limitResult) {
response.headers.set('X-RateLimit-Limit', limitResult.limit.toString());
response.headers.set('X-RateLimit-Remaining', limitResult.remaining.toString());
response.headers.set('X-RateLimit-Reset', limitResult.reset.toString());
}
// Apply Global Security Headers
return addSecurityHeaders(response);
}
/**
* Configure which routes should trigger this middleware.
*/
export const config = {
matcher: [
'/api/streak/:path*',
'/api/github/:path*',
'/api/track-user/:path*',
'/api/stats/:path*',
'/api/og/:path*',
'/api/notify/:path*',
'/api/compare/:path*',
'/api/wrapped/:path*',
'/api/student/:path*',
'/api/pr-insights/:path*',
'/api/architecture/:path*',
'/api/enterprise/:path*',
],
};