-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathmiddleware.ts
More file actions
163 lines (139 loc) · 5.71 KB
/
Copy pathmiddleware.ts
File metadata and controls
163 lines (139 loc) · 5.71 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 type { NextRequest } from 'next/server';
import { verifySessionToken, SESSION_COOKIE_NAME } from '@/lib/auth/session';
import { canAccessPath } from '@/lib/auth/roles';
// ─── CSP ─────────────────────────────────────────────────────────────────────
function buildCsp(): string {
const isDev = process.env.NODE_ENV === 'development';
const directives: Record<string, string[]> = {
'default-src': ["'self'"],
'script-src': isDev
? ["'self'", "'unsafe-eval'", "'unsafe-inline'"]
: ["'self'"],
'style-src': ["'self'", "'unsafe-inline'"],
'img-src': ["'self'", 'data:', 'blob:'],
'font-src': ["'self'"],
'connect-src': [
"'self'",
'https://horizon-testnet.stellar.org',
'https://soroban-testnet.stellar.org',
'https://horizon.stellar.org',
'https://soroban-rpc.stellar.org',
],
'worker-src': ["'self'", 'blob:'],
'child-src': ["'self'", 'blob:'],
'object-src': ["'none'"],
'base-uri': ["'self'"],
'form-action': ["'self'"],
'frame-ancestors': ["'none'"],
};
if (typeof WebAssembly !== 'undefined') {
directives['script-src'].push("'wasm-unsafe-eval'");
}
if (!isDev) {
directives['report-uri'] = ['/api/csp-report'];
}
return Object.entries(directives)
.map(([key, values]) => `${key} ${values.join(' ')}`)
.join('; ');
}
function applySecurityHeaders(response: NextResponse): void {
const csp = buildCsp();
response.headers.set('Content-Security-Policy', csp);
response.headers.set('X-Frame-Options', 'DENY');
response.headers.set('X-Content-Type-Options', 'nosniff');
response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
response.headers.set('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
response.headers.set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
response.headers.set('X-XSS-Protection', '0');
}
// ─── Route classification ────────────────────────────────────────────────────
const PUBLIC_PATHS = ['/', '/login', '/api/health', '/api/csp-report'];
const PUBLIC_PREFIXES = ['/api/auth/'];
const PROTECTED_PREFIXES = ['/dashboard', '/payroll', '/employees', '/settings', '/history', '/treasury', '/compliance', '/setup', '/incidents', '/admin'];
const ADMIN_ONLY_PREFIXES = ['/payroll/cancel', '/compliance/revoke', '/treasury/update', '/employees/deactivate', '/api/payroll/\:\s*\d+', '/api/compliance/\:\s*\d+', '/api/treasury/\:\s*\d+', '/api/employees/\:\s*\d+'];
function isPublicRoute(pathname: string): boolean {
if (PUBLIC_PATHS.includes(pathname)) return true;
return PUBLIC_PREFIXES.some((prefix) => pathname.startsWith(prefix));
}
function isProtectedRoute(pathname: string): boolean {
return PROTECTED_PREFIXES.some((prefix) => pathname.startsWith(prefix));
}
function isAdminOnlyRoute(pathname: string): boolean {
return ADMIN_ONLY_PREFIXES.some(pattern => {
const regex = new RegExp(pattern.replace(/:/g, '\\:'));
return regex.test(pathname);
});
}
function isApiRoute(pathname: string): boolean {
return pathname.startsWith('/api/');
}
// ─── Middleware ───────────────────────────────────────────────────────────────
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Public routes — security headers only
if (isPublicRoute(pathname)) {
const response = NextResponse.next();
applySecurityHeaders(response);
return response;
}
// Protected routes — verify session
if (isProtectedRoute(pathname) || (isApiRoute(pathname) && !isPublicRoute(pathname))) {
const token = request.cookies.get(SESSION_COOKIE_NAME)?.value;
if (!token) {
if (isApiRoute(pathname)) {
const response = NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
applySecurityHeaders(response);
return response;
}
const loginUrl = new URL('/login', request.url);
loginUrl.searchParams.set('redirect', pathname);
const response = NextResponse.redirect(loginUrl);
applySecurityHeaders(response);
return response;
}
const session = await verifySessionToken(token);
if (!session) {
if (isApiRoute(pathname)) {
const response = NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
applySecurityHeaders(response);
return response;
}
const loginUrl = new URL('/login', request.url);
loginUrl.searchParams.set('redirect', pathname);
const response = NextResponse.redirect(loginUrl);
applySecurityHeaders(response);
return response;
}
// Role-aware route guard
if (!canAccessPath(session.role, pathname)) {
if (isApiRoute(pathname)) {
const response = NextResponse.json(
{ error: 'Forbidden' },
{ status: 403 }
);
applySecurityHeaders(response);
return response;
}
const dashboardUrl = new URL('/', request.url);
const response = NextResponse.redirect(dashboardUrl);
applySecurityHeaders(response);
return response;
}
}
// Default — pass through with security headers
const response = NextResponse.next();
applySecurityHeaders(response);
return response;
}
export const config = {
matcher: [
'/((?!_next/static|_next/image|favicon.ico).*)',
],
};