返回 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 // 308, not 301: clients may turn a 301'd POST (the admin login and post
45 // forms) into a GET and drop its body. 308 keeps the method and body and is
46 // still a permanent move for crawlers.
47 return NextResponse.redirect(url, 308);
48 }
49
50 /**
51 * Paths with no page of their own that should land on installation in one
52 * hop, bare or localized. `/download` and `/desktop` 404'd (M2) until a dark
53 * download hub exists (D11). `/pricing` went bare → `/en/pricing` →
54 * `/en/install` (UX-13); public pricing stays off (§0), so it keeps landing on
55 * install — `app/[locale]/pricing/page.tsx` still redirects as a backstop.
56 * Temporary (307) because each of these may become a real page later.
57 */
58 const INSTALL_ALIASES = new Set(["download", "desktop", "pricing"]);
59
60 function installAliasRedirect(req: NextRequest): NextResponse | null {
61 const segments = req.nextUrl.pathname.split("/").filter(Boolean);
62 const existing = pathLocale(req.nextUrl.pathname);
63 const rest = existing ? segments.slice(1) : segments;
64 if (rest.length !== 1 || !INSTALL_ALIASES.has(rest[0].toLowerCase())) return null;
65 const locale =
66 existing ??
67 detectLocaleFromHeaders(req.cookies.get(COOKIE)?.value, req.headers.get("accept-language"));
68 const url = req.nextUrl.clone();
69 url.pathname = `/${locale}/install`;
70 const res = NextResponse.redirect(url, 307);
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 = canonicalHostRedirect(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 / create-account
100 // pages. 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 installAlias = installAliasRedirect(req);
110 if (installAlias) return applySecurityHeaders(installAlias);
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