Repository navigation
Expand file tree
/
Copy pathmiddleware.ts
More file actions
209 lines (190 loc) · 5.98 KB
/
Copy pathmiddleware.ts
File metadata and controls
209 lines (190 loc) · 5.98 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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
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' },
},
];
const ROUTES_WITH_OWN_RATE_LIMITING = [
'/api/spotlight',
'/api/reviews',
'/api/achievements',
'/api/ci-analytics',
'/api/user-repos',
'/api/team-attribution',
'/api/repo-burnout',
'/api/webhook',
'/api/articles',
'/api/learning-curve',
'/api/org',
'/api/spotify', // Added here in case it has its own rate limiter
];
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 }
)
);
}
}
}
// Check if route has its own local rate limiter to avoid double-limiting
const hasOwnRateLimiter = ROUTES_WITH_OWN_RATE_LIMITING.some((p) => path.startsWith(p));
// 2. Configurable Rate Limiting
let limitResult;
if (rule?.rateLimit !== false && !hasOwnRateLimiter) {
// 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/articles/:path*',
'/api/learning-curve/:path*',
'/api/languages/:path*',
'/api/org/:path*',
'/api/spotify/:path*',
'/api/Auth/:path*',
'/api/achievements/:path*',
'/api/ci-analytics/:path*',
'/api/cicd/:path*',
'/api/enterprise/:path*',
'/api/health/:path*',
'/api/insights-og/:path*',
'/api/repo-burnout/:path*',
'/api/reviews/:path*',
'/api/spotlight/:path*',
'/api/team-attribution/:path*',
'/api/user/:path*',
'/api/wakatime/:path*',
'/api/user-details/:path*',
'/api/user-repos/:path*',
'/api/webhook/:path*',
'/api/webhooks/:path*',
],
};