@@ -2,16 +2,39 @@ import { NextResponse, type NextRequest } from 'next/server';
22import { getAccessTokenServer } from '@utils/amplify-utils' ;
33import { getBasePath } from '@utils/get-base-path' ;
44
5+ function getContentSecurityPolicy ( nonce : string ) {
6+ const contentSecurityPolicyDirective = {
7+ 'base-uri' : [ `'self'` ] ,
8+ 'default-src' : [ `'none'` ] ,
9+ 'frame-ancestors' : [ `'none'` ] ,
10+ 'font-src' : [ `'self'` , 'https://assets.nhs.uk' ] ,
11+ 'form-action' : [ `'self'` ] ,
12+ 'frame-src' : [ `'self'` ] ,
13+ 'connect-src' : [ `'self'` , 'https://cognito-idp.eu-west-2.amazonaws.com' ] ,
14+ 'img-src' : [ `'self'` ] ,
15+ 'manifest-src' : [ `'self'` ] ,
16+ 'object-src' : [ `'none'` ] ,
17+ 'script-src' : [ `'nonce-${ nonce } '` , `'strict-dynamic'` ] ,
18+ 'style-src' : [ `'self'` ] ,
19+ } ;
20+
21+ if ( process . env . NODE_ENV === 'development' ) {
22+ contentSecurityPolicyDirective [ 'script-src' ] . push ( `'unsafe-eval'` ) ;
23+ }
24+
25+ return Object . entries ( contentSecurityPolicyDirective )
26+ . map ( ( [ key , value ] ) => `${ key } ${ value . join ( ' ' ) } ` )
27+ . join ( '; ' ) ;
28+ }
29+
530function isExcludedPath ( path : string , excludedPaths : string [ ] ) : boolean {
631 return excludedPaths . some ( ( excludedPath ) => path . startsWith ( excludedPath ) ) ;
732}
833
934export async function middleware ( request : NextRequest ) {
1035 const nonce = Buffer . from ( crypto . randomUUID ( ) ) . toString ( 'base64' ) ;
11- const cspUnsafeEval =
12- process . env . NODE_ENV === 'production' ? '' : `http: 'unsafe-eval'` ;
1336
14- const csp = `base-uri 'self'; form-action 'self'; frame-ancestors 'none'; default-src 'none'; connect-src 'self'; font-src 'self' https://assets.nhs.uk; img-src 'self'; script-src 'self' ' nonce- ${ nonce } ' ${ cspUnsafeEval } ; style-src 'self' 'nonce- ${ nonce } '; upgrade-insecure-requests` ;
37+ const csp = getContentSecurityPolicy ( nonce ) ;
1538
1639 const requestHeaders = new Headers ( request . headers ) ;
1740 requestHeaders . set ( 'x-nonce' , nonce ) ;
0 commit comments