-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathmiddleware.ts
More file actions
80 lines (70 loc) · 2.33 KB
/
middleware.ts
File metadata and controls
80 lines (70 loc) · 2.33 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
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const nonce = Buffer.from(crypto.randomUUID()).toString('base64');
const isDev = process.env.NODE_ENV === 'development';
// Define CSP directives
// Using strict-dynamic with nonces for scripts
// style-src includes nonce for styled-components or similar if used
const cspDirectives = {
'default-src': ["'self'"],
'script-src': [
"'self'",
`'nonce-${nonce}'`,
"'strict-dynamic'",
isDev ? "'unsafe-eval'" : "",
].filter(Boolean),
'style-src': ["'self'", `'nonce-${nonce}'`, "'unsafe-inline'"], // unsafe-inline often needed for Next.js internal styles
'img-src': ["'self'", "blob:", "data:", "https://*"], // Allow external images
'font-src': ["'self'"],
'object-src': ["'none'"],
'base-uri': ["'self'"],
'form-action': ["'self'"],
'frame-ancestors': ["'none'"],
'connect-src': [
"'self'",
"https://*.stellar.org",
"https://*.soroban-rpc.com",
"https://*.vercel-analytics.com",
isDev ? "ws://localhost:*" : ""
].filter(Boolean),
'upgrade-insecure-requests': [],
};
const cspHeaderValue = Object.entries(cspDirectives)
.map(([key, values]) => {
if (values.length === 0) return key;
return `${key} ${values.join(' ')}`;
})
.join('; ');
const requestHeaders = new Headers(request.headers);
requestHeaders.set('x-nonce', nonce);
// Start with Report-Only as per requirements
const headerName = process.env.CSP_ENFORCE === 'true'
? 'Content-Security-Policy'
: 'Content-Security-Policy-Report-Only';
const response = NextResponse.next({
request: {
headers: requestHeaders,
},
});
response.headers.set(headerName, cspHeaderValue);
return response;
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
{
source: '/((?!api|_next/static|_next/image|favicon.ico).*)',
missing: [
{ type: 'header', key: 'next-router-prefetch' },
{ type: 'header', key: 'purpose', value: 'prefetch' },
],
},
],
};