From 0eecaf8f914d5bf45ea9461abd7418168d60272b Mon Sep 17 00:00:00 2001 From: Adam Bilsing Date: Wed, 4 Sep 2024 20:16:56 -0500 Subject: [PATCH] feat: CPX-632 add CSP with explicit frame-ancestors --- src/middleware.ts | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/middleware.ts b/src/middleware.ts index 662c8fd..e075922 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -1,6 +1,7 @@ import csrf from 'edge-csrf'; import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; +import { authorize } from '~/lib/authorize'; const csrfProtect = csrf({ cookie: { @@ -17,7 +18,25 @@ export async function middleware(request: NextRequest) { return new NextResponse('invalid csrf token', { status: 403 }); } - return response; + const authorized = authorize(request.nextUrl.searchParams.get('authToken') ?? ''); + if (!authorized) { + return new NextResponse('unauthorized', { status: 401 }); + } + + const storeHash = authorized.storeHash; + const cspHeader = ` + frame-ancestors: 'self' 'https://store-${storeHash}.mybigcommerce.com' 'https://store-${storeHash}.my-integration.zone' 'https://store-${storeHash}.my-staging.zone'; + `; + const contentSecurityPolicyHeaderValue = cspHeader + .replace(/\s{2,}/g, ' ') + .trim(); + + response.headers.set( + 'Content-Security-Policy', + contentSecurityPolicyHeaderValue + ) + + return response } export const config = {