From 10e6c44c0e9e6fcc5c12d80287db90c4b6b15820 Mon Sep 17 00:00:00 2001 From: Daniel <45217974+w3bdesign@users.noreply.github.com> Date: Mon, 22 Jul 2024 21:55:01 +0200 Subject: [PATCH] CSP middleware --- next.config.mjs | 3 +++ src/app/middleware.ts | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 src/app/middleware.ts diff --git a/next.config.mjs b/next.config.mjs index df0484d5..b25c79a4 100644 --- a/next.config.mjs +++ b/next.config.mjs @@ -21,10 +21,13 @@ const nextConfig = { key: 'X-Content-Type-Options', value: 'nosniff', }, + /* { key: 'Content-Security-Policy', value: "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' https://cdn.sanity.io data:; font-src 'self' data:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'; form-action 'self'; upgrade-insecure-requests;", }, + */ + ], }, ]; diff --git a/src/app/middleware.ts b/src/app/middleware.ts new file mode 100644 index 00000000..f39da993 --- /dev/null +++ b/src/app/middleware.ts @@ -0,0 +1,41 @@ +import { NextRequest, NextResponse } from 'next/server' + +export function middleware(request: NextRequest) { + const nonce = Buffer.from(crypto.randomUUID()).toString('base64') + const cspHeader = ` + default-src 'self'; + script-src 'self' 'nonce-${nonce}' 'strict-dynamic'; + style-src 'self' 'nonce-${nonce}'; + img-src 'self' blob: data:; + font-src 'self'; + object-src 'none'; + base-uri 'self'; + form-action 'self'; + frame-ancestors 'none'; + upgrade-insecure-requests; +` + // Replace newline characters and spaces + const contentSecurityPolicyHeaderValue = cspHeader + .replace(/\s{2,}/g, ' ') + .trim() + + const requestHeaders = new Headers(request.headers) + requestHeaders.set('x-nonce', nonce) + + requestHeaders.set( + 'Content-Security-Policy', + contentSecurityPolicyHeaderValue + ) + + const response = NextResponse.next({ + request: { + headers: requestHeaders, + }, + }) + response.headers.set( + 'Content-Security-Policy', + contentSecurityPolicyHeaderValue + ) + + return response +} \ No newline at end of file