Skip to content

Commit

Permalink
@W-17307052@ Factor in CSP header when generating service worker etag (
Browse files Browse the repository at this point in the history
…#2191)

* Factor in CSP header when generating service worker etag

* Update CHANGELOG.md

* enclose etag in double quotes

* Lint

* Apply suggestions
  • Loading branch information
vcua-mobify authored Jan 28, 2025
1 parent bc83836 commit fa067c1
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
1 change: 1 addition & 0 deletions packages/pwa-kit-runtime/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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)
Expand Down
24 changes: 22 additions & 2 deletions packages/pwa-kit-runtime/src/ssr/server/build-remote-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import {
SET_COOKIE,
CACHE_CONTROL,
NO_CACHE,
X_ENCODED_HEADERS
X_ENCODED_HEADERS,
CONTENT_SECURITY_POLICY
} from './constants'
import {
catchAndLog,
Expand Down Expand Up @@ -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)
},
Expand Down

0 comments on commit fa067c1

Please sign in to comment.