-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
255 lines (223 loc) · 7.63 KB
/
Copy pathproxy.ts
File metadata and controls
255 lines (223 loc) · 7.63 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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { createServerClient } from "@supabase/ssr";
import { getServerSupabaseConfig } from "@/lib/supabase/config";
import { fetchWithTimeout } from "@/lib/security/timeouts";
import { validateCookieMutationOrigin } from "@/lib/security/csrf";
import { logSecurityEvent } from "@/lib/security/audit-log";
import { accountStatusDestination } from "@/lib/account-status";
import { authRedirectUrl } from "@/lib/supabase/auth-redirect";
const protectedPaths = [
"/dashboard",
"/materials",
"/exams",
"/progress",
"/chat",
"/profile",
"/settings",
"/account",
"/account-deactivated",
"/account-deletion-pending",
];
const guestOnlyPaths = [
"/login",
"/sign-up",
"/forgot-password",
"/check-email",
"/auth/password-reset",
"/reset-password",
];
const productionDisabledPaths = [
"/api/v1/whatsapp/webhook",
];
const HEALTH_CHECK_PATH = "/api/health";
const MAX_API_BODY_BYTES = 30 * 1024 * 1024;
export async function proxy(req: NextRequest) {
const pathname = req.nextUrl.pathname;
const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
const contentSecurityPolicy = buildContentSecurityPolicy(nonce);
if (
process.env.NODE_ENV === "production" &&
productionDisabledPaths.some((path) => pathMatches(pathname, path))
) {
return withContentSecurityPolicy(
new NextResponse("Not Found", {
status: 404,
headers: { "Cache-Control": "no-store" },
}),
contentSecurityPolicy
);
}
const csrfValidation = validateCookieMutationOrigin(req);
if (!csrfValidation.ok) {
logSecurityEvent("csrf_validation_failed", "warn", {
reason: csrfValidation.reason,
method: req.method,
path: pathname,
});
return withContentSecurityPolicy(
NextResponse.json(
{
error: "CSRF_VALIDATION_FAILED",
message: "The request origin could not be verified.",
},
{ status: 403, headers: { "Cache-Control": "no-store" } }
),
contentSecurityPolicy
);
}
if (pathname.startsWith("/api/") && requestBodyIsTooLarge(req)) {
return withContentSecurityPolicy(
NextResponse.json(
{
error: "REQUEST_TOO_LARGE",
message: "Request body must be 30 MB or smaller.",
},
{ status: 413, headers: { "Cache-Control": "no-store" } }
),
contentSecurityPolicy
);
}
const requestHeaders = new Headers(req.headers);
requestHeaders.set("x-nonce", nonce);
requestHeaders.set("Content-Security-Policy", contentSecurityPolicy);
const res = withContentSecurityPolicy(
NextResponse.next({ request: { headers: requestHeaders } }),
contentSecurityPolicy
);
// Railway only needs process liveness here. Avoid making deployment health
// depend on an external Supabase Auth request.
if (pathname === HEALTH_CHECK_PATH) return res;
const supabaseConfig = getServerSupabaseConfig();
const supabase = createServerClient(
supabaseConfig.url,
supabaseConfig.key,
{
global: { fetch: fetchWithTimeout },
cookies: {
getAll() {
return req.cookies.getAll().map(({ name, value }) => ({
name,
value,
}));
},
setAll(cookiesToSet) {
cookiesToSet.forEach(({ name, value, options }) => {
res.cookies.set(name, value, options);
});
},
},
}
);
const {
data: { user },
} = await supabase.auth.getUser();
const accountStatus =
typeof user?.user_metadata?.accountStatus === "string"
? user.user_metadata.accountStatus
: null;
if (protectedPaths.some((path) => pathMatches(pathname, path)) && !user) {
return withContentSecurityPolicy(
NextResponse.redirect(authRedirectUrl("/unauthorized", req.url)),
contentSecurityPolicy
);
}
if (user && protectedPaths.some((path) => pathMatches(pathname, path))) {
const restrictedDestination = accountStatusDestination(accountStatus);
if (restrictedDestination && restrictedDestination !== pathname) {
return withContentSecurityPolicy(
NextResponse.redirect(authRedirectUrl(restrictedDestination, req.url)),
contentSecurityPolicy
);
}
}
if (guestOnlyPaths.some((path) => pathMatches(pathname, path)) && user) {
const destination =
accountStatusDestination(accountStatus) ?? "/already-logged-in";
return withContentSecurityPolicy(
NextResponse.redirect(authRedirectUrl(destination, req.url)),
contentSecurityPolicy
);
}
return res;
}
function pathMatches(pathname: string, prefix: string) {
return pathname === prefix || pathname.startsWith(`${prefix}/`);
}
function buildContentSecurityPolicy(nonce: string) {
const isDevelopment = process.env.NODE_ENV === "development";
const styleSource = isDevelopment
? "style-src 'self' 'unsafe-inline' https://*.hcaptcha.com"
: `style-src 'self' 'nonce-${nonce}' https://*.hcaptcha.com`;
const imageSources = [
"'self'",
"data:",
"blob:",
...configuredSupabaseOrigins(isDevelopment),
];
return [
"default-src 'self'",
`script-src 'self' 'nonce-${nonce}' 'strict-dynamic'${isDevelopment ? " 'unsafe-eval'" : ""} https://challenges.cloudflare.com https://*.hcaptcha.com`,
"script-src-attr 'none'",
styleSource,
// React still renders a small number of dynamic style attributes. Keep the
// exception scoped to attributes instead of allowing arbitrary <style>
// blocks. Remove this after those attributes have moved to CSS classes.
"style-src-attr 'unsafe-inline'",
`img-src ${imageSources.join(" ")}`,
"font-src 'self' data:",
"connect-src 'self' https://*.supabase.co wss://*.supabase.co https://challenges.cloudflare.com https://*.hcaptcha.com",
"frame-src https://challenges.cloudflare.com https://*.hcaptcha.com",
"worker-src 'self' blob:",
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
"frame-ancestors 'none'",
...(!isDevelopment ? ["upgrade-insecure-requests"] : []),
].join("; ");
}
function configuredSupabaseOrigins(isDevelopment: boolean) {
const configuredUrls = [
process.env.SUPABASE_URL,
process.env.NEXT_PUBLIC_SUPABASE_URL,
];
const origins = new Set<string>();
for (const configuredUrl of configuredUrls) {
if (!configuredUrl?.trim()) continue;
try {
const url = new URL(configuredUrl.trim());
const isHostedSupabase =
url.protocol === "https:" && url.hostname.endsWith(".supabase.co");
const isLocalDevelopment =
isDevelopment &&
["localhost", "127.0.0.1", "[::1]"].includes(url.hostname) &&
["http:", "https:"].includes(url.protocol);
if (!url.username && !url.password && (isHostedSupabase || isLocalDevelopment)) {
origins.add(url.origin);
}
} catch {
// Ignore malformed values here. The stricter Supabase configuration
// validation reports them when an authenticated route is requested.
}
}
return [...origins];
}
function withContentSecurityPolicy(
response: NextResponse,
contentSecurityPolicy: string
) {
response.headers.set("Content-Security-Policy", contentSecurityPolicy);
return response;
}
function requestBodyIsTooLarge(req: NextRequest) {
if (["GET", "HEAD", "OPTIONS"].includes(req.method)) return false;
const rawLength = req.headers.get("content-length");
if (!rawLength) return false;
const length = Number.parseInt(rawLength, 10);
return Number.isFinite(length) && length > MAX_API_BODY_BYTES;
}
export const config = {
matcher: [
"/((?!_next/static|_next/image|favicon.ico|icons|logo-icon.svg).*)",
],
};