Repository navigation
Expand file tree
/
Copy pathproxy.ts
More file actions
209 lines (177 loc) · 8.04 KB
/
Copy pathproxy.ts
File metadata and controls
209 lines (177 loc) · 8.04 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
import { type NextRequest, NextResponse } from "next/server"
import { DEFAULT_LOCALE, isSupportedLocale, type Locale } from "@/lib/i18n/config"
import { SHARED_SECURITY_HEADERS, contentSecurityPolicy } from "@/lib/security-headers"
import { isRoutableShareId } from "@/lib/share-model"
const STATIC_SECURITY_HEADERS = [["X-Frame-Options", "DENY"], ...SHARED_SECURITY_HEADERS] as const
// Marks the homepage's internal rewrite of "/" into the "/en" app tree. Some
// dev servers (Turbopack) re-run the proxy on an internal rewrite; without this
// guard, the rewritten "/en" request would hit the "/en" -> "/" redirect and
// loop. Production runs the proxy once, so this is a belt-and-braces guard.
const HOME_REWRITE_HEADER = "x-tickward-home-rewrite"
// Agent-useful discovery links advertised on the home page (RFC 8288). Relative
// URIs resolve against the requested resource.
const DISCOVERY_LINK_HEADER = [
'</.well-known/api-catalog>; rel="api-catalog"',
'</openapi.json>; rel="service-desc"; type="application/json"',
'</docs/api-reference>; rel="service-doc"',
].join(", ")
function applySecurityHeaders(response: NextResponse): NextResponse {
STATIC_SECURITY_HEADERS.forEach(([key, value]) => {
response.headers.set(key, value)
})
response.headers.set("Content-Security-Policy", contentSecurityPolicy())
return response
}
function handleHomepage(request: NextRequest, internalPathname: string): NextResponse {
// Markdown for Agents: serve the markdown representation when negotiated.
if ((request.headers.get("accept") ?? "").includes("text/markdown")) {
const markdown = NextResponse.rewrite(new URL("/home.md", request.url))
markdown.headers.set("Vary", "Accept")
return applySecurityHeaders(markdown)
}
const rewriteUrl = request.nextUrl.clone()
rewriteUrl.pathname = internalPathname
const requestHeaders = new Headers(request.headers)
requestHeaders.set(HOME_REWRITE_HEADER, "1")
const response =
internalPathname === request.nextUrl.pathname
? NextResponse.next()
: NextResponse.rewrite(rewriteUrl, { request: { headers: requestHeaders } })
response.headers.set("Link", DISCOVERY_LINK_HEADER)
response.headers.set("Vary", "Accept")
return applySecurityHeaders(response)
}
function parseForwardedHosts(value: string | null) {
return (
value
?.split(",")
.map((host) => host.trim().toLowerCase())
.filter(Boolean) ?? []
)
}
function isAllowedRequestOrigin(request: NextRequest, origin: string) {
let originHost: string
try {
originHost = new URL(origin).host.toLowerCase()
} catch {
return false
}
const allowedHosts = new Set(
[request.nextUrl.host, request.headers.get("host"), ...parseForwardedHosts(request.headers.get("x-forwarded-host"))]
.filter((host): host is string => Boolean(host))
.map((host) => host.toLowerCase()),
)
return allowedHosts.has(originHost)
}
function shareIdFromPathname(pathname: string) {
const match = /^\/share\/([^/]+)\/?$/.exec(pathname)
if (!match?.[1]) return null
try {
return decodeURIComponent(match[1])
} catch {
return ""
}
}
// Splits an explicit /<locale> prefix off the public pathname.
function splitLocalePrefix(pathname: string): { locale: Locale; rest: string } | null {
const segment = pathname.split("/")[1] ?? ""
if (!isSupportedLocale(segment)) return null
return { locale: segment, rest: pathname.slice(segment.length + 1) || "/" }
}
function redirectToPath(request: NextRequest, pathname: string): NextResponse {
const redirectUrl = request.nextUrl.clone()
redirectUrl.pathname = pathname
return applySecurityHeaders(NextResponse.redirect(redirectUrl, 301))
}
// Returns the 403 response for a mutating request whose Origin header does not
// match any allowed host; null when the request may proceed.
function rejectedCrossOriginMutation(request: NextRequest): NextResponse | null {
const method = request.method
if (method !== "POST" && method !== "DELETE") return null
const origin = request.headers.get("Origin")
if (!origin || isAllowedRequestOrigin(request, origin)) return null
const response = NextResponse.json({ error: "Forbidden" }, { status: 403 })
return applySecurityHeaders(response)
}
function isEmbedPath(pathname: string): boolean {
return pathname === "/embed" || pathname.startsWith("/embed/")
}
// Some paths stay locale-neutral at their bare URL and must not be redirected
// onto /<locale>: embeds (iframed into external sites from a copy/paste
// snippet, where a 301 would add a hop or break under strict iframe/CSP
// rules) and docs (served bare via the external docs origin or the catch-all
// docs route, never under the /<locale> app tree).
function isLocaleNeutralPath(pathname: string): boolean {
return isEmbedPath(pathname) || pathname === "/docs" || pathname.startsWith("/docs/")
}
function handleShareRoute(
request: NextRequest,
shareId: string,
prefixed: boolean,
internalPathname: string,
): NextResponse {
if (!isRoutableShareId(shareId)) {
const response = new NextResponse("Not found", {
status: 404,
headers: { "Content-Type": "text/plain; charset=utf-8" },
})
return applySecurityHeaders(response)
}
const rejected = rejectedCrossOriginMutation(request)
if (rejected) return rejected
const shareRewriteUrl = request.nextUrl.clone()
shareRewriteUrl.pathname = internalPathname
const response = prefixed ? NextResponse.next() : NextResponse.rewrite(shareRewriteUrl)
return applySecurityHeaders(response)
}
export async function proxy(request: NextRequest) {
const pathname = request.nextUrl.pathname
// API routes are locale-neutral: origin-check mutations, add headers.
if (pathname === "/api" || pathname.startsWith("/api/")) {
return rejectedCrossOriginMutation(request) ?? applySecurityHeaders(NextResponse.next())
}
if (
(pathname === `/${DEFAULT_LOCALE}` || pathname === `/${DEFAULT_LOCALE}/`) &&
request.headers.get(HOME_REWRITE_HEADER) !== "1"
) {
return redirectToPath(request, "/")
}
const prefixed = splitLocalePrefix(pathname)
if (!prefixed && pathname !== "/" && !isLocaleNeutralPath(pathname)) {
return redirectToPath(request, `/${DEFAULT_LOCALE}${pathname}`)
}
// The public path the visitor sees, independent of the locale prefix, and
// the internal path inside the app/[locale] tree.
const publicPath = prefixed ? prefixed.rest : pathname
const barePathSuffix = pathname === "/" ? "" : pathname
const internalPathname = prefixed ? pathname : `/${DEFAULT_LOCALE}${barePathSuffix}`
if (publicPath === "/") {
return handleHomepage(request, internalPathname)
}
const shareId = shareIdFromPathname(publicPath)
if (shareId !== null) {
return handleShareRoute(request, shareId, prefixed !== null, internalPathname)
}
// Every other page route only needs the locale rewrite; response headers
// for these routes come from next.config headers(), as before.
const pageRewriteUrl = request.nextUrl.clone()
pageRewriteUrl.pathname = internalPathname
const response = prefixed ? NextResponse.next() : NextResponse.rewrite(pageRewriteUrl)
// The embed page is anonymous, cookie-free, and identical for a given URL, so
// let a CDN absorb repeat loads when a timer is embedded on a busy host page.
// Without this the framework marks the dynamic page (it reads searchParams)
// no-store, and every iframe load is a fresh SSR invocation. The window
// mirrors the embed state API (app/api/embed/[token]/route.ts). Set here in
// the proxy because a dynamic page's Cache-Control set via next.config
// headers() is overwritten by the framework, whereas proxy headers win.
if (isEmbedPath(publicPath)) {
response.headers.set("Cache-Control", "public, max-age=60, stale-while-revalidate=300")
}
return response
}
export const config = {
// Match every page path (no dots, not _next) so the default locale can be
// rewritten into the app/[locale] tree, plus the API for origin checks.
// Next.js statically analyzes matcher values and rejects String.raw here.
matcher: ["/((?!api|_next|.*\\..*).*)", "/", "/api/:path*"], // NOSONAR typescript:S7780
}