Repository navigation
Expand file tree
/
Copy pathproxy.ts
More file actions
132 lines (117 loc) · 5.58 KB
/
Copy pathproxy.ts
File metadata and controls
132 lines (117 loc) · 5.58 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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { isIP } from "node:net";
import { pageSecurity } from "@/lib/pageSecurity";
import { CLIENT_IP_HEADER, GATEWAY_HEADER, isFrontendPeer } from "@/lib/frontend/peer";
import { checkRateLimit } from "@/lib/rateLimit";
function tooMany(apiV1 = false, mobile = false) {
return NextResponse.json(
mobile
? { ok: false, error: { code: "RATE_LIMITED", message: "Too many requests. Try again later." } }
: apiV1
? { error: { code: "RATE_LIMITED", message: "Too many requests. Try again later." } }
: { error: "Too many requests. Try again later." },
{ status: 429, headers: { "Retry-After": "60", "Cache-Control": "no-store" } },
);
}
function tooManyText() {
return new NextResponse("Too many requests. Try again later.", {
status: 429,
headers: { "Retry-After": "60", "Cache-Control": "no-store" },
});
}
export async function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
// The peer credential authenticates only the frontend service, never a user.
// Only an authenticated peer may supply the original browser address.
if (request.headers.has(GATEWAY_HEADER)) {
if (!isFrontendPeer(request.headers)) return new NextResponse("Not found", { status: 404 });
const ip = request.headers.get(CLIENT_IP_HEADER)?.trim();
const header = process.env.TRUSTED_PROXY_IP_HEADER;
if (header && ["x-real-ip", "x-forwarded-for", "cf-connecting-ip"].includes(header)) request.headers.set(header, ip && isIP(ip) ? ip : "unknown");
}
if (process.env.DEPLOYMENT_MODE === "backend" && !pathname.startsWith("/api/") && !/\/(opengraph-image|twitter-image)(?:\/|$)/.test(pathname)) return new NextResponse("Not found", { status: 404 });
// Server Actions post to page URLs, not /api. Apply one distributed ceiling
// before any action-specific subject/IP limits run in the action itself.
if (request.method === "POST" && request.headers.has("next-action")) {
if (!(await checkRateLimit(request, "action"))) return tooMany();
}
if (pathname === "/discover") {
if (!(await checkRateLimit(request, "search"))) return tooManyText();
}
// Liveness must not depend on Redis. Readiness remains protected because a
// failed distributed limiter means the application is not fully ready.
// Payment provider webhooks have their own bucket instead of the global one.
const isPaymentWebhook = pathname.startsWith("/api/webhooks/");
// A split-hosted page render reads its views here, a dozen or more per page.
// A single-server render spends no API budget, so these authenticated peer
// reads (the gateway key was checked above) skip the per-user global bucket.
// Peer actions keep their own limit (lib/frontend/handler.ts).
const isPeerView = request.headers.has(GATEWAY_HEADER) && pathname.startsWith("/api/frontend/view/");
if (isPaymentWebhook) {
if (!(await checkRateLimit(request, "paymentWebhook"))) return tooMany();
} else if (pathname.startsWith("/api") && pathname !== "/api/health" && !isPeerView) {
if (!(await checkRateLimit(request, "global"))) {
return tooMany(pathname.startsWith("/api/v1"), pathname.startsWith("/api/mobile/"));
}
}
// Mobile app sign-in shares the strict per-IP sign-in bucket with the web
// (the credential verifier adds per-account limits). Mobile API requests are
// bearer-authenticated route handlers: no cookies, CSRF or Server Action
// origin checks apply, and nothing here redirects them.
if ((pathname === "/api/mobile/v1/auth/login" || pathname === "/api/mobile/v1/auth/google") && request.method === "POST") {
if (!(await checkRateLimit(request, "auth"))) return tooMany(false, true);
}
// Auth.js polls session, CSRF, and provider endpoints with GET requests.
// Counting those reads against the strict sign-in bucket logs active users
// out after a few tabs or routine session refreshes. Mutating auth requests
// retain the dedicated protection; all reads remain under the global limit.
if (pathname.startsWith("/api/auth") && request.method !== "GET") {
if (!(await checkRateLimit(request, "auth"))) {
return tooMany();
}
}
if (pathname === "/api/uploads" && request.method !== "GET") {
if (!(await checkRateLimit(request, "upload"))) {
return tooMany();
}
}
if (pathname === "/api/rsvp" && request.method === "POST") {
if (!(await checkRateLimit(request, "rsvp"))) {
return tooMany();
}
}
if (pathname === "/api/search" && request.method === "GET") {
if (!(await checkRateLimit(request, "search"))) {
return tooMany();
}
}
if (pathname === "/search") {
if (!(await checkRateLimit(request, "search"))) {
return tooManyText();
}
}
if (pathname.startsWith("/api")) {
const response = NextResponse.next({ request: { headers: new Headers(request.headers) } });
if (process.env.FRONTEND_GATEWAY_SECRET && /^\/api\/ticket\/[^/]+\/(events|status)$/.test(pathname) && request.headers.get("origin") === process.env.NEXT_PUBLIC_BASE_URL) {
response.headers.set("Access-Control-Allow-Origin", process.env.NEXT_PUBLIC_BASE_URL!);
response.headers.append("Vary", "Origin");
}
response.headers.set("X-Frame-Options", "DENY");
return response;
}
return pageSecurity(request);
}
export const config = {
matcher: [
"/api/:path*",
"/search",
{
source: "/((?!api|_next/static|_next/image|favicon.ico).*)",
missing: [
{ type: "header", key: "next-router-prefetch" },
{ type: "header", key: "purpose", value: "prefetch" },
],
},
],
};