Skip to content

Commit

Permalink
feat(dcellar-web-ui): add csp rules
Browse files Browse the repository at this point in the history
  • Loading branch information
devinxl committed Oct 30, 2024
1 parent fff19a1 commit 3ec6bc7
Showing 1 changed file with 67 additions and 0 deletions.
67 changes: 67 additions & 0 deletions apps/dcellar-web-ui/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { NextResponse } from 'next/server';

export function middleware(request) {
const nonce = Buffer.from(crypto.randomUUID()).toString('base64');
const cspHeader = `
default-src 'self';
script-src 'self' 'nonce-${nonce}' 'strict-dynamic' https: ${
process.env.NODE_ENV === 'production' ? '' : "'unsafe-eval'"
} 'report-sample' https://www.googletagmanager.com https://www.google-analytics.com https://analytics.google.com;
style-src 'self' 'nonce-${nonce}' https://fonts.googleapis.com;
img-src 'self' blob: data: https: https://www.google-analytics.com https://www.googletagmanager.com;
font-src 'self' https://fonts.gstatic.com;
connect-src 'self' https://www.google-analytics.com https://analytics.google.com;
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'none';
frame-src 'self';
media-src 'self';
manifest-src 'self';
worker-src 'self' blob:;
upgrade-insecure-requests;
report-uri https://your-report-collector.example.com/csp-reports;
report-to csp-endpoint;
`;

const reportToHeader = {
group: 'csp-endpoint',
max_age: 10886400,
endpoints: [{ url: 'https://your-report-collector.example.com/csp-reports' }],
};

const requestHeaders = new Headers(request.headers);
requestHeaders.set('x-nonce', nonce);
requestHeaders.set('Content-Security-Policy', cspHeader.replace(/\s{2,}/g, ' ').trim());
requestHeaders.set('Report-To', JSON.stringify(reportToHeader));

const response = NextResponse.next({
request: {
headers: requestHeaders,
},
});

response.headers.set('Content-Security-Policy', cspHeader.replace(/\s{2,}/g, ' ').trim());
response.headers.set('Report-To', JSON.stringify(reportToHeader));

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' },
],
},
],
};

0 comments on commit 3ec6bc7

Please sign in to comment.