Repository navigation
Expand file tree
/
Copy pathproxy.ts
More file actions
407 lines (360 loc) · 14.7 KB
/
Copy pathproxy.ts
File metadata and controls
407 lines (360 loc) · 14.7 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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
/**
* Next.js 16 proxy (replaces middleware).
*
* 1. Blocks /api-test in production.
* 2. Refreshes Supabase auth sessions when a session cookie is present.
* 3. Protects /admin/* routes — redirects unauthenticated users to home.
*/
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { createServerClient } from "@supabase/ssr";
import type { Locale } from "@/lib/i18n/translations";
import { isAdminUserId } from "@/lib/auth/admin-policy";
import {
ADMIN_SESSION_COOKIE_NAME,
verifyAdminSessionCookieValue,
} from "@/lib/auth/admin-session";
import {
addLocaleToPathname,
DEFAULT_LOCALE,
detectPreferredLocale,
getLocaleFromPathname,
shouldRewriteLocalizedPath,
shouldUseLocalizedFilesystemRoute,
isLocale,
LOCALE_COOKIE_NAME,
shouldBypassLocale,
stripLocaleFromPathname,
} from "@/lib/i18n/routing";
const SOCIAL_CRAWLER_RE =
/Twitterbot|facebookexternalhit|LinkedInBot|Slackbot|Discordbot|WhatsApp|TelegramBot|Pinterestbot|Applebot/i;
// Search-engine and AI crawlers verify ownership and index against the exact
// URL they request — they do not follow the 307 locale negotiation the way a
// browser does. Baidu's site-verification fetch of `/` in particular fails
// outright on a 307 ("未知原因:307"). Treat them like social crawlers at the
// root: serve the default-locale content (with its meta tags) in place instead
// of redirecting, while humans keep the language-negotiated 307 below.
const SEARCH_CRAWLER_RE =
/Baiduspider|bingbot|BingPreview|Googlebot|Google-InspectionTool|DuckDuckBot|YandexBot|Sogou|360Spider|Bytespider|GPTBot|OAI-SearchBot|ChatGPT-User|ClaudeBot|Claude-Web|Claude-SearchBot|PerplexityBot|Perplexity-User|CCBot|Applebot-Extended|meta-externalagent/i;
function isSocialCrawler(userAgent: string): boolean {
return SOCIAL_CRAWLER_RE.test(userAgent);
}
function isContentCrawler(userAgent: string): boolean {
return SOCIAL_CRAWLER_RE.test(userAgent) || SEARCH_CRAWLER_RE.test(userAgent);
}
// Search and AI crawlers fetch without cookies or Accept-Language, so locale
// negotiation can never learn anything about them; unprefixed /colors/* URLs
// answer them with the deterministic permanent redirect instead.
function isSearchBot(userAgent: string): boolean {
return SEARCH_CRAWLER_RE.test(userAgent);
}
function isAdminRoute(pathname: string): boolean {
return pathname === "/admin" || pathname.startsWith("/admin/");
}
function shouldRefreshAuthSession(pathname: string): boolean {
// Analytics is intentionally anonymous and can be called many times during
// a single page view. Refreshing a stale auth cookie for every analytics
// event creates a server-IP refresh storm and can exhaust Supabase Auth's
// per-IP token bucket, which then blocks real login callbacks.
return pathname !== "/api/analytics";
}
function isPrefetchRequest(request: NextRequest): boolean {
return (
request.headers.has("next-router-prefetch") ||
request.headers.get("purpose") === "prefetch"
);
}
function isSupabaseAuthCookie(name: string): boolean {
// @supabase/ssr appends .0, .1, ... when a session is split across cookies.
return name.startsWith("sb-") && /-auth-token(?:\.\d+)?$/.test(name);
}
function readInternalLocaleRewrite(
request: NextRequest,
incomingPath: string,
): { locale: Locale; visiblePath: string } | null {
const locale = request.headers.get("x-stylekit-locale");
const visiblePath = request.headers.get("x-stylekit-visible-path");
if (
!isLocale(locale) ||
!visiblePath ||
getLocaleFromPathname(visiblePath) !== locale ||
stripLocaleFromPathname(visiblePath) !== incomingPath
) {
return null;
}
return { locale, visiblePath };
}
function buildAdminLoginRedirect(request: NextRequest) {
const redirectUrl = request.nextUrl.clone();
redirectUrl.pathname = "/admin-login";
redirectUrl.search = "";
const currentPath = `${request.nextUrl.pathname}${request.nextUrl.search}`;
if (currentPath.startsWith("/admin")) {
redirectUrl.searchParams.set("next", currentPath);
}
return NextResponse.redirect(redirectUrl);
}
// Only send Set-Cookie when the persisted locale actually changes. Re-setting
// the same value on every localized response adds a header that shared caches
// must treat as private, for no benefit.
function applyLocaleCookie(
request: NextRequest,
response: NextResponse,
locale: Locale | null,
prefetchRequest: boolean,
): NextResponse {
if (!locale || prefetchRequest) return response;
if (request.cookies.get(LOCALE_COOKIE_NAME)?.value === locale) return response;
response.cookies.set(LOCALE_COOKIE_NAME, locale, {
path: "/",
sameSite: "lax",
maxAge: 60 * 60 * 24 * 365,
});
return response;
}
export async function proxy(request: NextRequest) {
const incomingPath = request.nextUrl.pathname;
const prefetchRequest = isPrefetchRequest(request);
const localeInPath = getLocaleFromPathname(incomingPath);
// Next can run the proxy again after a localized URL is rewritten to a
// shared filesystem route. Preserve the visible locale instead of treating
// that internal request as a fresh, unprefixed browser navigation.
const internalLocaleRewrite = localeInPath
? null
: readInternalLocaleRewrite(request, incomingPath);
const strippedPath = localeInPath
? stripLocaleFromPathname(incomingPath)
: incomingPath;
const effectivePath = strippedPath;
const localeCookieValue = request.cookies.get(LOCALE_COOKIE_NAME)?.value;
const requestLocale =
localeInPath ??
internalLocaleRewrite?.locale ??
(isLocale(localeCookieValue) ? localeCookieValue : DEFAULT_LOCALE);
if (localeInPath && shouldBypassLocale(strippedPath)) {
const redirectUrl = request.nextUrl.clone();
redirectUrl.pathname = strippedPath;
return NextResponse.redirect(redirectUrl);
}
if (
!localeInPath &&
!internalLocaleRewrite &&
!shouldBypassLocale(incomingPath) &&
(effectivePath === "/colors" || effectivePath.startsWith("/colors/"))
) {
// Unprefixed /colors/* has no language-negotiated value for crawlers:
// Googlebot (no cookie, no Accept-Language) saw both /en/ and /zh/ as
// 307 targets on different crawls and keeps the unprefixed URL indexed
// as a locale selector, splitting impressions between /colors/x and
// /en/colors/x. Answer crawler requests with a deterministic permanent
// redirect; humans keep the 307 negotiation below even without a
// language preference, so their choice is never pinned permanently.
const ua = request.headers.get("user-agent") || "";
if (isSearchBot(ua)) {
const permanentUrl = request.nextUrl.clone();
permanentUrl.pathname = addLocaleToPathname(incomingPath, DEFAULT_LOCALE);
return NextResponse.redirect(permanentUrl, 308);
}
}
if (
!localeInPath &&
!internalLocaleRewrite &&
!shouldBypassLocale(incomingPath)
) {
// Serve default-locale content in place (no 307) for two audiences:
// 1. Known social/search/AI crawler UAs.
// 2. ANY request with no language preference — no locale cookie AND no
// Accept-Language header. This is the decisive case for verification
// fetchers: Baidu's site-verification crawler does NOT send the
// Baiduspider UA, so UA matching alone missed it and it kept getting
// the empty 307 ("未知原因:307"). Real browsers always send
// Accept-Language, so humans still fall through to the 307 language
// negotiation below and keep their preferred locale.
const ua = request.headers.get("user-agent") || "";
const hasLanguagePreference =
isLocale(localeCookieValue) ||
Boolean(request.headers.get("accept-language"));
if (isContentCrawler(ua) || !hasLanguagePreference) {
// The English detail URL is canonical. Serving its unprefixed alias as
// another 200 let Google select /styles/swiss-style instead of /en/.
// Keep browser language negotiation below and standalone showcases out
// of this exact detail-route match.
if (/^\/styles\/[^/]+$/.test(incomingPath)) {
const canonicalUrl = request.nextUrl.clone();
canonicalUrl.pathname = addLocaleToPathname(incomingPath, DEFAULT_LOCALE);
const response = NextResponse.redirect(canonicalUrl, 308);
response.headers.set("Vary", "Accept-Language, Cookie, User-Agent");
return response;
}
const localizedVisiblePath = addLocaleToPathname(incomingPath, DEFAULT_LOCALE);
const requestHeaders = new Headers(request.headers);
requestHeaders.set("x-stylekit-locale", DEFAULT_LOCALE);
requestHeaders.set("x-stylekit-visible-path", localizedVisiblePath);
if (shouldUseLocalizedFilesystemRoute(incomingPath)) {
const rewriteUrl = request.nextUrl.clone();
rewriteUrl.pathname = localizedVisiblePath;
return NextResponse.rewrite(rewriteUrl, {
request: { headers: requestHeaders },
});
}
return NextResponse.next({
request: { headers: requestHeaders },
});
}
const preferredLocale = isLocale(localeCookieValue)
? localeCookieValue
: detectPreferredLocale(request.headers.get("accept-language"));
const redirectUrl = request.nextUrl.clone();
redirectUrl.pathname = addLocaleToPathname(incomingPath, preferredLocale || DEFAULT_LOCALE);
const response = NextResponse.redirect(redirectUrl);
// A prefetch carries no user intent; letting it write the locale cookie
// could silently pin the visitor's language from a background request.
return applyLocaleCookie(
request,
response,
preferredLocale || DEFAULT_LOCALE,
prefetchRequest,
);
}
// Block /api-test in production
if (
process.env.NODE_ENV === "production" &&
effectivePath.startsWith("/api-test")
) {
return new NextResponse("Not Found", { status: 404 });
}
const requestHeaders = new Headers(request.headers);
if (localeInPath) {
requestHeaders.set("x-stylekit-locale", localeInPath);
requestHeaders.set("x-stylekit-visible-path", incomingPath);
} else if (internalLocaleRewrite) {
requestHeaders.set("x-stylekit-locale", internalLocaleRewrite.locale);
requestHeaders.set(
"x-stylekit-visible-path",
internalLocaleRewrite.visiblePath,
);
} else {
requestHeaders.set("x-stylekit-locale", requestLocale);
requestHeaders.set("x-stylekit-visible-path", incomingPath);
}
const finalizeResponse = (response: NextResponse) => {
if (effectivePath === "/api/workspace" || effectivePath.startsWith("/api/workspace/")) {
response.headers.set("Cache-Control", "private, no-store");
response.headers.set("Pragma", "no-cache");
}
return response;
};
const buildResponse = () => {
if (localeInPath) {
if (shouldUseLocalizedFilesystemRoute(strippedPath)) {
return finalizeResponse(NextResponse.next({
request: { headers: requestHeaders },
}));
}
if (!shouldRewriteLocalizedPath(strippedPath)) {
return finalizeResponse(NextResponse.next({
request: { headers: requestHeaders },
}));
}
const rewriteUrl = request.nextUrl.clone();
rewriteUrl.pathname = strippedPath;
return finalizeResponse(NextResponse.rewrite(rewriteUrl, {
request: { headers: requestHeaders },
}));
}
return finalizeResponse(NextResponse.next({
request: { headers: requestHeaders },
}));
};
const isAdminRequest = isAdminRoute(effectivePath);
const adminSessionCookie = request.cookies.get(ADMIN_SESSION_COOKIE_NAME)?.value;
const hasAdminPasswordSession =
await verifyAdminSessionCookieValue(adminSessionCookie);
if (effectivePath === "/admin-login" && hasAdminPasswordSession) {
const redirectUrl = request.nextUrl.clone();
redirectUrl.pathname = "/admin/operations";
redirectUrl.search = "";
return NextResponse.redirect(redirectUrl);
}
if (isAdminRequest && hasAdminPasswordSession) {
return applyLocaleCookie(request, buildResponse(), localeInPath, prefetchRequest);
}
const hasAdminDevBypass =
process.env.NODE_ENV !== "production" &&
process.env.ADMIN_DEV_BYPASS === "true";
if (isAdminRequest && hasAdminDevBypass) {
return applyLocaleCookie(request, buildResponse(), localeInPath, prefetchRequest);
}
const url = process.env.NEXT_PUBLIC_SUPABASE_URL;
const key = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
// If Supabase is not configured, skip auth entirely
if (!url || !key) {
if (
process.env.NODE_ENV === "production" &&
isAdminRequest
) {
return buildAdminLoginRedirect(request);
}
const response = buildResponse();
return applyLocaleCookie(request, response, localeInPath, prefetchRequest);
}
if (!isAdminRequest && !shouldRefreshAuthSession(effectivePath)) {
const response = buildResponse();
return applyLocaleCookie(request, response, localeInPath, prefetchRequest);
}
let supabaseResponse = buildResponse();
const supabase = createServerClient(url, key, {
cookies: {
getAll() {
return request.cookies.getAll();
},
setAll(cookiesToSet) {
for (const { name, value } of cookiesToSet) {
request.cookies.set(name, value);
}
supabaseResponse = buildResponse();
for (const { name, value, options } of cookiesToSet) {
supabaseResponse.cookies.set(name, value, options);
}
},
},
});
// Check if user has an auth cookie — skip network call for anonymous visitors
const hasAuthCookie = request.cookies
.getAll()
.some((cookie) => isSupabaseAuthCookie(cookie.name));
if (hasAuthCookie) {
// getClaims() refreshes expired sessions but validates current ES256 JWTs
// locally using the project's cached JWKS. Unlike getUser(), it does not
// make an Auth API request on every page/API request.
const { data, error } = await supabase.auth.getClaims();
const userId = !error && typeof data?.claims.sub === "string"
? data.claims.sub
: null;
// Protect /admin routes
if (isAdminRequest) {
if (!userId) {
return buildAdminLoginRedirect(request);
}
if (!isAdminUserId(userId)) {
return buildAdminLoginRedirect(request);
}
}
} else if (isAdminRequest) {
// No auth cookie + admin route = redirect immediately
return buildAdminLoginRedirect(request);
}
return applyLocaleCookie(request, supabaseResponse, localeInPath, prefetchRequest);
}
export const config = {
matcher: [
/*
* Match all request paths except:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - public assets (images, fonts, etc.)
*/
"/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp|ico|woff|woff2)$).*)",
],
};