-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
264 lines (237 loc) · 9.57 KB
/
middleware.ts
File metadata and controls
264 lines (237 loc) · 9.57 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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'
// IMPORTANT: Edge runtime cannot use Node-only libraries (Supabase service role, etc.)
// We must not import code that references Node APIs from middleware.
import { NextResponse } from 'next/server'
import type { NextFetchEvent, NextRequest, NextMiddleware } from 'next/server'
import { handleJudgeRedirects } from '@/lib/middleware/judge-redirects'
import { createSecurityConfig, getSecurityHeaders, getCacheHeaders } from '@/lib/security/headers'
import {
enforceCSRFProtection,
getOrCreateCSRFToken,
setCSRFCookie,
addCSRFDebugHeaders,
} from '@/lib/security/csrf'
// Edge-safe logging (Edge runtime doesn't support all Node.js APIs)
// Note: Middleware always runs on Edge runtime in Next.js - no need to declare it
const edgeLogger = {
error: (msg: string, data?: unknown, err?: Error): void => {
if (process.env.NODE_ENV === 'development') {
console.error(`[middleware] ${msg}`, data, err)
}
},
warn: (msg: string, data?: unknown, err?: Error): void => {
if (process.env.NODE_ENV === 'development') {
console.warn(`[middleware] ${msg}`, data, err)
}
},
}
const isProtectedRoute = createRouteMatcher([
'/profile(.*)',
'/settings(.*)',
'/dashboard(.*)',
'/welcome(.*)',
'/ads/buy', // NEW: require sign-in to view purchase page
'/api/checkout(.*)', // NEW: protect all checkout API routes
'/api/billing(.*)', // NEW: protect billing routes
'/api/chat(.*)', // AI chatbox requires authentication to prevent bot abuse
])
const isAdminRoute = createRouteMatcher(['/admin(.*)'])
const clerkKeys = {
publishable: process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY,
secret: process.env.CLERK_SECRET_KEY,
}
const isProduction = process.env.NODE_ENV === 'production'
const isDevelopment = process.env.NODE_ENV === 'development'
// Accept both test keys (pk_test_*, sk_test_*) and live keys (pk_live_*, sk_live_*)
const hasValidClerkKeys = Boolean(
clerkKeys.publishable &&
clerkKeys.secret &&
(clerkKeys.publishable.startsWith('pk_test_') ||
clerkKeys.publishable.startsWith('pk_live_')) &&
(clerkKeys.secret.startsWith('sk_test_') || clerkKeys.secret.startsWith('sk_live_')) &&
!clerkKeys.publishable.includes('YOUR_') &&
!clerkKeys.publishable.includes('CONFIGURE')
)
// SECURITY: Log critical error if Clerk keys are missing in production
// Note: Netlify edge functions receive env vars at runtime, not build time
// We log the error but don't crash the edge function to allow deployment
if (!hasValidClerkKeys && isProduction) {
console.error('[MIDDLEWARE] CRITICAL: Clerk authentication keys missing in production')
console.error('[MIDDLEWARE] Protected routes will not be secured')
console.error(
'[MIDDLEWARE] Verify NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY and CLERK_SECRET_KEY in Netlify'
)
}
// In development, allow running without auth but log a clear warning
if (!hasValidClerkKeys && isDevelopment) {
edgeLogger.warn('Running in INSECURE MODE: Clerk keys not configured', {
publishableConfigured: Boolean(clerkKeys.publishable),
secretConfigured: Boolean(clerkKeys.secret),
publishablePrefix: clerkKeys.publishable?.substring(0, 8) || 'missing',
message:
'Protected routes will not require authentication. This is only acceptable in local development.',
help: 'Get development keys from https://dashboard.clerk.com → Your App → API Keys → Test Keys',
})
}
// Helper function to handle legacy auth route redirects
function handleLegacyAuthRedirects(request: NextRequest): NextResponse | null {
const url = request.nextUrl.clone()
if (url.pathname === '/signup') {
url.pathname = '/sign-up'
return NextResponse.redirect(url)
}
if (url.pathname === '/login') {
url.pathname = '/sign-in'
return NextResponse.redirect(url)
}
return null
}
// Always use clerkMiddleware() as the default export so Clerk can detect it
// Handle missing keys inside the callback to allow graceful degradation
export default clerkMiddleware(
async (auth, request: NextRequest) => {
try {
// SECURITY: Enforce CSRF protection on state-changing requests
// This prevents cross-site request forgery attacks on payment/admin routes
const csrfError = enforceCSRFProtection(request)
if (csrfError) {
if (isProduction) {
console.error('[MIDDLEWARE] CSRF validation failed:', {
method: request.method,
path: request.nextUrl.pathname,
origin: request.headers.get('origin'),
})
}
return csrfError
}
// Handle legacy auth route redirects (always)
const legacyRedirect = handleLegacyAuthRedirects(request)
if (legacyRedirect) {
return legacyRedirect
}
// Handle judge redirects (always)
const judgeRedirect = handleJudgeRedirects(request)
if (judgeRedirect) {
return judgeRedirect
}
// If Clerk keys are not configured, handle protected routes gracefully
if (!hasValidClerkKeys) {
// For protected routes without Clerk keys, redirect to sign-in in production
// In development, allow access but log warning
if (isProtectedRoute(request) || isAdminRoute(request)) {
if (isProduction) {
const signInUrl = request.nextUrl.clone()
signInUrl.pathname = '/sign-in'
signInUrl.searchParams.set('redirect_url', request.nextUrl.pathname)
return NextResponse.redirect(signInUrl)
} else {
edgeLogger.warn(
`Accessing protected route ${request.nextUrl.pathname} without Clerk keys configured`
)
}
}
return baseMiddleware(request)
}
// Clerk keys are configured - proceed with normal auth flow
if (isProtectedRoute(request)) {
const isApiRoute = request.nextUrl.pathname.startsWith('/api/')
if (isApiRoute) {
// API routes: return JSON error instead of HTML redirect
const { userId } = await auth()
if (!userId) {
return NextResponse.json(
{
error: 'Authentication required',
code: 'AUTH_REQUIRED',
message: 'You must be signed in to access this endpoint',
},
{ status: 401 }
)
}
} else {
// Page routes: maintain HTML redirect behavior
await auth.protect()
}
// Do NOT attempt Supabase/service role user mapping here (Edge runtime)
}
if (isAdminRoute(request)) {
await auth.protect()
// Edge runtime: skip Supabase/service role user mapping and MFA checks here.
// MFA enforcement is handled in server-side admin routes.
}
return baseMiddleware(request)
} catch (error) {
// Log error but don't crash - allow request to continue
// Edge functions must remain stable even with auth failures
if (isProduction) {
console.error('[MIDDLEWARE] Clerk middleware error in production:', error)
} else {
edgeLogger.warn(
'Clerk middleware failed in development; falling back to base handler',
undefined,
error as Error
)
}
return baseMiddleware(request)
}
},
{
debug: process.env.NODE_ENV === 'development',
clockSkewInMs: 10000,
}
)
function baseMiddleware(request: NextRequest): NextResponse {
const response = NextResponse.next()
const config = createSecurityConfig()
// SECURITY: Set CSRF token cookie on all responses
// This ensures clients always have a fresh token for state-changing requests
const csrfToken = getOrCreateCSRFToken(request)
setCSRFCookie(response, csrfToken)
// Add CSRF debug headers in development
addCSRFDebugHeaders(response, request)
// Centralized security headers (CSP/HSTS/etc.)
const securityHeaders = getSecurityHeaders(config)
for (const [key, value] of Object.entries(securityHeaders)) {
response.headers.set(key, value as string)
}
// CRITICAL FIX: Apply CORS headers to all requests to allow same-origin API calls
// This fixes the "Failed to fetch" error on Netlify deployments
const origin = request.headers.get('origin')
const requestUrl = new URL(request.url)
// Allow requests from same origin (e.g., netlify.app calling its own API)
if (origin && origin === requestUrl.origin) {
response.headers.set('Access-Control-Allow-Origin', origin)
response.headers.set('Access-Control-Allow-Methods', 'GET, HEAD, POST, OPTIONS')
response.headers.set(
'Access-Control-Allow-Headers',
'Content-Type, Authorization, X-Requested-With, X-CSRF-Token'
)
response.headers.set('Access-Control-Max-Age', '86400')
}
// Cache control based on path
const cacheHeaders = getCacheHeaders(request.nextUrl.pathname)
for (const [key, value] of Object.entries(cacheHeaders)) {
response.headers.set(key, value as string)
}
return response
}
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)
* - api/ (most API routes - they handle auth internally)
*
* THEN explicitly include the protected API routes:
* - /api/checkout/* (requires Clerk auth for user subscriptions)
* - /api/billing/* (requires Clerk auth for billing management)
* - /api/chat/* (requires Clerk auth to prevent abuse)
*/
'/((?!_next/static|_next/image|favicon.ico|api/).*)',
'/api/checkout/:path*',
'/api/billing/:path*',
'/api/chat/:path*',
],
}