From 032708cf1c0e6de54794b0818ced293f82c6eadb Mon Sep 17 00:00:00 2001 From: donneypr Date: Tue, 24 Dec 2024 18:05:11 -0500 Subject: [PATCH] Refactor: Simplify and optimize CSP header modification logic --- desktop-app/src/main/main.ts | 51 ++++++++++++++++-------------------- 1 file changed, 23 insertions(+), 28 deletions(-) diff --git a/desktop-app/src/main/main.ts b/desktop-app/src/main/main.ts index 8408dcbe..fd104540 100644 --- a/desktop-app/src/main/main.ts +++ b/desktop-app/src/main/main.ts @@ -142,36 +142,31 @@ const createWindow = async () => { // Add BROWSER_SYNC_HOST to the allowed Content-Security-Policy origins mainWindow.webContents.session.webRequest.onHeadersReceived( async (details, callback) => { - if (details.responseHeaders?.['content-security-policy']) { - let cspHeader = details.responseHeaders['content-security-policy'][0]; - - cspHeader = cspHeader.replace( - 'default-src', - `default-src ${BROWSER_SYNC_HOST}` - ); - cspHeader = cspHeader.replace( - 'script-src', - `script-src ${BROWSER_SYNC_HOST}` - ); - cspHeader = cspHeader.replace( - 'script-src-elem', - `script-src-elem ${BROWSER_SYNC_HOST}` + const cspKey = 'content-security-policy'; + + if (details.responseHeaders?.[cspKey]) { + const cspHeader = details.responseHeaders[cspKey][0]; + + // Define the rules to replace dynamically + const replacements: Record = { + 'default-src': `default-src ${BROWSER_SYNC_HOST}`, + 'script-src': `script-src ${BROWSER_SYNC_HOST}`, + 'script-src-elem': `script-src-elem ${BROWSER_SYNC_HOST}`, + 'connect-src': `connect-src ${BROWSER_SYNC_HOST} wss://${BROWSER_SYNC_HOST} ws://${BROWSER_SYNC_HOST}`, + 'child-src': `child-src ${BROWSER_SYNC_HOST}`, + 'worker-src': `worker-src ${BROWSER_SYNC_HOST}`, + }; + + // Apply replacements + const updatedCSPHeader = Object.entries(replacements).reduce( + (header, [key, value]) => header.replace(key, value), + cspHeader ); - cspHeader = cspHeader.replace( - 'connect-src', - `connect-src ${BROWSER_SYNC_HOST} wss://${BROWSER_SYNC_HOST} ws://${BROWSER_SYNC_HOST}` - ); - cspHeader = cspHeader.replace( - 'child-src', - `child-src ${BROWSER_SYNC_HOST}` - ); - cspHeader = cspHeader.replace( - 'worker-src', - `worker-src ${BROWSER_SYNC_HOST}` - ); // Required when/if the browser-sync script is eventually relocated to a web worker - - details.responseHeaders['content-security-policy'][0] = cspHeader; + + // Update the response headers + details.responseHeaders[cspKey][0] = updatedCSPHeader; } + callback({ responseHeaders: details.responseHeaders }); } );