返回 CodeWhale
middleware.ts
根目录 / web / middleware.ts
1 import { NextRequest, NextResponse } from "next/server";
2 import { detectLocaleFromHeaders } from "@/lib/i18n/detect";
3 import { pathLocale, replacePathLocale } from "@/lib/i18n/path";
4 import {
5 canonicalPublicAuthPath,
6 publicAuthCallbackDestination,
7 } from "@/lib/public-auth-routes";
8
9 const COOKIE = "NEXT_LOCALE";
10
11 const SECURITY_HEADERS: Record<string, string> = {
12 "X-Frame-Options": "DENY",
13 "X-Content-Type-Options": "nosniff",
14 "Referrer-Policy": "strict-origin-when-cross-origin",
15 "Permissions-Policy": "camera=(), microphone=(), geolocation=(), interest-cohort=()",
16 "Strict-Transport-Security": "max-age=63072000; includeSubDomains; preload",
17 };
18
19 function applySecurityHeaders(res: NextResponse): NextResponse {
20 for (const [k, v] of Object.entries(SECURITY_HEADERS)) res.headers.set(k, v);
21 return res;
22 }
23
24 /**
25 * The one host this site is indexed under. `www` is also bound to this worker
26 * as a custom domain, so without this guard the entire site answers on two
27 * hosts and every page has a duplicate URL a crawler can reach.
28 *
29 * This runs before the locale and static-asset branches on purpose: the
30 * canonical host has to win for assets and API routes too, or a `www` page
31 * keeps pulling subresources from `www` after the document moved.
32 */
33 const CANONICAL_HOST = "codewhale.net";
34
35 function canonicalHostRedirect(req: NextRequest): NextResponse | null {
36 const host = req.headers.get("host");
37 if (!host) return null;
38 // Compare without the port so local and preview hosts are untouched.
39 const bare = host.split(":")[0].toLowerCase();
40 if (bare !== `www.${CANONICAL_HOST}`) return null;
41 const url = req.nextUrl.clone();
42 url.host = CANONICAL_HOST;
43 url.port = "";
44 return NextResponse.redirect(url, 301);
45 }
46
47 export function middleware(req: NextRequest) {
48 const { pathname } = req.nextUrl;
49
50 const canonical = canonicalHostRedirect(req);
51 if (canonical) return applySecurityHeaders(canonical);
52
53 // Skip API routes, static files, _next, and the dot-less metadata route
54 // for the shared OG image (but still apply security headers).
55 if (
56 pathname.startsWith("/api/") ||
57 pathname.startsWith("/_next/") ||
58 pathname === "/opengraph-image" ||
59 pathname.includes(".")
60 ) {
61 return applySecurityHeaders(NextResponse.next());
62 }
63
64 // Auth callbacks belong on the CWC app. Locale-prefixing them produced
65 // `/en/auth/callback` 404s (#5767). Preserve the query string.
66 const callback = publicAuthCallbackDestination(req.nextUrl);
67 if (callback) {
68 return applySecurityHeaders(NextResponse.redirect(callback, 307));
69 }
70
71 // `/login` and `/register` are aliases for the public sign-in / create-account
72 // pages. Fold them before locale detection so `/login` becomes `/en/signin`
73 // instead of `/en/login` (which has no page).
74 const canonicalAuth = canonicalPublicAuthPath(pathname);
75 if (canonicalAuth && canonicalAuth !== pathname) {
76 const url = req.nextUrl.clone();
77 url.pathname = canonicalAuth;
78 return applySecurityHeaders(NextResponse.redirect(url, 308));
79 }
80
81 // Check if locale is already in path (`pt-BR` is one segment).
82 const existing = pathLocale(pathname);
83 if (existing) {
84 // A miscased prefix names the same route, so fold `/pt-br/install` onto
85 // `/pt-BR/install` instead of letting it reach the bare-path branch
86 // below, which would redirect to `/en/pt-br/install` — a 404. One
87 // canonical spelling also keeps a single URL in the index.
88 const canonicalPath = replacePathLocale(pathname, existing);
89 let res: NextResponse;
90 if (canonicalPath === pathname) {
91 res = NextResponse.next();
92 } else {
93 const url = req.nextUrl.clone();
94 url.pathname = canonicalPath;
95 res = NextResponse.redirect(url, 308);
96 }
97 res.cookies.set(COOKIE, existing, { path: "/", maxAge: 60 * 60 * 24 * 365 });
98 return applySecurityHeaders(res);
99 }
100
101 // Redirect bare paths to the detected locale (deterministic: cookie, then
102 // Accept-Language full-tag/primary-subtag matching, then the default).
103 const locale = detectLocaleFromHeaders(
104 req.cookies.get(COOKIE)?.value,
105 req.headers.get("accept-language"),
106 );
107 const url = req.nextUrl.clone();
108 url.pathname = `/${locale}${pathname}`;
109 const res = NextResponse.redirect(url);
110 res.cookies.set(COOKIE, locale, { path: "/", maxAge: 60 * 60 * 24 * 365 });
111 return applySecurityHeaders(res);
112 }
113
114 export const config = {
115 // Match everything so security headers apply globally; the function
116 // bypasses redirect/locale logic for /_next, /api, and dotted paths.
117 matcher: ["/:path*"],
118 };
119
119 lines TYPESCRIPT