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