-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathmiddleware.ts
More file actions
278 lines (257 loc) · 7.46 KB
/
middleware.ts
File metadata and controls
278 lines (257 loc) · 7.46 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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import { NextRequest, NextResponse } from "next/server";
import { LRUCache } from "lru-cache";
// In-memory metrics store
const metrics: Record<string, { count: number; errorCount: number }> = {};
// CORS & SECURITY CONFIGURATION
const CORS_ALLOWED_METHODS = [
"GET",
"POST",
"PUT",
"DELETE",
"PATCH",
"OPTIONS",
];
const CORS_ALLOWED_HEADERS = [
"Content-Type",
"Authorization",
"X-Requested-With",
];
const MAX_BODY_SIZE = parseInt(process.env.API_MAX_BODY_SIZE || "1048576", 10); // Default 1MB
const SECURITY_HEADERS: Record<string, string> = {
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"X-XSS-Protection": "1; mode=block",
};
// Helper functions
function applyCORS(response: NextResponse, request: NextRequest): void {
const allowedOrigin =
process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000";
const requestOrigin = request.headers.get("origin");
const isSameOrigin = !requestOrigin || requestOrigin === allowedOrigin;
if (isSameOrigin || requestOrigin === allowedOrigin) {
response.headers.set(
"Access-Control-Allow-Origin",
requestOrigin || allowedOrigin,
);
}
response.headers.set("Access-Control-Allow-Credentials", "true");
response.headers.set(
"Access-Control-Allow-Methods",
CORS_ALLOWED_METHODS.join(", "),
);
response.headers.set(
"Access-Control-Allow-Headers",
CORS_ALLOWED_HEADERS.join(", "),
);
response.headers.set("Vary", "Origin");
}
function applySecurityHeaders(response: NextResponse): void {
Object.entries(SECURITY_HEADERS).forEach(([key, value]) => {
response.headers.set(key, value);
});
}
async function validateBodySize(
request: NextRequest,
maxSize: number = MAX_BODY_SIZE,
): Promise<{ valid: boolean; error?: NextResponse }> {
const methodsToValidate = ["POST", "PUT", "PATCH"];
if (!methodsToValidate.includes(request.method)) {
return { valid: true };
}
const contentLength = request.headers.get("content-length");
if (contentLength && parseInt(contentLength, 10) > maxSize) {
return {
valid: false,
error: new NextResponse(
JSON.stringify({
error: "Payload Too Large",
message: `Request body exceeds maximum size of ${maxSize} bytes.`,
}),
{
status: 413,
headers: { "Content-Type": "application/json" },
},
),
};
}
if (!contentLength) {
try {
const bodyBuffer = await request.arrayBuffer();
if (bodyBuffer.byteLength > maxSize) {
return {
valid: false,
error: new NextResponse(
JSON.stringify({
error: "Payload Too Large",
message: `Request body exceeds maximum size of ${maxSize} bytes.`,
}),
{
status: 413,
headers: { "Content-Type": "application/json" },
},
),
};
}
} catch {
return { valid: true };
}
}
return { valid: true };
}
// RATE LIMITING CONFIGURATION
const RATE_LIMITS = {
auth: 10,
write: 50,
general: 100,
};
const rateLimitCache = new LRUCache<
string,
{ count: number; expiresAt: number }
>({
max: 10000,
ttl: 60 * 1000,
});
export async function middleware(request: NextRequest) {
const start = Date.now();
const method = request.method;
const url = request.nextUrl.pathname;
const requestId = Math.random().toString(36).substring(2, 10);
// Extract IP or fallback for key
const forwardedFor = request.headers.get("x-forwarded-for");
let ip = "127.0.0.1";
if (forwardedFor) {
ip = forwardedFor.split(",")[0].trim();
} else {
const remoteAddr = request.headers.get("x-real-ip");
if (remoteAddr) {
ip = remoteAddr;
}
}
// Whitelist test environments (Playwright E2E)
if (
request.headers.get("x-playwright-test") === "true" &&
process.env.NODE_ENV !== "production"
) {
return NextResponse.next();
}
// Whitelist Health Check
if (url === "/api/health" || url.startsWith("/api/health/")) {
return NextResponse.next();
}
// CORS & Security headers early
let apiResponse: NextResponse;
let statusCode = 200;
let error = false;
apiResponse = NextResponse.next();
applyCORS(apiResponse, request);
applySecurityHeaders(apiResponse);
// Handle CORS OPTIONS preflight requests
if (method === "OPTIONS") {
const preflightResponse = new NextResponse(null, { status: 204 });
applyCORS(preflightResponse, request);
applySecurityHeaders(preflightResponse);
return preflightResponse;
}
// Validate request body size
const bodySizeValidation = await validateBodySize(request);
if (!bodySizeValidation.valid && bodySizeValidation.error) {
applyCORS(bodySizeValidation.error, request);
applySecurityHeaders(bodySizeValidation.error);
return bodySizeValidation.error;
}
// Rate limiting
let limit = RATE_LIMITS.general;
let limitType = "general";
if (url.startsWith("/api/auth/")) {
limit = RATE_LIMITS.auth;
limitType = "auth";
} else if (["POST", "PUT", "DELETE", "PATCH"].includes(method)) {
limit = RATE_LIMITS.write;
limitType = "write";
}
const cacheKey = `${ip}:${limitType}`;
const now = Date.now();
const tokenRecord = rateLimitCache.get(cacheKey) || {
count: 0,
expiresAt: now + 60000,
};
if (now > tokenRecord.expiresAt) {
tokenRecord.count = 0;
tokenRecord.expiresAt = now + 60000;
}
tokenRecord.count += 1;
rateLimitCache.set(cacheKey, tokenRecord);
if (tokenRecord.count > limit) {
const retryAfter = Math.ceil(
(tokenRecord.expiresAt - now) / 1000,
).toString();
const rateLimitError = new NextResponse(
JSON.stringify({
error: "Too Many Requests",
message: "Rate limit exceeded.",
}),
{
status: 429,
headers: {
"Content-Type": "application/json",
"Retry-After": retryAfter,
"X-RateLimit-Limit": limit.toString(),
"X-RateLimit-Remaining": "0",
"X-RateLimit-Reset": tokenRecord.expiresAt.toString(),
},
},
);
applyCORS(rateLimitError, request);
applySecurityHeaders(rateLimitError);
// Log metrics for rate limit errors
const durationMs = Date.now() - start;
const key = `${method} ${url}`;
if (!metrics[key]) metrics[key] = { count: 0, errorCount: 0 };
metrics[key].count++;
metrics[key].errorCount++;
console.log(
JSON.stringify({
requestId,
method,
path: url,
statusCode: 429,
durationMs,
timestamp: new Date().toISOString(),
}),
);
rateLimitError.headers.set("X-Request-ID", requestId);
return rateLimitError;
}
// Add rate limit headers to response
apiResponse.headers.set("X-RateLimit-Limit", limit.toString());
apiResponse.headers.set(
"X-RateLimit-Remaining",
(limit - tokenRecord.count).toString(),
);
apiResponse.headers.set(
"X-RateLimit-Reset",
tokenRecord.expiresAt.toString(),
);
// Metrics logging
const durationMs = Date.now() - start;
const key = `${method} ${url}`;
if (!metrics[key]) metrics[key] = { count: 0, errorCount: 0 };
metrics[key].count++;
if (statusCode >= 400) metrics[key].errorCount++;
console.log(
JSON.stringify({
requestId,
method,
path: url,
statusCode,
durationMs,
timestamp: new Date().toISOString(),
}),
);
apiResponse.headers.set("X-Request-ID", requestId);
return apiResponse;
}
export { metrics };
export const config = {
matcher: "/api/:path*",
};