Repository navigation
Expand file tree
/
Copy pathproxy.ts
More file actions
154 lines (135 loc) · 4.54 KB
/
Copy pathproxy.ts
File metadata and controls
154 lines (135 loc) · 4.54 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
import { NextRequest, NextResponse } from "next/server";
const RATE_LIMIT_WINDOW_MS = 60_000; // 1 minute
const RATE_LIMIT_MAX_REQUESTS = 60; // 60 requests per minute per IP
// In-memory store for edge runtime (resets per cold start — use Upstash Redis for persistence)
const rateLimitStore = new Map<string, { count: number; resetAt: number }>();
function getClientIp(request: NextRequest): string {
const forwarded = request.headers.get("x-forwarded-for");
const realIp = request.headers.get("x-real-ip");
if (forwarded) return forwarded.split(",")[0].trim();
if (realIp) return realIp;
return "unknown";
}
function cleanExpiredRateLimits(): void {
if (rateLimitStore.size > 5000) {
const now = Date.now();
for (const [key, val] of rateLimitStore.entries()) {
if (now > val.resetAt) {
rateLimitStore.delete(key);
}
}
}
}
function isRateLimited(ip: string): boolean {
cleanExpiredRateLimits();
const now = Date.now();
const entry = rateLimitStore.get(ip);
if (!entry || now > entry.resetAt) {
rateLimitStore.set(ip, { count: 1, resetAt: now + RATE_LIMIT_WINDOW_MS });
return false;
}
entry.count += 1;
if (entry.count > RATE_LIMIT_MAX_REQUESTS) return true;
return false;
}
export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
const ip = getClientIp(request);
// Apply rate limiting to API routes only
if (pathname.startsWith("/api/")) {
if (isRateLimited(ip)) {
return new NextResponse(
JSON.stringify({
success: false,
error: {
code: "RATE_LIMIT_EXCEEDED",
message: "Too many requests. Please slow down and try again later.",
},
}),
{
status: 429,
headers: {
"Content-Type": "application/json",
"Retry-After": "60",
"X-RateLimit-Limit": String(RATE_LIMIT_MAX_REQUESTS),
"X-RateLimit-Remaining": "0",
},
}
);
}
}
// Block obviously bad paths (path traversal, common exploit probes)
const blockedPatterns = [
/\.\.(\/|\\)/, // Path traversal
/\.(env|git|htaccess)/, // Config file exposure
/wp-admin/, // WordPress probes
/phpMyAdmin/i, // phpMyAdmin probes
];
for (const pattern of blockedPatterns) {
if (pattern.test(pathname)) {
return new NextResponse("Not Found", { status: 404 });
}
}
const response = NextResponse.next();
// Add CSRF origin check for API mutation requests
if (pathname.startsWith("/api/") && ["POST", "PUT", "PATCH", "DELETE"].includes(request.method)) {
const origin = request.headers.get("origin");
const host = request.headers.get("host");
if (origin) {
try {
const originUrl = new URL(origin);
const originHost = originUrl.host;
const isAllowed =
// 1. Same-origin request matching Host header
(host && originHost === host) ||
// 2. Production custom domains
originHost === "ajitdev.com" ||
originHost === "www.ajitdev.com" ||
// 3. Vercel deployment and preview URLs
originHost.endsWith(".vercel.app") ||
// 4. Localhost on any development port (e.g. 3000, 3001, etc.)
originHost.startsWith("localhost") ||
originHost.startsWith("127.0.0.1");
if (!isAllowed) {
return new NextResponse(
JSON.stringify({
success: false,
error: {
code: "CSRF_FORBIDDEN",
message: "CSRF: Origin not allowed.",
},
}),
{
status: 403,
headers: { "Content-Type": "application/json" },
}
);
}
} catch {
return new NextResponse(
JSON.stringify({
success: false,
error: {
code: "CSRF_FORBIDDEN",
message: "CSRF: Invalid origin header.",
},
}),
{
status: 403,
headers: { "Content-Type": "application/json" },
}
);
}
}
}
// Security response headers (supplements next.config.ts static headers)
response.headers.set("X-XSS-Protection", "1; mode=block");
response.headers.set("X-DNS-Prefetch-Control", "on");
return response;
}
export const config = {
matcher: [
// Apply to all paths except static assets, images, and next internals
"/((?!_next/static|_next/image|favicon.ico|logo.png|og-image.png|site.webmanifest|sw.js|robots.txt|sitemap|feed).*)",
],
};