-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
316 lines (264 loc) · 10 KB
/
Copy pathproxy.ts
File metadata and controls
316 lines (264 loc) · 10 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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
import { NextResponse, type NextRequest } from "next/server";
import {
defaultLocale,
getLocaleFromAcceptLanguage,
getLocaleFromCookieValue,
getLocaleFromPathname,
localeCookieMaxAge,
localeCookieName,
localizePathname,
stripLocaleFromPathname,
type Locale,
} from "@/i18n/config";
import {
isPlatformLaunched,
isPrelaunchPublicSitePath,
} from "@/lib/platform-launch";
import { isPrivateIndexingHost } from "@/lib/seo";
const PRIVATE_SUBDOMAIN_ROBOTS_HEADER = "noindex, nofollow, noarchive, nosnippet";
const IS_PRODUCTION = process.env.NODE_ENV === "production";
// 'unsafe-eval' krävs bara av dev-verktyg (Turbopack/React Refresh) och ska
// aldrig skickas i produktion — det är den enskilt viktigaste XSS-broms som
// finns kvar så länge auth-token ligger i localStorage. ws:/localhost i
// connect-src är också rena dev-behov (HMR).
const CONTENT_SECURITY_POLICY = [
"default-src 'self'",
"base-uri 'self'",
"object-src 'none'",
"frame-ancestors 'none'",
"form-action 'self'",
"img-src 'self' data: blob: https:",
"font-src 'self' data: https:",
"style-src 'self' 'unsafe-inline' https:",
IS_PRODUCTION
? "script-src 'self' 'unsafe-inline' https:"
: "script-src 'self' 'unsafe-inline' 'unsafe-eval' https:",
IS_PRODUCTION
? "connect-src 'self' https:"
: "connect-src 'self' https: http://localhost:* http://127.0.0.1:* ws: wss:",
"frame-src 'self' https:",
"worker-src 'self' blob:",
"manifest-src 'self'",
"media-src 'self' https: blob:",
// Bara i produktion: Safari/WebKit undantar inte localhost från
// upgrade-insecure-requests som Chrome/Firefox gör, så i dev skulle alla
// chunkar/fonter tvingas till https://localhost:3000 där ingen TLS-server
// finns — sidan blir helt tom i Safari.
...(IS_PRODUCTION ? ["upgrade-insecure-requests"] : []),
].join("; ");
// Flagg-cookien sätts av src/lib/auth-storage.ts vid inloggning (värdet är
// alltid "1", aldrig själva tokenen). Saknas den kan vi avvisa anonyma
// anrop mot portal/admin redan i proxyn i stället för i klientkod.
const AUTH_FLAG_COOKIE_NAME = "cl_auth";
const SECURITY_HEADERS: ReadonlyArray<readonly [string, string]> = [
["Content-Security-Policy", CONTENT_SECURITY_POLICY],
// 'same-origin-allow-popups' (inte 'same-origin'): behåller COOP-isoleringen
// mot främmande openers men bevarar window.opener för popups sidan själv
// öppnar — krävs för att Google Identity Services (Sign in with Google) ska
// kunna posta tillbaka ID-tokenen till oss. Ren 'same-origin' kapar opener
// och Google-popupen hänger vit utan att logga in.
["Cross-Origin-Opener-Policy", "same-origin-allow-popups"],
["Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=()"],
["Referrer-Policy", "strict-origin-when-cross-origin"],
// HSTS bara i produktion: skulle dev någon gång servas över https pinnar
// headern localhost (inkl. subdomäner) till https i två år för webbläsaren
// och knäcker alla andra lokala http-servrar.
...(IS_PRODUCTION
? [["Strict-Transport-Security", "max-age=63072000; includeSubDomains; preload"] as const]
: []),
["X-Content-Type-Options", "nosniff"],
["X-Frame-Options", "DENY"],
];
function getHostname(req: NextRequest) {
const host = req.headers.get("host") ?? "";
return host.split(":")[0].toLowerCase();
}
const internalLocaleSearchParam = "__campuslyan_locale";
function pathStartsWithSegment(pathname: string, segment: "/portal" | "/admin") {
return pathname === segment || pathname.startsWith(`${segment}/`);
}
function isPublicAssetPath(pathname: string) {
return /\.[^/]+$/.test(pathname);
}
function isImmutablePublicAssetPath(pathname: string) {
return /\.(?:avif|webp|png|jpe?g|gif|svg|ico|woff2?)$/i.test(pathname);
}
function setLocaleCookie(response: NextResponse, locale: Locale) {
response.cookies.set(localeCookieName, locale, {
maxAge: localeCookieMaxAge,
path: "/",
sameSite: "lax",
});
}
function withSecurityHeaders(response: NextResponse) {
SECURITY_HEADERS.forEach(([key, value]) => {
response.headers.set(key, value);
});
return response;
}
function nextPublicAsset(pathname: string) {
const response = withSecurityHeaders(NextResponse.next());
if (isImmutablePublicAssetPath(pathname)) {
response.headers.set("Cache-Control", "public, max-age=31536000, immutable");
}
return response;
}
function requestHeadersWithLocale(req: NextRequest, locale: Locale) {
const requestHeaders = new Headers(req.headers);
requestHeaders.set("x-campuslyan-locale", locale);
return requestHeaders;
}
function resolvePreferredLocale(
req: NextRequest,
urlLocale: Locale | null,
internalLocale: Locale | null,
) {
return (
urlLocale ??
internalLocale ??
getLocaleFromCookieValue(req.cookies.get(localeCookieName)?.value) ??
getLocaleFromAcceptLanguage(req.headers.get("accept-language")) ??
defaultLocale
);
}
function nextWithLocale(req: NextRequest, locale: Locale) {
const response = NextResponse.next({
request: {
headers: requestHeadersWithLocale(req, locale),
},
});
setLocaleCookie(response, locale);
return withSecurityHeaders(response);
}
function rewriteWithLocale(req: NextRequest, url: URL, locale: Locale) {
const response = NextResponse.rewrite(url, {
request: {
headers: requestHeadersWithLocale(req, locale),
},
});
setLocaleCookie(response, locale);
return withSecurityHeaders(response);
}
function redirectWithLocale(url: URL, locale: Locale) {
const response = NextResponse.redirect(url);
setLocaleCookie(response, locale);
return withSecurityHeaders(response);
}
function withNoIndexHeader(response: NextResponse) {
response.headers.set("X-Robots-Tag", PRIVATE_SUBDOMAIN_ROBOTS_HEADER);
return response;
}
function redirectToPrelaunchHome(url: URL, locale: Locale) {
url.pathname = localizePathname("/", locale);
url.search = "";
return redirectWithLocale(url, locale);
}
/**
* Serversidigt skydd för portal-/admin-ytorna: utan auth-flagg-cookien
* skickas besökaren till inloggningen innan något sidskal renderas.
* Klientguardarna är fortfarande auktoritativa (cookien är bara en flagga);
* detta stoppar anonym rendering av skyddade sidor och deras prefetch.
* Endast i produktion — i dev delas ingen cookie mellan localhost-subdomäner.
*/
function requiresAuthRedirect(
req: NextRequest,
effectivePathname: string,
base: "/portal" | "/admin",
) {
if (!IS_PRODUCTION) {
return false;
}
const loginPath = `${base}/login`;
if (
effectivePathname === loginPath ||
effectivePathname.startsWith(`${loginPath}/`)
) {
return false;
}
return !req.cookies.get(AUTH_FLAG_COOKIE_NAME)?.value;
}
function redirectToSubdomainLogin(url: URL, locale: Locale) {
url.pathname = "/login";
url.search = "";
return withNoIndexHeader(redirectWithLocale(url, locale));
}
export function proxy(req: NextRequest) {
const hostname = getHostname(req);
const url = req.nextUrl.clone();
const { pathname } = url;
const urlLocale = getLocaleFromPathname(pathname);
const internalLocale = getLocaleFromCookieValue(url.searchParams.get(internalLocaleSearchParam));
const locale = resolvePreferredLocale(req, urlLocale, internalLocale);
const routingPathname = stripLocaleFromPathname(pathname);
if (isPublicAssetPath(pathname)) {
return nextPublicAsset(pathname);
}
const isPortalSubdomain = hostname.startsWith("portal.");
const isAdminSubdomain = hostname.startsWith("admin.");
const isPrivateSubdomain = isPrivateIndexingHost(hostname);
if (isPortalSubdomain) {
const effectivePortalPath = pathStartsWithSegment(routingPathname, "/portal")
? routingPathname
: `/portal${routingPathname === "/" ? "" : routingPathname}`;
if (requiresAuthRedirect(req, effectivePortalPath, "/portal")) {
return redirectToSubdomainLogin(url, locale);
}
if (!pathStartsWithSegment(routingPathname, "/portal")) {
url.pathname = `/portal${routingPathname === "/" ? "" : routingPathname}`;
return withNoIndexHeader(rewriteWithLocale(req, url, locale));
}
if (urlLocale) {
url.pathname = routingPathname;
return withNoIndexHeader(rewriteWithLocale(req, url, locale));
}
return withNoIndexHeader(nextWithLocale(req, locale));
}
if (isAdminSubdomain) {
const effectiveAdminPath = pathStartsWithSegment(routingPathname, "/admin")
? routingPathname
: `/admin${routingPathname === "/" ? "" : routingPathname}`;
if (requiresAuthRedirect(req, effectiveAdminPath, "/admin")) {
return redirectToSubdomainLogin(url, locale);
}
if (routingPathname === "/" || routingPathname === "/admin") {
url.pathname = "/tags";
return withNoIndexHeader(redirectWithLocale(url, locale));
}
if (!pathStartsWithSegment(routingPathname, "/admin")) {
url.pathname = `/admin${routingPathname === "/" ? "" : routingPathname}`;
return withNoIndexHeader(rewriteWithLocale(req, url, locale));
}
if (urlLocale) {
url.pathname = routingPathname;
return withNoIndexHeader(rewriteWithLocale(req, url, locale));
}
return withNoIndexHeader(nextWithLocale(req, locale));
}
if (
pathStartsWithSegment(routingPathname, "/portal") ||
pathStartsWithSegment(routingPathname, "/admin")
) {
url.pathname = "/404";
const response = rewriteWithLocale(req, url, locale);
return isPrivateSubdomain ? withNoIndexHeader(response) : response;
}
if (!isPlatformLaunched() && !isPrelaunchPublicSitePath(routingPathname)) {
return redirectToPrelaunchHome(url, locale);
}
if (internalLocale && !urlLocale) {
return nextWithLocale(req, locale);
}
if (!urlLocale && locale === "en") {
url.pathname = localizePathname(pathname, "en");
return redirectWithLocale(url, locale);
}
if (urlLocale) {
url.pathname = routingPathname;
url.searchParams.set(internalLocaleSearchParam, locale);
return rewriteWithLocale(req, url, locale);
}
return nextWithLocale(req, locale);
}
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};