-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
228 lines (199 loc) · 8.09 KB
/
Copy pathproxy.ts
File metadata and controls
228 lines (199 loc) · 8.09 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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { getToken } from 'next-auth/jwt'
import { getSecurityHeaders, isSignatureAuthenticatedWebhook, verifyCsrfToken } from '@/lib/csrf'
const IS_DEVELOPMENT = process.env.NODE_ENV === 'development'
const SECURITY_HEADERS = getSecurityHeaders()
const DEFAULT_CORS_ORIGINS = [
'http://localhost:3000',
'http://127.0.0.1:3000',
'https://boardly.online',
]
const ALLOWED_ORIGINS_FROM_ENV = process.env.CORS_ORIGIN
? process.env.CORS_ORIGIN.split(',').map((value) => value.trim()).filter(Boolean)
: []
const RAW_ALLOWED_CORS_ORIGINS = ALLOWED_ORIGINS_FROM_ENV.length > 0
? ALLOWED_ORIGINS_FROM_ENV
: DEFAULT_CORS_ORIGINS
function normalizeCorsOrigin(origin: string | null | undefined): string | null {
if (!origin) return null
try {
const parsed = new URL(origin)
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
return null
}
return parsed.origin
} catch {
return null
}
}
const ALLOWED_CORS_ORIGIN_SET = new Set(
RAW_ALLOWED_CORS_ORIGINS
.map((origin) => normalizeCorsOrigin(origin))
.filter((origin): origin is string => origin !== null)
)
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])
function isLocalDevelopmentOrigin(origin: string): boolean {
try {
const parsed = new URL(origin)
return parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1'
} catch {
return false
}
}
function resolveAllowedCorsOrigin(origin: string | null): string | null {
const normalizedOrigin = normalizeCorsOrigin(origin)
if (!normalizedOrigin) return null
if (ALLOWED_CORS_ORIGIN_SET.has(normalizedOrigin)) {
return normalizedOrigin
}
if (IS_DEVELOPMENT && isLocalDevelopmentOrigin(normalizedOrigin)) {
return normalizedOrigin
}
return null
}
function hasValidInternalSecret(request: NextRequest): boolean {
const configuredSecret = process.env.BOARDLY_INTERNAL_SECRET
if (!configuredSecret) return false
return request.headers.get('X-Internal-Secret') === configuredSecret
}
function hasValidCronAuthorization(request: NextRequest): boolean {
const cronSecret = process.env.CRON_SECRET
if (!cronSecret) return false
return request.headers.get('authorization') === `Bearer ${cronSecret}`
}
function isTrustedServerRequest(request: NextRequest): boolean {
return hasValidInternalSecret(request) || hasValidCronAuthorization(request)
}
function buildCspHeaderValue() {
const connectSrcCandidates = new Set<string>([
"'self'",
'ws://localhost:*',
'ws://127.0.0.1:*',
'http://localhost:*',
'http://127.0.0.1:*',
'https://*.supabase.co',
'wss://*.supabase.co',
'https://vercel.live',
'https://*.ingest.sentry.io',
'https://*.ingest.de.sentry.io',
// AdSense and the Google consent message (#876) talk back to these.
'https://pagead2.googlesyndication.com',
'https://fundingchoicesmessages.google.com',
'https://csi.gstatic.com',
])
const connectSrcValue = Array.from(connectSrcCandidates).join(' ')
// Next.js 15 app-router output includes inline bootstrap scripts without nonce
// across statically rendered routes. Keep production CSP compatible with that
// output to avoid blocking core Next.js chunk/bootstrap execution.
// The AdSense loader, the ad-serving hosts it pulls in, and the Google
// consent message (#784 put the tag in the HTML; #876 found that the policy
// had never let it run).
const adsScriptHosts =
'https://pagead2.googlesyndication.com https://fundingchoicesmessages.google.com https://tpc.googlesyndication.com https://googleads.g.doubleclick.net https://www.googletagservices.com'
const scriptSrcValue = IS_DEVELOPMENT
? `'self' 'unsafe-eval' 'unsafe-inline' https://vercel.live https://accounts.google.com https://apis.google.com ${adsScriptHosts}`
: `'self' 'unsafe-inline' https://vercel.live https://accounts.google.com https://apis.google.com ${adsScriptHosts}`
return `
default-src 'self';
script-src ${scriptSrcValue};
style-src 'self' 'unsafe-inline' https://accounts.google.com;
img-src 'self' data: https: blob:;
font-src 'self' data:;
connect-src ${connectSrcValue};
worker-src 'self' blob:;
frame-src 'self' https://accounts.google.com https://vercel.live https://googleads.g.doubleclick.net https://tpc.googlesyndication.com https://www.google.com https://fundingchoicesmessages.google.com;
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'none';
${IS_DEVELOPMENT ? '' : 'upgrade-insecure-requests;'}
`.replace(/\s{2,}/g, ' ').trim()
}
export async function proxy(request: NextRequest) {
const response = NextResponse.next()
const { pathname } = request.nextUrl
const SUSPENDED_EXEMPT = ['/suspended', '/auth/', '/api/', '/_next/', '/favicon']
const isSuspendedExempt = SUSPENDED_EXEMPT.some((p) => pathname.startsWith(p))
if (!isSuspendedExempt) {
const suspendedToken = await getToken({ req: request, secret: process.env.NEXTAUTH_SECRET })
if (suspendedToken?.suspended) {
return NextResponse.redirect(new URL('/suspended', request.url))
}
}
if (pathname.startsWith('/admin') || pathname.startsWith('/api/admin')) {
if (request.method === 'OPTIONS' && pathname.startsWith('/api/admin')) {
// Let CORS preflight pass; auth is enforced on actual request methods.
} else {
const token = await getToken({ req: request, secret: process.env.NEXTAUTH_SECRET })
const isAdmin = token?.role === 'admin' && !token?.suspended
if (!isAdmin) {
if (pathname.startsWith('/api/admin')) {
const status = token ? 403 : 401
return NextResponse.json(
{ error: token ? 'Admin access required' : 'Authentication required' },
{ status }
)
}
if (!token) {
const loginUrl = new URL('/auth/login', request.url)
loginUrl.searchParams.set('returnUrl', pathname)
return NextResponse.redirect(loginUrl)
}
return NextResponse.redirect(new URL('/games', request.url))
}
}
}
// Add security headers to all responses
Object.entries(SECURITY_HEADERS).forEach(([key, value]) => {
response.headers.set(key, value)
})
response.headers.set('Content-Security-Policy', buildCspHeaderValue())
// Add CORS headers for API routes.
// When no Origin header is present (same-origin requests), Safari still performs
// access-control checks in certain conditions. Fall back to the server's own origin
// so CORS headers are always present on API responses.
if (pathname.startsWith('/api')) {
const origin = request.headers.get('origin')
const allowedOrigin =
resolveAllowedCorsOrigin(origin) ??
(origin === null ? resolveAllowedCorsOrigin(request.nextUrl.origin) : null)
if (allowedOrigin) {
response.headers.set('Access-Control-Allow-Origin', allowedOrigin)
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Guest-Token')
response.headers.set('Access-Control-Allow-Credentials', 'true')
response.headers.set('Vary', 'Origin')
}
// Handle preflight requests
if (request.method === 'OPTIONS') {
return new NextResponse(null, { status: 200, headers: response.headers })
}
const isUnsafeMethod = !SAFE_METHODS.has(request.method.toUpperCase())
if (
isUnsafeMethod &&
!isSignatureAuthenticatedWebhook(pathname) &&
!isTrustedServerRequest(request) &&
!verifyCsrfToken(request)
) {
return NextResponse.json(
{ error: 'Invalid origin. Possible CSRF attack.' },
{ status: 403 }
)
}
}
return response
}
// Configure which routes the proxy should run on
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - public folder
*/
'/((?!_next/static|_next/image|favicon.ico|public/).*)',
],
}