-
Notifications
You must be signed in to change notification settings - Fork 976
/
Copy pathmiddleware.ts
139 lines (119 loc) · 3.4 KB
/
middleware.ts
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
import micromatch from 'micromatch';
import { getToken } from 'next-auth/jwt';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import env from './lib/env';
// Constants for security headers
const SECURITY_HEADERS = {
'Referrer-Policy': 'strict-origin-when-cross-origin',
'Permissions-Policy': 'geolocation=(), microphone=()',
'Cross-Origin-Embedder-Policy': 'require-corp',
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Resource-Policy': 'same-site',
} as const;
// Generate CSP
const generateCSP = (): string => {
const policies = {
'default-src': ["'self'"],
'img-src': [
"'self'",
'boxyhq.com',
'*.boxyhq.com',
'*.dicebear.com',
'data:',
],
'script-src': [
"'self'",
"'unsafe-inline'",
"'unsafe-eval'",
'*.gstatic.com',
'*.google.com',
],
'style-src': ["'self'", "'unsafe-inline'"],
'connect-src': [
"'self'",
'*.google.com',
'*.gstatic.com',
'boxyhq.com',
'*.ingest.sentry.io',
'*.mixpanel.com',
],
'frame-src': ["'self'", '*.google.com', '*.gstatic.com'],
'font-src': ["'self'"],
'object-src': ["'none'"],
'base-uri': ["'self'"],
'form-action': ["'self'"],
'frame-ancestors': ["'none'"],
};
return Object.entries(policies)
.map(([key, values]) => `${key} ${values.join(' ')}`)
.concat(['upgrade-insecure-requests'])
.join('; ');
};
// Add routes that don't require authentication
const unAuthenticatedRoutes = [
'/api/hello',
'/api/health',
'/api/auth/**',
'/api/oauth/**',
'/api/scim/v2.0/**',
'/api/invitations/*',
'/api/webhooks/stripe',
'/api/webhooks/dsync',
'/auth/**',
'/invitations/*',
'/terms-condition',
'/unlock-account',
'/login/saml',
'/.well-known/*',
];
export default async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
// Bypass routes that don't require authentication
if (micromatch.isMatch(pathname, unAuthenticatedRoutes)) {
return NextResponse.next();
}
const redirectUrl = new URL('/auth/login', req.url);
redirectUrl.searchParams.set('callbackUrl', encodeURI(req.url));
// JWT strategy
if (env.nextAuth.sessionStrategy === 'jwt') {
const token = await getToken({
req,
});
if (!token) {
return NextResponse.redirect(redirectUrl);
}
}
// Database strategy
else if (env.nextAuth.sessionStrategy === 'database') {
const url = new URL('/api/auth/session', req.url);
const response = await fetch(url, {
headers: {
'Content-Type': 'application/json',
cookie: req.headers.get('cookie') || '',
},
});
const session = await response.json();
if (!session.user) {
return NextResponse.redirect(redirectUrl);
}
}
const requestHeaders = new Headers(req.headers);
const csp = generateCSP();
requestHeaders.set('Content-Security-Policy', csp);
const response = NextResponse.next({
request: { headers: requestHeaders },
});
if (env.securityHeadersEnabled) {
// Set security headers
response.headers.set('Content-Security-Policy', csp);
Object.entries(SECURITY_HEADERS).forEach(([key, value]) => {
response.headers.set(key, value);
});
}
// All good, let the request through
return response;
}
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico|api/auth/session).*)'],
};