From fa067c17465a646d19316f3c8e472436736acfb3 Mon Sep 17 00:00:00 2001 From: vcua-mobify <47404250+vcua-mobify@users.noreply.github.com> Date: Tue, 28 Jan 2025 09:29:02 -0800 Subject: [PATCH] @W-17307052@ Factor in CSP header when generating service worker etag (#2191) * Factor in CSP header when generating service worker etag * Update CHANGELOG.md * enclose etag in double quotes * Lint * Apply suggestions --- packages/pwa-kit-runtime/CHANGELOG.md | 1 + .../src/ssr/server/build-remote-server.js | 24 +++++++++++++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/packages/pwa-kit-runtime/CHANGELOG.md b/packages/pwa-kit-runtime/CHANGELOG.md index 74aa323121..c80ae51b7f 100644 --- a/packages/pwa-kit-runtime/CHANGELOG.md +++ b/packages/pwa-kit-runtime/CHANGELOG.md @@ -1,4 +1,5 @@ ## v3.9.0-dev (Oct 29, 2024) +- Fix stale service worker file that could cause requests to still use old Content-Security-Policy [#2191](https://github.com/SalesforceCommerceCloud/pwa-kit/pull/2191) ## v3.8.0 (Oct 28, 2024) - Add proxy handling for trusted agent on behalf of (TAOB) requests [#2077](https://github.com/SalesforceCommerceCloud/pwa-kit/pull/2077) diff --git a/packages/pwa-kit-runtime/src/ssr/server/build-remote-server.js b/packages/pwa-kit-runtime/src/ssr/server/build-remote-server.js index 7c318eddbf..39be4694b8 100644 --- a/packages/pwa-kit-runtime/src/ssr/server/build-remote-server.js +++ b/packages/pwa-kit-runtime/src/ssr/server/build-remote-server.js @@ -12,7 +12,8 @@ import { SET_COOKIE, CACHE_CONTROL, NO_CACHE, - X_ENCODED_HEADERS + X_ENCODED_HEADERS, + CONTENT_SECURITY_POLICY } from './constants' import { catchAndLog, @@ -911,8 +912,27 @@ export const RemoteServerFactory = { const content = fs.readFileSync(workerFilePath, {encoding: 'utf8'}) + // If the service worker is not updated when content security policy headers inside + // ssr.js are changed, then service worker initiated requests will continue to use + // the old CSP headers. + // + // This is problematic in stacked CDN setups where an old service worker with + // old CSPs can remain cached if the content of the service worker itself is not changed. + // + // To ensure the service worker is refetched when CSPs are changed, we factor in + // the CSP headers when generating the Etag. + // + // See https://gus.lightning.force.com/lightning/r/ADM_Work__c/a07EE000025yeu9YAA/view + // and https://salesforce-internal.slack.com/archives/C01GLHLBPT5/p1730739370922629 + // for more details. + + const contentSecurityPolicyHeader = res.getHeaders()[CONTENT_SECURITY_POLICY] || '' + // Serve the file, with a strong ETag - res.set('etag', getHashForString(content)) + // For this to be a valid ETag, the string must be placed between "" + // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag#etag_value for + // more details + res.set('etag', `"${getHashForString(content + contentSecurityPolicyHeader)}"`) res.set(CONTENT_TYPE, 'application/javascript') res.send(content) },