Skip to content

Commit

Permalink
♻️🐛 [Trusted Types] Make AmpWorker Trusted Types compatible (#39211)
Browse files Browse the repository at this point in the history
* ♻️🐛 [Trusted Types] Make AmpWorker Trusted Types compatible (#6)

* fix regex to match subdomains properly

* fixing regex

* fixing hostname regex

* typo

* lint changes

* lint fix

* conditional fix

* testing string conversion before passing

* more permissive for testing

* update test regex with more urls

* fixing hostname

* adding one more url to test allowlist

* removing restrictions on testing due to dynamic url

* mjs file extensions

* replace slice with endsWith for readability
  • Loading branch information
youssef-attia authored Jul 31, 2023
1 parent a7cf8a6 commit 54c0400
Showing 1 changed file with 50 additions and 7 deletions.
57 changes: 50 additions & 7 deletions src/web-worker/amp-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,12 +72,42 @@ class AmpWorker {
// Use RTV to make sure we fetch prod/canary/experiment correctly.
const useLocal = getMode().localDev || getMode().test;
const useRtvVersion = !useLocal;
const url = calculateEntryPointScriptUrl(
loc,
'ww',
useLocal,
useRtvVersion
);

let url = '';

const policy = {
createScriptURL: function (url) {
// Only allow the correct webworker url to pass through
const regexURL =
/^https:\/\/([a-zA-Z0-9_-]+\.)?cdn\.ampproject\.org(\/.*)?$/;

if (
(regexURL.test(url) || getMode().test) &&
(url.endsWith('ww.js') ||
url.endsWith('ww.min.js') ||
url.endsWith('ww.mjs') ||
url.endsWith('ww.min.mjs'))
) {
return url;
} else {
return '';
}
},
};

if (self.trustedTypes && self.trustedTypes.createPolicy) {
const policy = self.trustedTypes.createPolicy(
'amp-worker#fetchUrl',
policy
);
}

url = policy
.createScriptURL(
calculateEntryPointScriptUrl(loc, 'ww', useLocal, useRtvVersion)
)
.toString();

dev().fine(TAG, 'Fetching web worker from', url);

/** @private {Worker} */
Expand All @@ -103,7 +133,20 @@ class AmpWorker {
type: 'text/javascript',
});
const blobUrl = win.URL.createObjectURL(blob);
this.worker_ = new win.Worker(blobUrl);
if (self.trustedTypes && self.trustedTypes.createPolicy) {
// We can trust the url for this policy usage because the blobUrl pulls the script from a controlled source, the ww.js file.
const policy = self.trustedTypes.createPolicy(
'amp-worker#constructor',
{
createScriptURL: function (url) {
return url;
},
}
);
this.worker_ = new win.Worker(policy.createScriptURL(blobUrl));
} else {
this.worker_ = new win.Worker(blobUrl);
}
this.worker_.onmessage = this.receiveMessage_.bind(this);
});

Expand Down

0 comments on commit 54c0400

Please sign in to comment.