Skip to content

Commit

Permalink
♻️Make loadScript function in validator-integration Trusted Types com…
Browse files Browse the repository at this point in the history
…patible (#38703)

* Make loadScript in validator-integration Trusted Types compatible

* Lint fix

* Disable lint to avoid forbidden term error

* Add missing https:// to url comparison

* Update test url to include https://

* Add explanation of why we use the explicit cdn domain
  • Loading branch information
eozmen410 authored Apr 4, 2023
1 parent cec3a0b commit 201864e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
24 changes: 23 additions & 1 deletion src/validator-integration.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,29 @@ export function loadScript(doc, url) {
const script = /** @type {!HTMLScriptElement} */ (
doc.createElement('script')
);
script.src = url;
// Make script.src assignment Trusted Types compatible for compatible browsers
if (self.trustedTypes && self.trustedTypes.createPolicy) {
const policy = self.trustedTypes.createPolicy(
'validator-integration#loadScript',
{
createScriptURL: function (url) {
// Only allow trusted URLs
// Using explicit cdn domain as no other AMP Cache hosts validator_
// wasm so we can assume the explicit cdn domain is cdn.ampproject.org
// instead of using the dynamic cdn value from src/config/urls.js
// eslint-disable-next-line local/no-forbidden-terms
if (url === 'https://cdn.ampproject.org/v0/validator_wasm.js') {
return url;
} else {
return '';
}
},
}
);
script.src = policy.createScriptURL(url);
} else {
script.src = url;
}
propagateNonce(doc, script);

const promise = loadPromise(script).then(
Expand Down
5 changes: 4 additions & 1 deletion test/unit/test-validator-integration.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,10 @@ describes.fakeWin('validator-integration', {}, (env) => {
.stub(eventHelper, 'loadPromise')
.returns(Promise.resolve());

loadScript(win.document, 'http://example.com');
loadScript(
win.document,
'https://cdn.ampproject.org/v0/validator_wasm.js'
);

expect(loadScriptStub).calledWith(
env.sandbox.match((el) => el.nonce === '123')
Expand Down

0 comments on commit 201864e

Please sign in to comment.