-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
163 lines (142 loc) · 5.08 KB
/
Copy pathproxy.ts
File metadata and controls
163 lines (142 loc) · 5.08 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
import { NextResponse } from "next/server"
import { getSessionCookie } from "better-auth/cookies"
/**
* Build Sentry security report URL from DSN for CSP report-uri / report-to.
* Parsed once at module load. Returns null if DSN is missing or invalid.
*/
function getSentryCspReportUrl(): string | null {
const dsn = process.env.NEXT_PUBLIC_SENTRY_DSN
if (!dsn || typeof dsn !== "string") return null
try {
const url = new URL(dsn)
const key = url.username
const host = url.hostname
const projectId = url.pathname.replace(/^\//, "").replace(/\/$/, "")
if (!key || !host || !projectId) return null
const reportUrl = new URL(`https://${host}/api/${projectId}/security/`)
reportUrl.searchParams.set("sentry_key", decodeURIComponent(key))
const env = process.env.SENTRY_ENVIRONMENT ?? process.env.NODE_ENV
if (env) reportUrl.searchParams.set("sentry_environment", env)
const release = process.env.SENTRY_RELEASE
if (release) reportUrl.searchParams.set("sentry_release", release)
return reportUrl.toString()
} catch {
return null
}
}
const sentryCspReportUrl = getSentryCspReportUrl()
const protectedRoutes = ["/concerts/new", "/concerts/edit", "/settings", "/map"]
const authRoutes = [
"/login",
"/register",
"/forgot-password",
"/reset-password",
"/verify-email",
"/resend-verification",
]
const POSTHOG_DEFAULT_HOST = "https://eu.i.posthog.com"
function isPostHogAnalyticsEnabled(): boolean {
const key = process.env.NEXT_PUBLIC_POSTHOG_KEY?.trim()
if (!key) return false
const flag = process.env.NEXT_PUBLIC_POSTHOG_ENABLED?.toLowerCase()
return flag === "true" || flag === "1" || flag === "yes"
}
function getPostHogConnectSrc(): string {
if (!isPostHogAnalyticsEnabled()) return ""
const host =
process.env.NEXT_PUBLIC_POSTHOG_HOST?.trim() || POSTHOG_DEFAULT_HOST
let apiOrigin: string
try {
apiOrigin = new URL(host).origin
} catch {
apiOrigin = POSTHOG_DEFAULT_HOST
}
// posthog-js loads remote config from {region}-assets.i.posthog.com (e.g. eu-assets),
// not only from the API host; *.i.posthog.com covers EU/US asset endpoints.
return ` ${apiOrigin} https://*.i.posthog.com`
}
function buildCsp(nonce: string): string {
const isDev = process.env.NODE_ENV === "development"
const postHogConnectSrc = getPostHogConnectSrc()
const directives = [
"default-src 'self'",
`script-src 'self' 'nonce-${nonce}' 'strict-dynamic'${isDev ? " 'unsafe-eval'" : ""}`,
"style-src 'self' 'unsafe-inline'",
`connect-src 'self' https://*.ingest.sentry.io https://tiles.openfreemap.org${postHogConnectSrc}`,
"img-src 'self' blob: data: https://upload.wikimedia.org https://avatars.githubusercontent.com https://tiles.openfreemap.org",
"font-src 'self' data:",
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
"frame-ancestors 'none'",
"worker-src 'self' blob:",
]
if (sentryCspReportUrl) {
directives.push(
`report-uri ${sentryCspReportUrl}`,
"report-to csp-endpoint"
)
}
return directives.join("; ")
}
function setCspReportingHeaders(res: NextResponse): void {
if (!sentryCspReportUrl) return
res.headers.set(
"Report-To",
JSON.stringify({
group: "csp-endpoint",
max_age: 10886400,
endpoints: [{ url: sentryCspReportUrl }],
include_subdomains: true,
})
)
res.headers.set("Reporting-Endpoints", `csp-endpoint="${sentryCspReportUrl}"`)
}
export async function proxy(request: Request) {
const url = new URL(request.url)
const { pathname } = url
const nonce = Buffer.from(crypto.randomUUID()).toString("base64")
const csp = buildCsp(nonce)
const requestHeaders = new Headers(request.headers)
requestHeaders.set("x-nonce", nonce)
requestHeaders.set("Content-Security-Policy", csp)
const sessionCookie = getSessionCookie(request)
const isAuthenticated = !!sessionCookie
if (authRoutes.some((route) => pathname.startsWith(route))) {
if (isAuthenticated) {
const res = NextResponse.redirect(new URL("/", request.url))
res.headers.set("Content-Security-Policy", csp)
setCspReportingHeaders(res)
return res
}
const res = NextResponse.next({ request: { headers: requestHeaders } })
res.headers.set("Content-Security-Policy", csp)
setCspReportingHeaders(res)
return res
}
if (protectedRoutes.some((route) => pathname.startsWith(route))) {
if (!isAuthenticated) {
const loginUrl = new URL("/login", request.url)
loginUrl.searchParams.set("callbackUrl", pathname)
const res = NextResponse.redirect(loginUrl)
res.headers.set("Content-Security-Policy", csp)
setCspReportingHeaders(res)
return res
}
}
const res = NextResponse.next({ request: { headers: requestHeaders } })
res.headers.set("Content-Security-Policy", csp)
setCspReportingHeaders(res)
return res
}
export const config = {
matcher: [
{
source: "/((?!api|_next/static|_next/image|favicon.ico).*)",
missing: [
{ type: "header", key: "next-router-prefetch" },
{ type: "header", key: "purpose", value: "prefetch" },
],
},
],
}