-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmiddleware.ts
More file actions
97 lines (84 loc) · 3.1 KB
/
middleware.ts
File metadata and controls
97 lines (84 loc) · 3.1 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
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { applyRateLimit } from './lib/rate-limit';
/**
* Middleware - Security, Rate Limiting & Basic Route Protection
*
* This middleware handles:
* 1. Rate limiting (to prevent abuse and DoS attacks)
* 2. Security headers (CSP, HSTS, etc.)
* 3. Basic authentication check (presence of auth cookies)
*
* NOTE: Full authentication and permission checks are done in pages/components
* to avoid Edge Runtime compatibility issues with Supabase client.
*/
// Public routes that don't require authentication
const publicRoutes = [
'/',
'/login',
'/signup',
'/setup',
'/onboarding',
'/invite',
'/client-invite', // Client portal invitations
'/pending-approval',
'/welcome',
'/reset-password',
'/forgot-password',
'/auth/callback',
];
/**
* Check if user has Supabase auth cookies
* We only check for cookie presence, not validity, to avoid Edge Runtime issues
*/
function hasAuthCookies(req: NextRequest): boolean {
const allCookies = req.cookies.getAll();
// Check for any Supabase auth cookie (handles all naming patterns):
// - sb-movalab-auth (our custom cookie name)
// - sb-access-token / sb-refresh-token (default Supabase)
// - sb-<project-ref>-auth-token (Supabase SSR format)
return allCookies.some(cookie => cookie.name.startsWith('sb-'));
}
export async function middleware(req: NextRequest) {
const pathname = req.nextUrl.pathname;
// Apply rate limiting to API routes
if (pathname.startsWith('/api')) {
const rateLimitResponse = await applyRateLimit(req);
if (rateLimitResponse) {
return rateLimitResponse; // Rate limit exceeded
}
}
// Create response with security headers
const res = NextResponse.next();
// Add security headers
res.headers.set('X-Frame-Options', 'DENY');
res.headers.set('X-Content-Type-Options', 'nosniff');
res.headers.set('X-XSS-Protection', '1; mode=block');
res.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
// Add HSTS in production
if (process.env.NODE_ENV === 'production') {
res.headers.set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
}
// Allow public routes (and their sub-paths), Next.js internals, and API routes
const isPublicRoute = publicRoutes.some(route => pathname === route || pathname.startsWith(route + '/'));
if (isPublicRoute || pathname.startsWith('/_next') || pathname.startsWith('/api')) {
return res;
}
// Simple auth check: If no auth cookies, redirect to login
// Pages will do full authentication validation
const hasAuth = hasAuthCookies(req);
if (!hasAuth) {
const redirectUrl = new URL('/login', req.url);
redirectUrl.searchParams.set('redirectTo', pathname);
return NextResponse.redirect(redirectUrl);
}
// Allow the request to proceed
// Full authentication, role checks, and permission validation
// happen in the actual page components to avoid Edge Runtime issues
return res;
}
export const config = {
matcher: [
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
],
};