-
Notifications
You must be signed in to change notification settings - Fork 74
/
full.js
87 lines (78 loc) · 2.39 KB
/
full.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the W3C SOFTWARE AND DOCUMENT NOTICE AND LICENSE.
*
* https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document
*/
/**
* @fileoverview Entry point for a polyfill that enforces the types.
*/
import './api_only.js';
import {TrustedTypesEnforcer} from '../enforcer.js';
import {TrustedTypeConfig} from '../data/trustedtypeconfig.js';
/* eslint-enable no-unused-vars */
/**
* Tries to guess a CSP policy from:
* - the current polyfill script element text content (if prefixed with
* "Content-Security-Policy:")
* - the data-csp attribute value of the current script element.
* - meta header
* @return {?string} Guessed CSP value, or null.
*/
function detectPolicy() {
try {
const currentScript = document.currentScript || (function() {
const scripts = document.getElementsByTagName('script');
return scripts[scripts.length - 1];
})();
const bodyPrefix = 'Content-Security-Policy:';
if (currentScript &&
currentScript.textContent.trim().substr(0, bodyPrefix.length) ==
bodyPrefix) {
return currentScript.textContent.trim().slice(bodyPrefix.length);
}
if (currentScript.dataset['csp']) {
return currentScript.dataset['csp'];
}
const cspInMeta = document.head.querySelector(
'meta[http-equiv^="Content-Security-Policy"]');
if (cspInMeta) {
return cspInMeta['content'].trim();
}
} catch (e) {
return null;
}
return null;
}
/**
* Bootstraps all trusted types polyfill and their enforcement.
*/
export function bootstrap() {
const csp = detectPolicy();
const config = csp ? TrustedTypeConfig.fromCSP(csp) : new TrustedTypeConfig(
/* isLoggingEnabled */ false,
/* isEnforcementEnabled */ false,
/* allowedPolicyNames */ [],
/* allowDuplicates */ true);
const trustedTypesEnforcer = new TrustedTypesEnforcer(config);
trustedTypesEnforcer.install();
}
/**
* Determines if the enforcement should be enabled.
* @return {boolean}
*/
function shouldBootstrap() {
for (const rootProperty of ['trustedTypes', 'TrustedTypes']) {
if (window[rootProperty] && !window[rootProperty]['_isPolyfill_']) {
// Native implementation exists
return false;
}
}
return true;
}
// Bootstrap only if native implementation is missing.
if (shouldBootstrap()) {
bootstrap();
}