Skip to content

Commit 201864e

Browse files
authored
♻️Make loadScript function in validator-integration Trusted Types compatible (ampproject#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
1 parent cec3a0b commit 201864e

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

Diff for: src/validator-integration.js

+23-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,29 @@ export function loadScript(doc, url) {
4444
const script = /** @type {!HTMLScriptElement} */ (
4545
doc.createElement('script')
4646
);
47-
script.src = url;
47+
// Make script.src assignment Trusted Types compatible for compatible browsers
48+
if (self.trustedTypes && self.trustedTypes.createPolicy) {
49+
const policy = self.trustedTypes.createPolicy(
50+
'validator-integration#loadScript',
51+
{
52+
createScriptURL: function (url) {
53+
// Only allow trusted URLs
54+
// Using explicit cdn domain as no other AMP Cache hosts validator_
55+
// wasm so we can assume the explicit cdn domain is cdn.ampproject.org
56+
// instead of using the dynamic cdn value from src/config/urls.js
57+
// eslint-disable-next-line local/no-forbidden-terms
58+
if (url === 'https://cdn.ampproject.org/v0/validator_wasm.js') {
59+
return url;
60+
} else {
61+
return '';
62+
}
63+
},
64+
}
65+
);
66+
script.src = policy.createScriptURL(url);
67+
} else {
68+
script.src = url;
69+
}
4870
propagateNonce(doc, script);
4971

5072
const promise = loadPromise(script).then(

Diff for: test/unit/test-validator-integration.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,10 @@ describes.fakeWin('validator-integration', {}, (env) => {
7171
.stub(eventHelper, 'loadPromise')
7272
.returns(Promise.resolve());
7373

74-
loadScript(win.document, 'http://example.com');
74+
loadScript(
75+
win.document,
76+
'https://cdn.ampproject.org/v0/validator_wasm.js'
77+
);
7578

7679
expect(loadScriptStub).calledWith(
7780
env.sandbox.match((el) => el.nonce === '123')

0 commit comments

Comments
 (0)