Skip to content

Commit

Permalink
CPX-632: add CSP in middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
Adam Bilsing committed Sep 5, 2024
1 parent 3adb3d1 commit 2453d38
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
4 changes: 2 additions & 2 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export default function RootLayout({
};

const { storeHash } = useAppContext();
const allowedParents = () => [
const frameAncestors = [
`https://store-${storeHash}.mybigcommerce.com`,
`https://store-${storeHash}.my-staging.com`,
`https://store-${storeHash}.my-integration.com`
Expand All @@ -42,7 +42,7 @@ export default function RootLayout({
<head>
<meta
http-equiv="Content-Security-Policy"
frame-ancestors={allowedParents()} />
frame-ancestors={frameAncestors} />
<link rel="icon" href="/favicon.svg" />
</head>
<body>
Expand Down
29 changes: 28 additions & 1 deletion src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,34 @@ export async function middleware(request: NextRequest) {
return new NextResponse('invalid csrf token', { status: 403 });
}

return response;
const nonce = Buffer.from(crypto.randomUUID()).toString('base64');
const cspHeader = `
script-src 'self' 'nonce-${nonce}' 'strict-dynamic';
frame-ancestors: 'https://store-*.mybigcommerce.com' 'https://store-*.my-integration.zone' 'https://store-*.my-staging.zone';
`;
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 newResponse = NextResponse.next({
request: {
headers: requestHeaders,
},
})
newResponse.headers.set(
'Content-Security-Policy',
contentSecurityPolicyHeaderValue
)

return newResponse
}

export const config = {
Expand Down

0 comments on commit 2453d38

Please sign in to comment.