dompurify 3.3.3 → 3.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/purify.js CHANGED
@@ -1,1405 +1,1478 @@
1
- /*! @license DOMPurify 3.3.3 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.3.3/LICENSE */
1
+ /*! @license DOMPurify 3.4.1 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.1/LICENSE */
2
2
 
3
3
  (function (global, factory) {
4
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
5
- typeof define === 'function' && define.amd ? define(factory) :
6
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.DOMPurify = factory());
4
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
5
+ typeof define === 'function' && define.amd ? define(factory) :
6
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.DOMPurify = factory());
7
7
  })(this, (function () { 'use strict';
8
8
 
9
- const {
10
- entries,
11
- setPrototypeOf,
12
- isFrozen,
13
- getPrototypeOf,
14
- getOwnPropertyDescriptor
15
- } = Object;
16
- let {
17
- freeze,
18
- seal,
19
- create
20
- } = Object; // eslint-disable-line import/no-mutable-exports
21
- let {
22
- apply,
23
- construct
24
- } = typeof Reflect !== 'undefined' && Reflect;
25
- if (!freeze) {
26
- freeze = function freeze(x) {
27
- return x;
28
- };
29
- }
30
- if (!seal) {
31
- seal = function seal(x) {
32
- return x;
33
- };
34
- }
35
- if (!apply) {
36
- apply = function apply(func, thisArg) {
37
- for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
38
- args[_key - 2] = arguments[_key];
39
- }
40
- return func.apply(thisArg, args);
41
- };
42
- }
43
- if (!construct) {
44
- construct = function construct(Func) {
45
- for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
46
- args[_key2 - 1] = arguments[_key2];
47
- }
48
- return new Func(...args);
49
- };
50
- }
51
- const arrayForEach = unapply(Array.prototype.forEach);
52
- const arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);
53
- const arrayPop = unapply(Array.prototype.pop);
54
- const arrayPush = unapply(Array.prototype.push);
55
- const arraySplice = unapply(Array.prototype.splice);
56
- const stringToLowerCase = unapply(String.prototype.toLowerCase);
57
- const stringToString = unapply(String.prototype.toString);
58
- const stringMatch = unapply(String.prototype.match);
59
- const stringReplace = unapply(String.prototype.replace);
60
- const stringIndexOf = unapply(String.prototype.indexOf);
61
- const stringTrim = unapply(String.prototype.trim);
62
- const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);
63
- const regExpTest = unapply(RegExp.prototype.test);
64
- const typeErrorCreate = unconstruct(TypeError);
65
- /**
66
- * Creates a new function that calls the given function with a specified thisArg and arguments.
67
- *
68
- * @param func - The function to be wrapped and called.
69
- * @returns A new function that calls the given function with a specified thisArg and arguments.
70
- */
71
- function unapply(func) {
72
- return function (thisArg) {
73
- if (thisArg instanceof RegExp) {
74
- thisArg.lastIndex = 0;
75
- }
76
- for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
77
- args[_key3 - 1] = arguments[_key3];
78
- }
79
- return apply(func, thisArg, args);
80
- };
81
- }
82
- /**
83
- * Creates a new function that constructs an instance of the given constructor function with the provided arguments.
84
- *
85
- * @param func - The constructor function to be wrapped and called.
86
- * @returns A new function that constructs an instance of the given constructor function with the provided arguments.
87
- */
88
- function unconstruct(Func) {
89
- return function () {
90
- for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
91
- args[_key4] = arguments[_key4];
92
- }
93
- return construct(Func, args);
94
- };
95
- }
96
- /**
97
- * Add properties to a lookup table
98
- *
99
- * @param set - The set to which elements will be added.
100
- * @param array - The array containing elements to be added to the set.
101
- * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.
102
- * @returns The modified set with added elements.
103
- */
104
- function addToSet(set, array) {
105
- let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;
106
- if (setPrototypeOf) {
107
- // Make 'in' and truthy checks like Boolean(set.constructor)
108
- // independent of any properties defined on Object.prototype.
109
- // Prevent prototype setters from intercepting set as a this value.
110
- setPrototypeOf(set, null);
111
- }
112
- let l = array.length;
113
- while (l--) {
114
- let element = array[l];
115
- if (typeof element === 'string') {
116
- const lcElement = transformCaseFunc(element);
117
- if (lcElement !== element) {
118
- // Config presets (e.g. tags.js, attrs.js) are immutable.
119
- if (!isFrozen(array)) {
120
- array[l] = lcElement;
121
- }
122
- element = lcElement;
123
- }
124
- }
125
- set[element] = true;
9
+ const {
10
+ entries,
11
+ setPrototypeOf,
12
+ isFrozen,
13
+ getPrototypeOf,
14
+ getOwnPropertyDescriptor
15
+ } = Object;
16
+ let {
17
+ freeze,
18
+ seal,
19
+ create
20
+ } = Object; // eslint-disable-line import/no-mutable-exports
21
+ let {
22
+ apply,
23
+ construct
24
+ } = typeof Reflect !== 'undefined' && Reflect;
25
+ if (!freeze) {
26
+ freeze = function freeze(x) {
27
+ return x;
28
+ };
126
29
  }
127
- return set;
128
- }
129
- /**
130
- * Clean up an array to harden against CSPP
131
- *
132
- * @param array - The array to be cleaned.
133
- * @returns The cleaned version of the array
134
- */
135
- function cleanArray(array) {
136
- for (let index = 0; index < array.length; index++) {
137
- const isPropertyExist = objectHasOwnProperty(array, index);
138
- if (!isPropertyExist) {
139
- array[index] = null;
140
- }
30
+ if (!seal) {
31
+ seal = function seal(x) {
32
+ return x;
33
+ };
141
34
  }
142
- return array;
143
- }
144
- /**
145
- * Shallow clone an object
146
- *
147
- * @param object - The object to be cloned.
148
- * @returns A new object that copies the original.
149
- */
150
- function clone(object) {
151
- const newObject = create(null);
152
- for (const [property, value] of entries(object)) {
153
- const isPropertyExist = objectHasOwnProperty(object, property);
154
- if (isPropertyExist) {
155
- if (Array.isArray(value)) {
156
- newObject[property] = cleanArray(value);
157
- } else if (value && typeof value === 'object' && value.constructor === Object) {
158
- newObject[property] = clone(value);
159
- } else {
160
- newObject[property] = value;
35
+ if (!apply) {
36
+ apply = function apply(func, thisArg) {
37
+ for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
38
+ args[_key - 2] = arguments[_key];
161
39
  }
162
- }
40
+ return func.apply(thisArg, args);
41
+ };
163
42
  }
164
- return newObject;
165
- }
166
- /**
167
- * This method automatically checks if the prop is function or getter and behaves accordingly.
168
- *
169
- * @param object - The object to look up the getter function in its prototype chain.
170
- * @param prop - The property name for which to find the getter function.
171
- * @returns The getter function found in the prototype chain or a fallback function.
172
- */
173
- function lookupGetter(object, prop) {
174
- while (object !== null) {
175
- const desc = getOwnPropertyDescriptor(object, prop);
176
- if (desc) {
177
- if (desc.get) {
178
- return unapply(desc.get);
179
- }
180
- if (typeof desc.value === 'function') {
181
- return unapply(desc.value);
43
+ if (!construct) {
44
+ construct = function construct(Func) {
45
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
46
+ args[_key2 - 1] = arguments[_key2];
182
47
  }
183
- }
184
- object = getPrototypeOf(object);
185
- }
186
- function fallbackValue() {
187
- return null;
188
- }
189
- return fallbackValue;
190
- }
191
-
192
- const html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'search', 'section', 'select', 'shadow', 'slot', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']);
193
- const svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'enterkeyhint', 'exportparts', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'inputmode', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'part', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);
194
- const svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']);
195
- // List of SVG elements that are disallowed by default.
196
- // We still need to know them so that we can do namespace
197
- // checks properly in case one wants to add them to
198
- // allow-list.
199
- const svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);
200
- const mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']);
201
- // Similarly to SVG, we want to know all MathML elements,
202
- // even those that we disallow by default.
203
- const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
204
- const text = freeze(['#text']);
205
-
206
- const html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'exportparts', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inert', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'part', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns', 'slot']);
207
- const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'mask-type', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);
208
- const mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);
209
- const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
210
-
211
- // eslint-disable-next-line unicorn/better-regex
212
- const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode
213
- const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
214
- const TMPLIT_EXPR = seal(/\$\{[\w\W]*/gm); // eslint-disable-line unicorn/better-regex
215
- const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape
216
- const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
217
- const IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape
218
- );
219
- const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
220
- const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex
221
- );
222
- const DOCTYPE_NAME = seal(/^html$/i);
223
- const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);
224
-
225
- var EXPRESSIONS = /*#__PURE__*/Object.freeze({
226
- __proto__: null,
227
- ARIA_ATTR: ARIA_ATTR,
228
- ATTR_WHITESPACE: ATTR_WHITESPACE,
229
- CUSTOM_ELEMENT: CUSTOM_ELEMENT,
230
- DATA_ATTR: DATA_ATTR,
231
- DOCTYPE_NAME: DOCTYPE_NAME,
232
- ERB_EXPR: ERB_EXPR,
233
- IS_ALLOWED_URI: IS_ALLOWED_URI,
234
- IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA,
235
- MUSTACHE_EXPR: MUSTACHE_EXPR,
236
- TMPLIT_EXPR: TMPLIT_EXPR
237
- });
238
-
239
- /* eslint-disable @typescript-eslint/indent */
240
- // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
241
- const NODE_TYPE = {
242
- element: 1,
243
- attribute: 2,
244
- text: 3,
245
- cdataSection: 4,
246
- entityReference: 5,
247
- // Deprecated
248
- entityNode: 6,
249
- // Deprecated
250
- progressingInstruction: 7,
251
- comment: 8,
252
- document: 9,
253
- documentType: 10,
254
- documentFragment: 11,
255
- notation: 12 // Deprecated
256
- };
257
- const getGlobal = function getGlobal() {
258
- return typeof window === 'undefined' ? null : window;
259
- };
260
- /**
261
- * Creates a no-op policy for internal use only.
262
- * Don't export this function outside this module!
263
- * @param trustedTypes The policy factory.
264
- * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).
265
- * @return The policy created (or null, if Trusted Types
266
- * are not supported or creating the policy failed).
267
- */
268
- const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {
269
- if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
270
- return null;
271
- }
272
- // Allow the callers to control the unique policy name
273
- // by adding a data-tt-policy-suffix to the script element with the DOMPurify.
274
- // Policy creation with duplicate names throws in Trusted Types.
275
- let suffix = null;
276
- const ATTR_NAME = 'data-tt-policy-suffix';
277
- if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {
278
- suffix = purifyHostElement.getAttribute(ATTR_NAME);
48
+ return new Func(...args);
49
+ };
279
50
  }
280
- const policyName = 'dompurify' + (suffix ? '#' + suffix : '');
281
- try {
282
- return trustedTypes.createPolicy(policyName, {
283
- createHTML(html) {
284
- return html;
285
- },
286
- createScriptURL(scriptUrl) {
287
- return scriptUrl;
288
- }
289
- });
290
- } catch (_) {
291
- // Policy creation failed (most likely another DOMPurify script has
292
- // already run). Skip creating the policy, as this will only cause errors
293
- // if TT are enforced.
294
- console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
295
- return null;
51
+ const arrayForEach = unapply(Array.prototype.forEach);
52
+ const arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);
53
+ const arrayPop = unapply(Array.prototype.pop);
54
+ const arrayPush = unapply(Array.prototype.push);
55
+ const arraySplice = unapply(Array.prototype.splice);
56
+ const arrayIsArray = Array.isArray;
57
+ const stringToLowerCase = unapply(String.prototype.toLowerCase);
58
+ const stringToString = unapply(String.prototype.toString);
59
+ const stringMatch = unapply(String.prototype.match);
60
+ const stringReplace = unapply(String.prototype.replace);
61
+ const stringIndexOf = unapply(String.prototype.indexOf);
62
+ const stringTrim = unapply(String.prototype.trim);
63
+ const numberToString = unapply(Number.prototype.toString);
64
+ const booleanToString = unapply(Boolean.prototype.toString);
65
+ const bigintToString = typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString);
66
+ const symbolToString = typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString);
67
+ const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);
68
+ const objectToString = unapply(Object.prototype.toString);
69
+ const regExpTest = unapply(RegExp.prototype.test);
70
+ const typeErrorCreate = unconstruct(TypeError);
71
+ /**
72
+ * Creates a new function that calls the given function with a specified thisArg and arguments.
73
+ *
74
+ * @param func - The function to be wrapped and called.
75
+ * @returns A new function that calls the given function with a specified thisArg and arguments.
76
+ */
77
+ function unapply(func) {
78
+ return function (thisArg) {
79
+ if (thisArg instanceof RegExp) {
80
+ thisArg.lastIndex = 0;
81
+ }
82
+ for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
83
+ args[_key3 - 1] = arguments[_key3];
84
+ }
85
+ return apply(func, thisArg, args);
86
+ };
296
87
  }
297
- };
298
- const _createHooksMap = function _createHooksMap() {
299
- return {
300
- afterSanitizeAttributes: [],
301
- afterSanitizeElements: [],
302
- afterSanitizeShadowDOM: [],
303
- beforeSanitizeAttributes: [],
304
- beforeSanitizeElements: [],
305
- beforeSanitizeShadowDOM: [],
306
- uponSanitizeAttribute: [],
307
- uponSanitizeElement: [],
308
- uponSanitizeShadowNode: []
309
- };
310
- };
311
- function createDOMPurify() {
312
- let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
313
- const DOMPurify = root => createDOMPurify(root);
314
- DOMPurify.version = '3.3.3';
315
- DOMPurify.removed = [];
316
- if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {
317
- // Not running in a browser, provide a factory function
318
- // so that you can pass your own Window
319
- DOMPurify.isSupported = false;
320
- return DOMPurify;
88
+ /**
89
+ * Creates a new function that constructs an instance of the given constructor function with the provided arguments.
90
+ *
91
+ * @param func - The constructor function to be wrapped and called.
92
+ * @returns A new function that constructs an instance of the given constructor function with the provided arguments.
93
+ */
94
+ function unconstruct(Func) {
95
+ return function () {
96
+ for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
97
+ args[_key4] = arguments[_key4];
98
+ }
99
+ return construct(Func, args);
100
+ };
321
101
  }
322
- let {
323
- document
324
- } = window;
325
- const originalDocument = document;
326
- const currentScript = originalDocument.currentScript;
327
- const {
328
- DocumentFragment,
329
- HTMLTemplateElement,
330
- Node,
331
- Element,
332
- NodeFilter,
333
- NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap,
334
- HTMLFormElement,
335
- DOMParser,
336
- trustedTypes
337
- } = window;
338
- const ElementPrototype = Element.prototype;
339
- const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
340
- const remove = lookupGetter(ElementPrototype, 'remove');
341
- const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
342
- const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
343
- const getParentNode = lookupGetter(ElementPrototype, 'parentNode');
344
- // As per issue #47, the web-components registry is inherited by a
345
- // new document created via createHTMLDocument. As per the spec
346
- // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
347
- // a new empty registry is used when creating a template contents owner
348
- // document, so we use that as our parent document to ensure nothing
349
- // is inherited.
350
- if (typeof HTMLTemplateElement === 'function') {
351
- const template = document.createElement('template');
352
- if (template.content && template.content.ownerDocument) {
353
- document = template.content.ownerDocument;
102
+ /**
103
+ * Add properties to a lookup table
104
+ *
105
+ * @param set - The set to which elements will be added.
106
+ * @param array - The array containing elements to be added to the set.
107
+ * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.
108
+ * @returns The modified set with added elements.
109
+ */
110
+ function addToSet(set, array) {
111
+ let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;
112
+ if (setPrototypeOf) {
113
+ // Make 'in' and truthy checks like Boolean(set.constructor)
114
+ // independent of any properties defined on Object.prototype.
115
+ // Prevent prototype setters from intercepting set as a this value.
116
+ setPrototypeOf(set, null);
117
+ }
118
+ if (!arrayIsArray(array)) {
119
+ return set;
120
+ }
121
+ let l = array.length;
122
+ while (l--) {
123
+ let element = array[l];
124
+ if (typeof element === 'string') {
125
+ const lcElement = transformCaseFunc(element);
126
+ if (lcElement !== element) {
127
+ // Config presets (e.g. tags.js, attrs.js) are immutable.
128
+ if (!isFrozen(array)) {
129
+ array[l] = lcElement;
130
+ }
131
+ element = lcElement;
132
+ }
133
+ }
134
+ set[element] = true;
354
135
  }
136
+ return set;
355
137
  }
356
- let trustedTypesPolicy;
357
- let emptyHTML = '';
358
- const {
359
- implementation,
360
- createNodeIterator,
361
- createDocumentFragment,
362
- getElementsByTagName
363
- } = document;
364
- const {
365
- importNode
366
- } = originalDocument;
367
- let hooks = _createHooksMap();
368
138
  /**
369
- * Expose whether this browser supports running the full DOMPurify.
139
+ * Clean up an array to harden against CSPP
140
+ *
141
+ * @param array - The array to be cleaned.
142
+ * @returns The cleaned version of the array
370
143
  */
371
- DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;
372
- const {
373
- MUSTACHE_EXPR,
374
- ERB_EXPR,
375
- TMPLIT_EXPR,
376
- DATA_ATTR,
377
- ARIA_ATTR,
378
- IS_SCRIPT_OR_DATA,
379
- ATTR_WHITESPACE,
380
- CUSTOM_ELEMENT
381
- } = EXPRESSIONS;
382
- let {
383
- IS_ALLOWED_URI: IS_ALLOWED_URI$1
384
- } = EXPRESSIONS;
144
+ function cleanArray(array) {
145
+ for (let index = 0; index < array.length; index++) {
146
+ const isPropertyExist = objectHasOwnProperty(array, index);
147
+ if (!isPropertyExist) {
148
+ array[index] = null;
149
+ }
150
+ }
151
+ return array;
152
+ }
385
153
  /**
386
- * We consider the elements and attributes below to be safe. Ideally
387
- * don't add any new ones but feel free to remove unwanted ones.
388
- */
389
- /* allowed element names */
390
- let ALLOWED_TAGS = null;
391
- const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);
392
- /* Allowed attribute names */
393
- let ALLOWED_ATTR = null;
394
- const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);
395
- /*
396
- * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.
397
- * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)
398
- * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)
399
- * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.
154
+ * Shallow clone an object
155
+ *
156
+ * @param object - The object to be cloned.
157
+ * @returns A new object that copies the original.
400
158
  */
401
- let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {
402
- tagNameCheck: {
403
- writable: true,
404
- configurable: false,
405
- enumerable: true,
406
- value: null
407
- },
408
- attributeNameCheck: {
409
- writable: true,
410
- configurable: false,
411
- enumerable: true,
412
- value: null
413
- },
414
- allowCustomizedBuiltInElements: {
415
- writable: true,
416
- configurable: false,
417
- enumerable: true,
418
- value: false
419
- }
420
- }));
421
- /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
422
- let FORBID_TAGS = null;
423
- /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
424
- let FORBID_ATTR = null;
425
- /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */
426
- const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, {
427
- tagCheck: {
428
- writable: true,
429
- configurable: false,
430
- enumerable: true,
431
- value: null
432
- },
433
- attributeCheck: {
434
- writable: true,
435
- configurable: false,
436
- enumerable: true,
437
- value: null
159
+ function clone(object) {
160
+ const newObject = create(null);
161
+ for (const [property, value] of entries(object)) {
162
+ const isPropertyExist = objectHasOwnProperty(object, property);
163
+ if (isPropertyExist) {
164
+ if (arrayIsArray(value)) {
165
+ newObject[property] = cleanArray(value);
166
+ } else if (value && typeof value === 'object' && value.constructor === Object) {
167
+ newObject[property] = clone(value);
168
+ } else {
169
+ newObject[property] = value;
170
+ }
171
+ }
438
172
  }
439
- }));
440
- /* Decide if ARIA attributes are okay */
441
- let ALLOW_ARIA_ATTR = true;
442
- /* Decide if custom data attributes are okay */
443
- let ALLOW_DATA_ATTR = true;
444
- /* Decide if unknown protocols are okay */
445
- let ALLOW_UNKNOWN_PROTOCOLS = false;
446
- /* Decide if self-closing tags in attributes are allowed.
447
- * Usually removed due to a mXSS issue in jQuery 3.0 */
448
- let ALLOW_SELF_CLOSE_IN_ATTR = true;
449
- /* Output should be safe for common template engines.
450
- * This means, DOMPurify removes data attributes, mustaches and ERB
451
- */
452
- let SAFE_FOR_TEMPLATES = false;
453
- /* Output should be safe even for XML used within HTML and alike.
454
- * This means, DOMPurify removes comments when containing risky content.
455
- */
456
- let SAFE_FOR_XML = true;
457
- /* Decide if document with <html>... should be returned */
458
- let WHOLE_DOCUMENT = false;
459
- /* Track whether config is already set on this instance of DOMPurify. */
460
- let SET_CONFIG = false;
461
- /* Decide if all elements (e.g. style, script) must be children of
462
- * document.body. By default, browsers might move them to document.head */
463
- let FORCE_BODY = false;
464
- /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
465
- * string (or a TrustedHTML object if Trusted Types are supported).
466
- * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
467
- */
468
- let RETURN_DOM = false;
469
- /* Decide if a DOM `DocumentFragment` should be returned, instead of a html
470
- * string (or a TrustedHTML object if Trusted Types are supported) */
471
- let RETURN_DOM_FRAGMENT = false;
472
- /* Try to return a Trusted Type object instead of a string, return a string in
473
- * case Trusted Types are not supported */
474
- let RETURN_TRUSTED_TYPE = false;
475
- /* Output should be free from DOM clobbering attacks?
476
- * This sanitizes markups named with colliding, clobberable built-in DOM APIs.
477
- */
478
- let SANITIZE_DOM = true;
479
- /* Achieve full DOM Clobbering protection by isolating the namespace of named
480
- * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.
481
- *
482
- * HTML/DOM spec rules that enable DOM Clobbering:
483
- * - Named Access on Window (§7.3.3)
484
- * - DOM Tree Accessors (§3.1.5)
485
- * - Form Element Parent-Child Relations (§4.10.3)
486
- * - Iframe srcdoc / Nested WindowProxies (§4.8.5)
487
- * - HTMLCollection (§4.2.10.2)
173
+ return newObject;
174
+ }
175
+ /**
176
+ * Convert non-node values into strings without depending on direct property access.
488
177
  *
489
- * Namespace isolation is implemented by prefixing `id` and `name` attributes
490
- * with a constant string, i.e., `user-content-`
178
+ * @param value - The value to stringify.
179
+ * @returns A string representation of the provided value.
491
180
  */
492
- let SANITIZE_NAMED_PROPS = false;
493
- const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';
494
- /* Keep element content when removing element? */
495
- let KEEP_CONTENT = true;
496
- /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
497
- * of importing it into a new Document and returning a sanitized copy */
498
- let IN_PLACE = false;
499
- /* Allow usage of profiles like html, svg and mathMl */
500
- let USE_PROFILES = {};
501
- /* Tags to ignore content of when KEEP_CONTENT is true */
502
- let FORBID_CONTENTS = null;
503
- const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
504
- /* Tags that are safe for data: URIs */
505
- let DATA_URI_TAGS = null;
506
- const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
507
- /* Attributes safe for values like "javascript:" */
508
- let URI_SAFE_ATTRIBUTES = null;
509
- const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);
510
- const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
511
- const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
512
- const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
513
- /* Document namespace */
514
- let NAMESPACE = HTML_NAMESPACE;
515
- let IS_EMPTY_INPUT = false;
516
- /* Allowed XHTML+XML namespaces */
517
- let ALLOWED_NAMESPACES = null;
518
- const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
519
- let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
520
- let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);
521
- // Certain elements are allowed in both SVG and HTML
522
- // namespace. We need to specify them explicitly
523
- // so that they don't get erroneously deleted from
524
- // HTML namespace.
525
- const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
526
- /* Parsing of strict XHTML documents */
527
- let PARSER_MEDIA_TYPE = null;
528
- const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
529
- const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
530
- let transformCaseFunc = null;
531
- /* Keep a reference to config to pass to hooks */
532
- let CONFIG = null;
533
- /* Ideally, do not touch anything below this line */
534
- /* ______________________________________________ */
535
- const formElement = document.createElement('form');
536
- const isRegexOrFunction = function isRegexOrFunction(testValue) {
537
- return testValue instanceof RegExp || testValue instanceof Function;
538
- };
181
+ function stringifyValue(value) {
182
+ switch (typeof value) {
183
+ case 'string':
184
+ {
185
+ return value;
186
+ }
187
+ case 'number':
188
+ {
189
+ return numberToString(value);
190
+ }
191
+ case 'boolean':
192
+ {
193
+ return booleanToString(value);
194
+ }
195
+ case 'bigint':
196
+ {
197
+ return bigintToString ? bigintToString(value) : '0';
198
+ }
199
+ case 'symbol':
200
+ {
201
+ return symbolToString ? symbolToString(value) : 'Symbol()';
202
+ }
203
+ case 'undefined':
204
+ {
205
+ return objectToString(value);
206
+ }
207
+ case 'function':
208
+ case 'object':
209
+ {
210
+ if (value === null) {
211
+ return objectToString(value);
212
+ }
213
+ const valueAsRecord = value;
214
+ const valueToString = lookupGetter(valueAsRecord, 'toString');
215
+ if (typeof valueToString === 'function') {
216
+ const stringified = valueToString(valueAsRecord);
217
+ return typeof stringified === 'string' ? stringified : objectToString(stringified);
218
+ }
219
+ return objectToString(value);
220
+ }
221
+ default:
222
+ {
223
+ return objectToString(value);
224
+ }
225
+ }
226
+ }
539
227
  /**
540
- * _parseConfig
228
+ * This method automatically checks if the prop is function or getter and behaves accordingly.
541
229
  *
542
- * @param cfg optional config literal
230
+ * @param object - The object to look up the getter function in its prototype chain.
231
+ * @param prop - The property name for which to find the getter function.
232
+ * @returns The getter function found in the prototype chain or a fallback function.
543
233
  */
544
- // eslint-disable-next-line complexity
545
- const _parseConfig = function _parseConfig() {
546
- let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
547
- if (CONFIG && CONFIG === cfg) {
548
- return;
549
- }
550
- /* Shield configuration object from tampering */
551
- if (!cfg || typeof cfg !== 'object') {
552
- cfg = {};
553
- }
554
- /* Shield configuration object from prototype pollution */
555
- cfg = clone(cfg);
556
- PARSER_MEDIA_TYPE =
557
- // eslint-disable-next-line unicorn/prefer-includes
558
- SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;
559
- // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
560
- transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
561
- /* Set configuration parameters */
562
- ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
563
- ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
564
- ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
565
- URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES;
566
- DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS;
567
- FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
568
- FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({});
569
- FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({});
570
- USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES : false;
571
- ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
572
- ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
573
- ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
574
- ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true
575
- SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
576
- SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true
577
- WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
578
- RETURN_DOM = cfg.RETURN_DOM || false; // Default false
579
- RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
580
- RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false
581
- FORCE_BODY = cfg.FORCE_BODY || false; // Default false
582
- SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
583
- SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
584
- KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
585
- IN_PLACE = cfg.IN_PLACE || false; // Default false
586
- IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI;
587
- NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
588
- MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS;
589
- HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS;
590
- CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};
591
- if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
592
- CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
593
- }
594
- if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
595
- CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
234
+ function lookupGetter(object, prop) {
235
+ while (object !== null) {
236
+ const desc = getOwnPropertyDescriptor(object, prop);
237
+ if (desc) {
238
+ if (desc.get) {
239
+ return unapply(desc.get);
240
+ }
241
+ if (typeof desc.value === 'function') {
242
+ return unapply(desc.value);
243
+ }
244
+ }
245
+ object = getPrototypeOf(object);
596
246
  }
597
- if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {
598
- CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
247
+ function fallbackValue() {
248
+ return null;
599
249
  }
600
- if (SAFE_FOR_TEMPLATES) {
601
- ALLOW_DATA_ATTR = false;
250
+ return fallbackValue;
251
+ }
252
+ function isRegex(value) {
253
+ try {
254
+ regExpTest(value, '');
255
+ return true;
256
+ } catch (_unused) {
257
+ return false;
602
258
  }
603
- if (RETURN_DOM_FRAGMENT) {
604
- RETURN_DOM = true;
259
+ }
260
+
261
+ const html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'search', 'section', 'select', 'shadow', 'slot', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']);
262
+ const svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'enterkeyhint', 'exportparts', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'inputmode', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'part', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);
263
+ const svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']);
264
+ // List of SVG elements that are disallowed by default.
265
+ // We still need to know them so that we can do namespace
266
+ // checks properly in case one wants to add them to
267
+ // allow-list.
268
+ const svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);
269
+ const mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']);
270
+ // Similarly to SVG, we want to know all MathML elements,
271
+ // even those that we disallow by default.
272
+ const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
273
+ const text = freeze(['#text']);
274
+
275
+ const html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'exportparts', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inert', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'part', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns']);
276
+ const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'mask-type', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);
277
+ const mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnalign', 'columnlines', 'columnspacing', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lquote', 'lspace', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);
278
+ const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
279
+
280
+ // eslint-disable-next-line unicorn/better-regex
281
+ const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode
282
+ const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
283
+ const TMPLIT_EXPR = seal(/\$\{[\w\W]*/gm); // eslint-disable-line unicorn/better-regex
284
+ const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape
285
+ const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
286
+ const IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape
287
+ );
288
+ const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
289
+ const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex
290
+ );
291
+ const DOCTYPE_NAME = seal(/^html$/i);
292
+ const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);
293
+
294
+ var EXPRESSIONS = /*#__PURE__*/Object.freeze({
295
+ __proto__: null,
296
+ ARIA_ATTR: ARIA_ATTR,
297
+ ATTR_WHITESPACE: ATTR_WHITESPACE,
298
+ CUSTOM_ELEMENT: CUSTOM_ELEMENT,
299
+ DATA_ATTR: DATA_ATTR,
300
+ DOCTYPE_NAME: DOCTYPE_NAME,
301
+ ERB_EXPR: ERB_EXPR,
302
+ IS_ALLOWED_URI: IS_ALLOWED_URI,
303
+ IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA,
304
+ MUSTACHE_EXPR: MUSTACHE_EXPR,
305
+ TMPLIT_EXPR: TMPLIT_EXPR
306
+ });
307
+
308
+ /* eslint-disable @typescript-eslint/indent */
309
+ // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
310
+ const NODE_TYPE = {
311
+ element: 1,
312
+ text: 3,
313
+ // Deprecated
314
+ progressingInstruction: 7,
315
+ comment: 8,
316
+ document: 9};
317
+ const getGlobal = function getGlobal() {
318
+ return typeof window === 'undefined' ? null : window;
319
+ };
320
+ /**
321
+ * Creates a no-op policy for internal use only.
322
+ * Don't export this function outside this module!
323
+ * @param trustedTypes The policy factory.
324
+ * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).
325
+ * @return The policy created (or null, if Trusted Types
326
+ * are not supported or creating the policy failed).
327
+ */
328
+ const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {
329
+ if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
330
+ return null;
331
+ }
332
+ // Allow the callers to control the unique policy name
333
+ // by adding a data-tt-policy-suffix to the script element with the DOMPurify.
334
+ // Policy creation with duplicate names throws in Trusted Types.
335
+ let suffix = null;
336
+ const ATTR_NAME = 'data-tt-policy-suffix';
337
+ if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {
338
+ suffix = purifyHostElement.getAttribute(ATTR_NAME);
339
+ }
340
+ const policyName = 'dompurify' + (suffix ? '#' + suffix : '');
341
+ try {
342
+ return trustedTypes.createPolicy(policyName, {
343
+ createHTML(html) {
344
+ return html;
345
+ },
346
+ createScriptURL(scriptUrl) {
347
+ return scriptUrl;
348
+ }
349
+ });
350
+ } catch (_) {
351
+ // Policy creation failed (most likely another DOMPurify script has
352
+ // already run). Skip creating the policy, as this will only cause errors
353
+ // if TT are enforced.
354
+ console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
355
+ return null;
605
356
  }
606
- /* Parse profile info */
607
- if (USE_PROFILES) {
608
- ALLOWED_TAGS = addToSet({}, text);
609
- ALLOWED_ATTR = create(null);
610
- if (USE_PROFILES.html === true) {
611
- addToSet(ALLOWED_TAGS, html$1);
612
- addToSet(ALLOWED_ATTR, html);
613
- }
614
- if (USE_PROFILES.svg === true) {
615
- addToSet(ALLOWED_TAGS, svg$1);
616
- addToSet(ALLOWED_ATTR, svg);
617
- addToSet(ALLOWED_ATTR, xml);
618
- }
619
- if (USE_PROFILES.svgFilters === true) {
620
- addToSet(ALLOWED_TAGS, svgFilters);
621
- addToSet(ALLOWED_ATTR, svg);
622
- addToSet(ALLOWED_ATTR, xml);
623
- }
624
- if (USE_PROFILES.mathMl === true) {
625
- addToSet(ALLOWED_TAGS, mathMl$1);
626
- addToSet(ALLOWED_ATTR, mathMl);
627
- addToSet(ALLOWED_ATTR, xml);
357
+ };
358
+ const _createHooksMap = function _createHooksMap() {
359
+ return {
360
+ afterSanitizeAttributes: [],
361
+ afterSanitizeElements: [],
362
+ afterSanitizeShadowDOM: [],
363
+ beforeSanitizeAttributes: [],
364
+ beforeSanitizeElements: [],
365
+ beforeSanitizeShadowDOM: [],
366
+ uponSanitizeAttribute: [],
367
+ uponSanitizeElement: [],
368
+ uponSanitizeShadowNode: []
369
+ };
370
+ };
371
+ function createDOMPurify() {
372
+ let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
373
+ const DOMPurify = root => createDOMPurify(root);
374
+ DOMPurify.version = '3.4.1';
375
+ DOMPurify.removed = [];
376
+ if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {
377
+ // Not running in a browser, provide a factory function
378
+ // so that you can pass your own Window
379
+ DOMPurify.isSupported = false;
380
+ return DOMPurify;
381
+ }
382
+ let {
383
+ document
384
+ } = window;
385
+ const originalDocument = document;
386
+ const currentScript = originalDocument.currentScript;
387
+ const {
388
+ DocumentFragment,
389
+ HTMLTemplateElement,
390
+ Node,
391
+ Element,
392
+ NodeFilter,
393
+ NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap,
394
+ HTMLFormElement,
395
+ DOMParser,
396
+ trustedTypes
397
+ } = window;
398
+ const ElementPrototype = Element.prototype;
399
+ const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
400
+ const remove = lookupGetter(ElementPrototype, 'remove');
401
+ const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
402
+ const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
403
+ const getParentNode = lookupGetter(ElementPrototype, 'parentNode');
404
+ // As per issue #47, the web-components registry is inherited by a
405
+ // new document created via createHTMLDocument. As per the spec
406
+ // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
407
+ // a new empty registry is used when creating a template contents owner
408
+ // document, so we use that as our parent document to ensure nothing
409
+ // is inherited.
410
+ if (typeof HTMLTemplateElement === 'function') {
411
+ const template = document.createElement('template');
412
+ if (template.content && template.content.ownerDocument) {
413
+ document = template.content.ownerDocument;
628
414
  }
629
415
  }
630
- /* Prevent function-based ADD_ATTR / ADD_TAGS from leaking across calls */
631
- if (!objectHasOwnProperty(cfg, 'ADD_TAGS')) {
416
+ let trustedTypesPolicy;
417
+ let emptyHTML = '';
418
+ const {
419
+ implementation,
420
+ createNodeIterator,
421
+ createDocumentFragment,
422
+ getElementsByTagName
423
+ } = document;
424
+ const {
425
+ importNode
426
+ } = originalDocument;
427
+ let hooks = _createHooksMap();
428
+ /**
429
+ * Expose whether this browser supports running the full DOMPurify.
430
+ */
431
+ DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;
432
+ const {
433
+ MUSTACHE_EXPR,
434
+ ERB_EXPR,
435
+ TMPLIT_EXPR,
436
+ DATA_ATTR,
437
+ ARIA_ATTR,
438
+ IS_SCRIPT_OR_DATA,
439
+ ATTR_WHITESPACE,
440
+ CUSTOM_ELEMENT
441
+ } = EXPRESSIONS;
442
+ let {
443
+ IS_ALLOWED_URI: IS_ALLOWED_URI$1
444
+ } = EXPRESSIONS;
445
+ /**
446
+ * We consider the elements and attributes below to be safe. Ideally
447
+ * don't add any new ones but feel free to remove unwanted ones.
448
+ */
449
+ /* allowed element names */
450
+ let ALLOWED_TAGS = null;
451
+ const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);
452
+ /* Allowed attribute names */
453
+ let ALLOWED_ATTR = null;
454
+ const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);
455
+ /*
456
+ * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.
457
+ * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)
458
+ * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)
459
+ * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.
460
+ */
461
+ let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {
462
+ tagNameCheck: {
463
+ writable: true,
464
+ configurable: false,
465
+ enumerable: true,
466
+ value: null
467
+ },
468
+ attributeNameCheck: {
469
+ writable: true,
470
+ configurable: false,
471
+ enumerable: true,
472
+ value: null
473
+ },
474
+ allowCustomizedBuiltInElements: {
475
+ writable: true,
476
+ configurable: false,
477
+ enumerable: true,
478
+ value: false
479
+ }
480
+ }));
481
+ /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
482
+ let FORBID_TAGS = null;
483
+ /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
484
+ let FORBID_ATTR = null;
485
+ /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */
486
+ const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, {
487
+ tagCheck: {
488
+ writable: true,
489
+ configurable: false,
490
+ enumerable: true,
491
+ value: null
492
+ },
493
+ attributeCheck: {
494
+ writable: true,
495
+ configurable: false,
496
+ enumerable: true,
497
+ value: null
498
+ }
499
+ }));
500
+ /* Decide if ARIA attributes are okay */
501
+ let ALLOW_ARIA_ATTR = true;
502
+ /* Decide if custom data attributes are okay */
503
+ let ALLOW_DATA_ATTR = true;
504
+ /* Decide if unknown protocols are okay */
505
+ let ALLOW_UNKNOWN_PROTOCOLS = false;
506
+ /* Decide if self-closing tags in attributes are allowed.
507
+ * Usually removed due to a mXSS issue in jQuery 3.0 */
508
+ let ALLOW_SELF_CLOSE_IN_ATTR = true;
509
+ /* Output should be safe for common template engines.
510
+ * This means, DOMPurify removes data attributes, mustaches and ERB
511
+ */
512
+ let SAFE_FOR_TEMPLATES = false;
513
+ /* Output should be safe even for XML used within HTML and alike.
514
+ * This means, DOMPurify removes comments when containing risky content.
515
+ */
516
+ let SAFE_FOR_XML = true;
517
+ /* Decide if document with <html>... should be returned */
518
+ let WHOLE_DOCUMENT = false;
519
+ /* Track whether config is already set on this instance of DOMPurify. */
520
+ let SET_CONFIG = false;
521
+ /* Decide if all elements (e.g. style, script) must be children of
522
+ * document.body. By default, browsers might move them to document.head */
523
+ let FORCE_BODY = false;
524
+ /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
525
+ * string (or a TrustedHTML object if Trusted Types are supported).
526
+ * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
527
+ */
528
+ let RETURN_DOM = false;
529
+ /* Decide if a DOM `DocumentFragment` should be returned, instead of a html
530
+ * string (or a TrustedHTML object if Trusted Types are supported) */
531
+ let RETURN_DOM_FRAGMENT = false;
532
+ /* Try to return a Trusted Type object instead of a string, return a string in
533
+ * case Trusted Types are not supported */
534
+ let RETURN_TRUSTED_TYPE = false;
535
+ /* Output should be free from DOM clobbering attacks?
536
+ * This sanitizes markups named with colliding, clobberable built-in DOM APIs.
537
+ */
538
+ let SANITIZE_DOM = true;
539
+ /* Achieve full DOM Clobbering protection by isolating the namespace of named
540
+ * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.
541
+ *
542
+ * HTML/DOM spec rules that enable DOM Clobbering:
543
+ * - Named Access on Window (§7.3.3)
544
+ * - DOM Tree Accessors (§3.1.5)
545
+ * - Form Element Parent-Child Relations (§4.10.3)
546
+ * - Iframe srcdoc / Nested WindowProxies (§4.8.5)
547
+ * - HTMLCollection (§4.2.10.2)
548
+ *
549
+ * Namespace isolation is implemented by prefixing `id` and `name` attributes
550
+ * with a constant string, i.e., `user-content-`
551
+ */
552
+ let SANITIZE_NAMED_PROPS = false;
553
+ const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';
554
+ /* Keep element content when removing element? */
555
+ let KEEP_CONTENT = true;
556
+ /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
557
+ * of importing it into a new Document and returning a sanitized copy */
558
+ let IN_PLACE = false;
559
+ /* Allow usage of profiles like html, svg and mathMl */
560
+ let USE_PROFILES = {};
561
+ /* Tags to ignore content of when KEEP_CONTENT is true */
562
+ let FORBID_CONTENTS = null;
563
+ const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
564
+ /* Tags that are safe for data: URIs */
565
+ let DATA_URI_TAGS = null;
566
+ const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
567
+ /* Attributes safe for values like "javascript:" */
568
+ let URI_SAFE_ATTRIBUTES = null;
569
+ const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);
570
+ const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
571
+ const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
572
+ const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
573
+ /* Document namespace */
574
+ let NAMESPACE = HTML_NAMESPACE;
575
+ let IS_EMPTY_INPUT = false;
576
+ /* Allowed XHTML+XML namespaces */
577
+ let ALLOWED_NAMESPACES = null;
578
+ const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
579
+ let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
580
+ let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);
581
+ // Certain elements are allowed in both SVG and HTML
582
+ // namespace. We need to specify them explicitly
583
+ // so that they don't get erroneously deleted from
584
+ // HTML namespace.
585
+ const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
586
+ /* Parsing of strict XHTML documents */
587
+ let PARSER_MEDIA_TYPE = null;
588
+ const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
589
+ const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
590
+ let transformCaseFunc = null;
591
+ /* Keep a reference to config to pass to hooks */
592
+ let CONFIG = null;
593
+ /* Ideally, do not touch anything below this line */
594
+ /* ______________________________________________ */
595
+ const formElement = document.createElement('form');
596
+ const isRegexOrFunction = function isRegexOrFunction(testValue) {
597
+ return testValue instanceof RegExp || testValue instanceof Function;
598
+ };
599
+ /**
600
+ * _parseConfig
601
+ *
602
+ * @param cfg optional config literal
603
+ */
604
+ // eslint-disable-next-line complexity
605
+ const _parseConfig = function _parseConfig() {
606
+ let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
607
+ if (CONFIG && CONFIG === cfg) {
608
+ return;
609
+ }
610
+ /* Shield configuration object from tampering */
611
+ if (!cfg || typeof cfg !== 'object') {
612
+ cfg = {};
613
+ }
614
+ /* Shield configuration object from prototype pollution */
615
+ cfg = clone(cfg);
616
+ PARSER_MEDIA_TYPE =
617
+ // eslint-disable-next-line unicorn/prefer-includes
618
+ SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;
619
+ // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
620
+ transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
621
+ /* Set configuration parameters */
622
+ ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') && arrayIsArray(cfg.ALLOWED_TAGS) ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
623
+ ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') && arrayIsArray(cfg.ALLOWED_ATTR) ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
624
+ ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') && arrayIsArray(cfg.ALLOWED_NAMESPACES) ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
625
+ URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR) ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES;
626
+ DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') && arrayIsArray(cfg.ADD_DATA_URI_TAGS) ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS;
627
+ FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS) ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
628
+ FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') && arrayIsArray(cfg.FORBID_TAGS) ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({});
629
+ FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') && arrayIsArray(cfg.FORBID_ATTR) ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({});
630
+ USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;
631
+ ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
632
+ ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
633
+ ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
634
+ ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true
635
+ SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
636
+ SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true
637
+ WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
638
+ RETURN_DOM = cfg.RETURN_DOM || false; // Default false
639
+ RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
640
+ RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false
641
+ FORCE_BODY = cfg.FORCE_BODY || false; // Default false
642
+ SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
643
+ SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
644
+ KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
645
+ IN_PLACE = cfg.IN_PLACE || false; // Default false
646
+ IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp
647
+ NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace
648
+ MATHML_TEXT_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'MATHML_TEXT_INTEGRATION_POINTS') && cfg.MATHML_TEXT_INTEGRATION_POINTS && typeof cfg.MATHML_TEXT_INTEGRATION_POINTS === 'object' ? clone(cfg.MATHML_TEXT_INTEGRATION_POINTS) : addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']); // Default built-in map
649
+ HTML_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'HTML_INTEGRATION_POINTS') && cfg.HTML_INTEGRATION_POINTS && typeof cfg.HTML_INTEGRATION_POINTS === 'object' ? clone(cfg.HTML_INTEGRATION_POINTS) : addToSet({}, ['annotation-xml']); // Default built-in map
650
+ const customElementHandling = objectHasOwnProperty(cfg, 'CUSTOM_ELEMENT_HANDLING') && cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING === 'object' ? clone(cfg.CUSTOM_ELEMENT_HANDLING) : create(null);
651
+ CUSTOM_ELEMENT_HANDLING = create(null);
652
+ if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) {
653
+ CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined
654
+ }
655
+ if (objectHasOwnProperty(customElementHandling, 'attributeNameCheck') && isRegexOrFunction(customElementHandling.attributeNameCheck)) {
656
+ CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck; // Default undefined
657
+ }
658
+ if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') {
659
+ CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined
660
+ }
661
+ if (SAFE_FOR_TEMPLATES) {
662
+ ALLOW_DATA_ATTR = false;
663
+ }
664
+ if (RETURN_DOM_FRAGMENT) {
665
+ RETURN_DOM = true;
666
+ }
667
+ /* Parse profile info */
668
+ if (USE_PROFILES) {
669
+ ALLOWED_TAGS = addToSet({}, text);
670
+ ALLOWED_ATTR = create(null);
671
+ if (USE_PROFILES.html === true) {
672
+ addToSet(ALLOWED_TAGS, html$1);
673
+ addToSet(ALLOWED_ATTR, html);
674
+ }
675
+ if (USE_PROFILES.svg === true) {
676
+ addToSet(ALLOWED_TAGS, svg$1);
677
+ addToSet(ALLOWED_ATTR, svg);
678
+ addToSet(ALLOWED_ATTR, xml);
679
+ }
680
+ if (USE_PROFILES.svgFilters === true) {
681
+ addToSet(ALLOWED_TAGS, svgFilters);
682
+ addToSet(ALLOWED_ATTR, svg);
683
+ addToSet(ALLOWED_ATTR, xml);
684
+ }
685
+ if (USE_PROFILES.mathMl === true) {
686
+ addToSet(ALLOWED_TAGS, mathMl$1);
687
+ addToSet(ALLOWED_ATTR, mathMl);
688
+ addToSet(ALLOWED_ATTR, xml);
689
+ }
690
+ }
691
+ /* Always reset function-based ADD_TAGS / ADD_ATTR checks to prevent
692
+ * leaking across calls when switching from function to array config */
632
693
  EXTRA_ELEMENT_HANDLING.tagCheck = null;
633
- }
634
- if (!objectHasOwnProperty(cfg, 'ADD_ATTR')) {
635
694
  EXTRA_ELEMENT_HANDLING.attributeCheck = null;
636
- }
637
- /* Merge configuration parameters */
638
- if (cfg.ADD_TAGS) {
639
- if (typeof cfg.ADD_TAGS === 'function') {
640
- EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;
641
- } else {
642
- if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
643
- ALLOWED_TAGS = clone(ALLOWED_TAGS);
695
+ /* Merge configuration parameters */
696
+ if (objectHasOwnProperty(cfg, 'ADD_TAGS')) {
697
+ if (typeof cfg.ADD_TAGS === 'function') {
698
+ EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;
699
+ } else if (arrayIsArray(cfg.ADD_TAGS)) {
700
+ if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
701
+ ALLOWED_TAGS = clone(ALLOWED_TAGS);
702
+ }
703
+ addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
644
704
  }
645
- addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
646
705
  }
647
- }
648
- if (cfg.ADD_ATTR) {
649
- if (typeof cfg.ADD_ATTR === 'function') {
650
- EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;
651
- } else {
652
- if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
653
- ALLOWED_ATTR = clone(ALLOWED_ATTR);
706
+ if (objectHasOwnProperty(cfg, 'ADD_ATTR')) {
707
+ if (typeof cfg.ADD_ATTR === 'function') {
708
+ EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;
709
+ } else if (arrayIsArray(cfg.ADD_ATTR)) {
710
+ if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
711
+ ALLOWED_ATTR = clone(ALLOWED_ATTR);
712
+ }
713
+ addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
654
714
  }
655
- addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
656
715
  }
657
- }
658
- if (cfg.ADD_URI_SAFE_ATTR) {
659
- addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
660
- }
661
- if (cfg.FORBID_CONTENTS) {
662
- if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
663
- FORBID_CONTENTS = clone(FORBID_CONTENTS);
716
+ if (objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR)) {
717
+ addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
664
718
  }
665
- addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
666
- }
667
- if (cfg.ADD_FORBID_CONTENTS) {
668
- if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
669
- FORBID_CONTENTS = clone(FORBID_CONTENTS);
719
+ if (objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS)) {
720
+ if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
721
+ FORBID_CONTENTS = clone(FORBID_CONTENTS);
722
+ }
723
+ addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
670
724
  }
671
- addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);
672
- }
673
- /* Add #text in case KEEP_CONTENT is set to true */
674
- if (KEEP_CONTENT) {
675
- ALLOWED_TAGS['#text'] = true;
676
- }
677
- /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
678
- if (WHOLE_DOCUMENT) {
679
- addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
680
- }
681
- /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */
682
- if (ALLOWED_TAGS.table) {
683
- addToSet(ALLOWED_TAGS, ['tbody']);
684
- delete FORBID_TAGS.tbody;
685
- }
686
- if (cfg.TRUSTED_TYPES_POLICY) {
687
- if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
688
- throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
689
- }
690
- if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
691
- throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
692
- }
693
- // Overwrite existing TrustedTypes policy.
694
- trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
695
- // Sign local variables required by `sanitize`.
696
- emptyHTML = trustedTypesPolicy.createHTML('');
697
- } else {
698
- // Uninitialized policy, attempt to initialize the internal dompurify policy.
699
- if (trustedTypesPolicy === undefined) {
700
- trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
701
- }
702
- // If creating the internal policy succeeded sign internal variables.
703
- if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {
725
+ if (objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) {
726
+ if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
727
+ FORBID_CONTENTS = clone(FORBID_CONTENTS);
728
+ }
729
+ addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);
730
+ }
731
+ /* Add #text in case KEEP_CONTENT is set to true */
732
+ if (KEEP_CONTENT) {
733
+ ALLOWED_TAGS['#text'] = true;
734
+ }
735
+ /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
736
+ if (WHOLE_DOCUMENT) {
737
+ addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
738
+ }
739
+ /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */
740
+ if (ALLOWED_TAGS.table) {
741
+ addToSet(ALLOWED_TAGS, ['tbody']);
742
+ delete FORBID_TAGS.tbody;
743
+ }
744
+ if (cfg.TRUSTED_TYPES_POLICY) {
745
+ if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
746
+ throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
747
+ }
748
+ if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
749
+ throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
750
+ }
751
+ // Overwrite existing TrustedTypes policy.
752
+ trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
753
+ // Sign local variables required by `sanitize`.
704
754
  emptyHTML = trustedTypesPolicy.createHTML('');
755
+ } else {
756
+ // Uninitialized policy, attempt to initialize the internal dompurify policy.
757
+ if (trustedTypesPolicy === undefined) {
758
+ trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
759
+ }
760
+ // If creating the internal policy succeeded sign internal variables.
761
+ if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {
762
+ emptyHTML = trustedTypesPolicy.createHTML('');
763
+ }
705
764
  }
706
- }
707
- // Prevent further manipulation of configuration.
708
- // Not available in IE8, Safari 5, etc.
709
- if (freeze) {
710
- freeze(cfg);
711
- }
712
- CONFIG = cfg;
713
- };
714
- /* Keep track of all possible SVG and MathML tags
715
- * so that we can perform the namespace checks
716
- * correctly. */
717
- const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
718
- const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
719
- /**
720
- * @param element a DOM element whose namespace is being checked
721
- * @returns Return false if the element has a
722
- * namespace that a spec-compliant parser would never
723
- * return. Return true otherwise.
724
- */
725
- const _checkValidNamespace = function _checkValidNamespace(element) {
726
- let parent = getParentNode(element);
727
- // In JSDOM, if we're inside shadow DOM, then parentNode
728
- // can be null. We just simulate parent in this case.
729
- if (!parent || !parent.tagName) {
730
- parent = {
731
- namespaceURI: NAMESPACE,
732
- tagName: 'template'
733
- };
734
- }
735
- const tagName = stringToLowerCase(element.tagName);
736
- const parentTagName = stringToLowerCase(parent.tagName);
737
- if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
738
- return false;
739
- }
740
- if (element.namespaceURI === SVG_NAMESPACE) {
741
- // The only way to switch from HTML namespace to SVG
742
- // is via <svg>. If it happens via any other tag, then
743
- // it should be killed.
744
- if (parent.namespaceURI === HTML_NAMESPACE) {
745
- return tagName === 'svg';
746
- }
747
- // The only way to switch from MathML to SVG is via`
748
- // svg if parent is either <annotation-xml> or MathML
749
- // text integration points.
750
- if (parent.namespaceURI === MATHML_NAMESPACE) {
751
- return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
752
- }
753
- // We only allow elements that are defined in SVG
754
- // spec. All others are disallowed in SVG namespace.
755
- return Boolean(ALL_SVG_TAGS[tagName]);
756
- }
757
- if (element.namespaceURI === MATHML_NAMESPACE) {
758
- // The only way to switch from HTML namespace to MathML
759
- // is via <math>. If it happens via any other tag, then
760
- // it should be killed.
761
- if (parent.namespaceURI === HTML_NAMESPACE) {
762
- return tagName === 'math';
763
- }
764
- // The only way to switch from SVG to MathML is via
765
- // <math> and HTML integration points
766
- if (parent.namespaceURI === SVG_NAMESPACE) {
767
- return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
768
- }
769
- // We only allow elements that are defined in MathML
770
- // spec. All others are disallowed in MathML namespace.
771
- return Boolean(ALL_MATHML_TAGS[tagName]);
772
- }
773
- if (element.namespaceURI === HTML_NAMESPACE) {
774
- // The only way to switch from SVG to HTML is via
775
- // HTML integration points, and from MathML to HTML
776
- // is via MathML text integration points
777
- if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
778
- return false;
765
+ // Prevent further manipulation of configuration.
766
+ // Not available in IE8, Safari 5, etc.
767
+ if (freeze) {
768
+ freeze(cfg);
779
769
  }
780
- if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
770
+ CONFIG = cfg;
771
+ };
772
+ /* Keep track of all possible SVG and MathML tags
773
+ * so that we can perform the namespace checks
774
+ * correctly. */
775
+ const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
776
+ const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
777
+ /**
778
+ * @param element a DOM element whose namespace is being checked
779
+ * @returns Return false if the element has a
780
+ * namespace that a spec-compliant parser would never
781
+ * return. Return true otherwise.
782
+ */
783
+ const _checkValidNamespace = function _checkValidNamespace(element) {
784
+ let parent = getParentNode(element);
785
+ // In JSDOM, if we're inside shadow DOM, then parentNode
786
+ // can be null. We just simulate parent in this case.
787
+ if (!parent || !parent.tagName) {
788
+ parent = {
789
+ namespaceURI: NAMESPACE,
790
+ tagName: 'template'
791
+ };
792
+ }
793
+ const tagName = stringToLowerCase(element.tagName);
794
+ const parentTagName = stringToLowerCase(parent.tagName);
795
+ if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
781
796
  return false;
782
797
  }
783
- // We disallow tags that are specific for MathML
784
- // or SVG and should never appear in HTML namespace
785
- return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
786
- }
787
- // For XHTML and XML documents that support custom namespaces
788
- if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
789
- return true;
790
- }
791
- // The code should never reach this place (this means
792
- // that the element somehow got namespace that is not
793
- // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).
794
- // Return false just in case.
795
- return false;
796
- };
797
- /**
798
- * _forceRemove
799
- *
800
- * @param node a DOM node
801
- */
802
- const _forceRemove = function _forceRemove(node) {
803
- arrayPush(DOMPurify.removed, {
804
- element: node
805
- });
806
- try {
807
- // eslint-disable-next-line unicorn/prefer-dom-node-remove
808
- getParentNode(node).removeChild(node);
809
- } catch (_) {
810
- remove(node);
811
- }
812
- };
813
- /**
814
- * _removeAttribute
815
- *
816
- * @param name an Attribute name
817
- * @param element a DOM node
818
- */
819
- const _removeAttribute = function _removeAttribute(name, element) {
820
- try {
821
- arrayPush(DOMPurify.removed, {
822
- attribute: element.getAttributeNode(name),
823
- from: element
824
- });
825
- } catch (_) {
798
+ if (element.namespaceURI === SVG_NAMESPACE) {
799
+ // The only way to switch from HTML namespace to SVG
800
+ // is via <svg>. If it happens via any other tag, then
801
+ // it should be killed.
802
+ if (parent.namespaceURI === HTML_NAMESPACE) {
803
+ return tagName === 'svg';
804
+ }
805
+ // The only way to switch from MathML to SVG is via`
806
+ // svg if parent is either <annotation-xml> or MathML
807
+ // text integration points.
808
+ if (parent.namespaceURI === MATHML_NAMESPACE) {
809
+ return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
810
+ }
811
+ // We only allow elements that are defined in SVG
812
+ // spec. All others are disallowed in SVG namespace.
813
+ return Boolean(ALL_SVG_TAGS[tagName]);
814
+ }
815
+ if (element.namespaceURI === MATHML_NAMESPACE) {
816
+ // The only way to switch from HTML namespace to MathML
817
+ // is via <math>. If it happens via any other tag, then
818
+ // it should be killed.
819
+ if (parent.namespaceURI === HTML_NAMESPACE) {
820
+ return tagName === 'math';
821
+ }
822
+ // The only way to switch from SVG to MathML is via
823
+ // <math> and HTML integration points
824
+ if (parent.namespaceURI === SVG_NAMESPACE) {
825
+ return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
826
+ }
827
+ // We only allow elements that are defined in MathML
828
+ // spec. All others are disallowed in MathML namespace.
829
+ return Boolean(ALL_MATHML_TAGS[tagName]);
830
+ }
831
+ if (element.namespaceURI === HTML_NAMESPACE) {
832
+ // The only way to switch from SVG to HTML is via
833
+ // HTML integration points, and from MathML to HTML
834
+ // is via MathML text integration points
835
+ if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
836
+ return false;
837
+ }
838
+ if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
839
+ return false;
840
+ }
841
+ // We disallow tags that are specific for MathML
842
+ // or SVG and should never appear in HTML namespace
843
+ return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
844
+ }
845
+ // For XHTML and XML documents that support custom namespaces
846
+ if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
847
+ return true;
848
+ }
849
+ // The code should never reach this place (this means
850
+ // that the element somehow got namespace that is not
851
+ // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).
852
+ // Return false just in case.
853
+ return false;
854
+ };
855
+ /**
856
+ * _forceRemove
857
+ *
858
+ * @param node a DOM node
859
+ */
860
+ const _forceRemove = function _forceRemove(node) {
826
861
  arrayPush(DOMPurify.removed, {
827
- attribute: null,
828
- from: element
862
+ element: node
829
863
  });
830
- }
831
- element.removeAttribute(name);
832
- // We void attribute values for unremovable "is" attributes
833
- if (name === 'is') {
834
- if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
835
- try {
836
- _forceRemove(element);
837
- } catch (_) {}
838
- } else {
839
- try {
840
- element.setAttribute(name, '');
841
- } catch (_) {}
864
+ try {
865
+ // eslint-disable-next-line unicorn/prefer-dom-node-remove
866
+ getParentNode(node).removeChild(node);
867
+ } catch (_) {
868
+ remove(node);
842
869
  }
843
- }
844
- };
845
- /**
846
- * _initDocument
847
- *
848
- * @param dirty - a string of dirty markup
849
- * @return a DOM, filled with the dirty markup
850
- */
851
- const _initDocument = function _initDocument(dirty) {
852
- /* Create a HTML document */
853
- let doc = null;
854
- let leadingWhitespace = null;
855
- if (FORCE_BODY) {
856
- dirty = '<remove></remove>' + dirty;
857
- } else {
858
- /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
859
- const matches = stringMatch(dirty, /^[\r\n\t ]+/);
860
- leadingWhitespace = matches && matches[0];
861
- }
862
- if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {
863
- // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
864
- dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
865
- }
866
- const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
867
- /*
868
- * Use the DOMParser API by default, fallback later if needs be
869
- * DOMParser not work for svg when has multiple root element.
870
+ };
871
+ /**
872
+ * _removeAttribute
873
+ *
874
+ * @param name an Attribute name
875
+ * @param element a DOM node
870
876
  */
871
- if (NAMESPACE === HTML_NAMESPACE) {
877
+ const _removeAttribute = function _removeAttribute(name, element) {
872
878
  try {
873
- doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
874
- } catch (_) {}
875
- }
876
- /* Use createHTMLDocument in case DOMParser is not available */
877
- if (!doc || !doc.documentElement) {
878
- doc = implementation.createDocument(NAMESPACE, 'template', null);
879
- try {
880
- doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;
879
+ arrayPush(DOMPurify.removed, {
880
+ attribute: element.getAttributeNode(name),
881
+ from: element
882
+ });
881
883
  } catch (_) {
882
- // Syntax error if dirtyPayload is invalid xml
884
+ arrayPush(DOMPurify.removed, {
885
+ attribute: null,
886
+ from: element
887
+ });
883
888
  }
884
- }
885
- const body = doc.body || doc.documentElement;
886
- if (dirty && leadingWhitespace) {
887
- body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
888
- }
889
- /* Work on whole document or just its body */
890
- if (NAMESPACE === HTML_NAMESPACE) {
891
- return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
892
- }
893
- return WHOLE_DOCUMENT ? doc.documentElement : body;
894
- };
895
- /**
896
- * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.
897
- *
898
- * @param root The root element or node to start traversing on.
899
- * @return The created NodeIterator
900
- */
901
- const _createNodeIterator = function _createNodeIterator(root) {
902
- return createNodeIterator.call(root.ownerDocument || root, root,
903
- // eslint-disable-next-line no-bitwise
904
- NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
905
- };
906
- /**
907
- * _isClobbered
908
- *
909
- * @param element element to check for clobbering attacks
910
- * @return true if clobbered, false if safe
911
- */
912
- const _isClobbered = function _isClobbered(element) {
913
- return element instanceof HTMLFormElement && (typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function');
914
- };
915
- /**
916
- * Checks whether the given object is a DOM node.
917
- *
918
- * @param value object to check whether it's a DOM node
919
- * @return true is object is a DOM node
920
- */
921
- const _isNode = function _isNode(value) {
922
- return typeof Node === 'function' && value instanceof Node;
923
- };
924
- function _executeHooks(hooks, currentNode, data) {
925
- arrayForEach(hooks, hook => {
926
- hook.call(DOMPurify, currentNode, data, CONFIG);
927
- });
928
- }
929
- /**
930
- * _sanitizeElements
931
- *
932
- * @protect nodeName
933
- * @protect textContent
934
- * @protect removeChild
935
- * @param currentNode to check for permission to exist
936
- * @return true if node was killed, false if left alive
937
- */
938
- const _sanitizeElements = function _sanitizeElements(currentNode) {
939
- let content = null;
940
- /* Execute a hook if present */
941
- _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
942
- /* Check if element is clobbered or can clobber */
943
- if (_isClobbered(currentNode)) {
944
- _forceRemove(currentNode);
945
- return true;
946
- }
947
- /* Now let's check the element's type and name */
948
- const tagName = transformCaseFunc(currentNode.nodeName);
949
- /* Execute a hook if present */
950
- _executeHooks(hooks.uponSanitizeElement, currentNode, {
951
- tagName,
952
- allowedTags: ALLOWED_TAGS
953
- });
954
- /* Detect mXSS attempts abusing namespace confusion */
955
- if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) {
956
- _forceRemove(currentNode);
957
- return true;
958
- }
959
- /* Remove any occurrence of processing instructions */
960
- if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {
961
- _forceRemove(currentNode);
962
- return true;
963
- }
964
- /* Remove any kind of possibly harmful comments */
965
- if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) {
966
- _forceRemove(currentNode);
967
- return true;
968
- }
969
- /* Remove element if anything forbids its presence */
970
- if (!(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName])) {
971
- /* Check if we have a custom element to handle */
972
- if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
973
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
974
- return false;
975
- }
976
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
977
- return false;
889
+ element.removeAttribute(name);
890
+ // We void attribute values for unremovable "is" attributes
891
+ if (name === 'is') {
892
+ if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
893
+ try {
894
+ _forceRemove(element);
895
+ } catch (_) {}
896
+ } else {
897
+ try {
898
+ element.setAttribute(name, '');
899
+ } catch (_) {}
978
900
  }
979
901
  }
980
- /* Keep content except for bad-listed elements */
981
- if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
982
- const parentNode = getParentNode(currentNode) || currentNode.parentNode;
983
- const childNodes = getChildNodes(currentNode) || currentNode.childNodes;
984
- if (childNodes && parentNode) {
985
- const childCount = childNodes.length;
986
- for (let i = childCount - 1; i >= 0; --i) {
987
- const childClone = cloneNode(childNodes[i], true);
988
- childClone.__removalCount = (currentNode.__removalCount || 0) + 1;
989
- parentNode.insertBefore(childClone, getNextSibling(currentNode));
990
- }
902
+ };
903
+ /**
904
+ * _initDocument
905
+ *
906
+ * @param dirty - a string of dirty markup
907
+ * @return a DOM, filled with the dirty markup
908
+ */
909
+ const _initDocument = function _initDocument(dirty) {
910
+ /* Create a HTML document */
911
+ let doc = null;
912
+ let leadingWhitespace = null;
913
+ if (FORCE_BODY) {
914
+ dirty = '<remove></remove>' + dirty;
915
+ } else {
916
+ /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
917
+ const matches = stringMatch(dirty, /^[\r\n\t ]+/);
918
+ leadingWhitespace = matches && matches[0];
919
+ }
920
+ if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {
921
+ // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
922
+ dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
923
+ }
924
+ const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
925
+ /*
926
+ * Use the DOMParser API by default, fallback later if needs be
927
+ * DOMParser not work for svg when has multiple root element.
928
+ */
929
+ if (NAMESPACE === HTML_NAMESPACE) {
930
+ try {
931
+ doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
932
+ } catch (_) {}
933
+ }
934
+ /* Use createHTMLDocument in case DOMParser is not available */
935
+ if (!doc || !doc.documentElement) {
936
+ doc = implementation.createDocument(NAMESPACE, 'template', null);
937
+ try {
938
+ doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;
939
+ } catch (_) {
940
+ // Syntax error if dirtyPayload is invalid xml
991
941
  }
992
942
  }
993
- _forceRemove(currentNode);
994
- return true;
995
- }
996
- /* Check whether element has a valid namespace */
997
- if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
998
- _forceRemove(currentNode);
999
- return true;
1000
- }
1001
- /* Make sure that older browsers don't get fallback-tag mXSS */
1002
- if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {
1003
- _forceRemove(currentNode);
1004
- return true;
943
+ const body = doc.body || doc.documentElement;
944
+ if (dirty && leadingWhitespace) {
945
+ body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
946
+ }
947
+ /* Work on whole document or just its body */
948
+ if (NAMESPACE === HTML_NAMESPACE) {
949
+ return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
950
+ }
951
+ return WHOLE_DOCUMENT ? doc.documentElement : body;
952
+ };
953
+ /**
954
+ * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.
955
+ *
956
+ * @param root The root element or node to start traversing on.
957
+ * @return The created NodeIterator
958
+ */
959
+ const _createNodeIterator = function _createNodeIterator(root) {
960
+ return createNodeIterator.call(root.ownerDocument || root, root,
961
+ // eslint-disable-next-line no-bitwise
962
+ NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
963
+ };
964
+ /**
965
+ * _isClobbered
966
+ *
967
+ * @param element element to check for clobbering attacks
968
+ * @return true if clobbered, false if safe
969
+ */
970
+ const _isClobbered = function _isClobbered(element) {
971
+ return element instanceof HTMLFormElement && (typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function');
972
+ };
973
+ /**
974
+ * Checks whether the given object is a DOM node.
975
+ *
976
+ * @param value object to check whether it's a DOM node
977
+ * @return true is object is a DOM node
978
+ */
979
+ const _isNode = function _isNode(value) {
980
+ return typeof Node === 'function' && value instanceof Node;
981
+ };
982
+ function _executeHooks(hooks, currentNode, data) {
983
+ arrayForEach(hooks, hook => {
984
+ hook.call(DOMPurify, currentNode, data, CONFIG);
985
+ });
1005
986
  }
1006
- /* Sanitize element content to be template-safe */
1007
- if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
1008
- /* Get the element's text content */
1009
- content = currentNode.textContent;
1010
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1011
- content = stringReplace(content, expr, ' ');
987
+ /**
988
+ * _sanitizeElements
989
+ *
990
+ * @protect nodeName
991
+ * @protect textContent
992
+ * @protect removeChild
993
+ * @param currentNode to check for permission to exist
994
+ * @return true if node was killed, false if left alive
995
+ */
996
+ const _sanitizeElements = function _sanitizeElements(currentNode) {
997
+ let content = null;
998
+ /* Execute a hook if present */
999
+ _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
1000
+ /* Check if element is clobbered or can clobber */
1001
+ if (_isClobbered(currentNode)) {
1002
+ _forceRemove(currentNode);
1003
+ return true;
1004
+ }
1005
+ /* Now let's check the element's type and name */
1006
+ const tagName = transformCaseFunc(currentNode.nodeName);
1007
+ /* Execute a hook if present */
1008
+ _executeHooks(hooks.uponSanitizeElement, currentNode, {
1009
+ tagName,
1010
+ allowedTags: ALLOWED_TAGS
1012
1011
  });
1013
- if (currentNode.textContent !== content) {
1014
- arrayPush(DOMPurify.removed, {
1015
- element: currentNode.cloneNode()
1012
+ /* Detect mXSS attempts abusing namespace confusion */
1013
+ if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) {
1014
+ _forceRemove(currentNode);
1015
+ return true;
1016
+ }
1017
+ /* Remove risky CSS construction leading to mXSS */
1018
+ if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {
1019
+ _forceRemove(currentNode);
1020
+ return true;
1021
+ }
1022
+ /* Remove any occurrence of processing instructions */
1023
+ if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {
1024
+ _forceRemove(currentNode);
1025
+ return true;
1026
+ }
1027
+ /* Remove any kind of possibly harmful comments */
1028
+ if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) {
1029
+ _forceRemove(currentNode);
1030
+ return true;
1031
+ }
1032
+ /* Remove element if anything forbids its presence */
1033
+ if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) {
1034
+ /* Check if we have a custom element to handle */
1035
+ if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
1036
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
1037
+ return false;
1038
+ }
1039
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
1040
+ return false;
1041
+ }
1042
+ }
1043
+ /* Keep content except for bad-listed elements */
1044
+ if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
1045
+ const parentNode = getParentNode(currentNode) || currentNode.parentNode;
1046
+ const childNodes = getChildNodes(currentNode) || currentNode.childNodes;
1047
+ if (childNodes && parentNode) {
1048
+ const childCount = childNodes.length;
1049
+ for (let i = childCount - 1; i >= 0; --i) {
1050
+ const childClone = cloneNode(childNodes[i], true);
1051
+ parentNode.insertBefore(childClone, getNextSibling(currentNode));
1052
+ }
1053
+ }
1054
+ }
1055
+ _forceRemove(currentNode);
1056
+ return true;
1057
+ }
1058
+ /* Check whether element has a valid namespace */
1059
+ if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
1060
+ _forceRemove(currentNode);
1061
+ return true;
1062
+ }
1063
+ /* Make sure that older browsers don't get fallback-tag mXSS */
1064
+ if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {
1065
+ _forceRemove(currentNode);
1066
+ return true;
1067
+ }
1068
+ /* Sanitize element content to be template-safe */
1069
+ if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
1070
+ /* Get the element's text content */
1071
+ content = currentNode.textContent;
1072
+ arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1073
+ content = stringReplace(content, expr, ' ');
1016
1074
  });
1017
- currentNode.textContent = content;
1075
+ if (currentNode.textContent !== content) {
1076
+ arrayPush(DOMPurify.removed, {
1077
+ element: currentNode.cloneNode()
1078
+ });
1079
+ currentNode.textContent = content;
1080
+ }
1018
1081
  }
1019
- }
1020
- /* Execute a hook if present */
1021
- _executeHooks(hooks.afterSanitizeElements, currentNode, null);
1022
- return false;
1023
- };
1024
- /**
1025
- * _isValidAttribute
1026
- *
1027
- * @param lcTag Lowercase tag name of containing element.
1028
- * @param lcName Lowercase attribute name.
1029
- * @param value Attribute value.
1030
- * @return Returns true if `value` is valid, otherwise false.
1031
- */
1032
- // eslint-disable-next-line complexity
1033
- const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
1034
- /* FORBID_ATTR must always win, even if ADD_ATTR predicate would allow it */
1035
- if (FORBID_ATTR[lcName]) {
1036
- return false;
1037
- }
1038
- /* Make sure attribute cannot clobber */
1039
- if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
1082
+ /* Execute a hook if present */
1083
+ _executeHooks(hooks.afterSanitizeElements, currentNode, null);
1040
1084
  return false;
1041
- }
1042
- /* Allow valid data-* attributes: At least one character after "-"
1043
- (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
1044
- XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
1045
- We don't need to check the value; it's always URI safe. */
1046
- if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) ; else if (EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
1047
- if (
1048
- // First condition does a very basic check if a) it's basically a valid custom element tagname AND
1049
- // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1050
- // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
1051
- _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName, lcTag)) ||
1052
- // Alternative, second condition checks if it's an `is`-attribute, AND
1053
- // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1054
- lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else {
1085
+ };
1086
+ /**
1087
+ * _isValidAttribute
1088
+ *
1089
+ * @param lcTag Lowercase tag name of containing element.
1090
+ * @param lcName Lowercase attribute name.
1091
+ * @param value Attribute value.
1092
+ * @return Returns true if `value` is valid, otherwise false.
1093
+ */
1094
+ // eslint-disable-next-line complexity
1095
+ const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
1096
+ /* FORBID_ATTR must always win, even if ADD_ATTR predicate would allow it */
1097
+ if (FORBID_ATTR[lcName]) {
1055
1098
  return false;
1056
1099
  }
1057
- /* Check value is safe. First, is attr inert? If so, is safe */
1058
- } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if (value) {
1059
- return false;
1060
- } else ;
1061
- return true;
1062
- };
1063
- /**
1064
- * _isBasicCustomElement
1065
- * checks if at least one dash is included in tagName, and it's not the first char
1066
- * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name
1067
- *
1068
- * @param tagName name of the tag of the node to sanitize
1069
- * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.
1070
- */
1071
- const _isBasicCustomElement = function _isBasicCustomElement(tagName) {
1072
- return tagName !== 'annotation-xml' && stringMatch(tagName, CUSTOM_ELEMENT);
1073
- };
1074
- /**
1075
- * _sanitizeAttributes
1076
- *
1077
- * @protect attributes
1078
- * @protect nodeName
1079
- * @protect removeAttribute
1080
- * @protect setAttribute
1081
- *
1082
- * @param currentNode to sanitize
1083
- */
1084
- const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
1085
- /* Execute a hook if present */
1086
- _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);
1087
- const {
1088
- attributes
1089
- } = currentNode;
1090
- /* Check if we have attributes; if not we might have a text node */
1091
- if (!attributes || _isClobbered(currentNode)) {
1092
- return;
1093
- }
1094
- const hookEvent = {
1095
- attrName: '',
1096
- attrValue: '',
1097
- keepAttr: true,
1098
- allowedAttributes: ALLOWED_ATTR,
1099
- forceKeepAttr: undefined
1100
+ /* Make sure attribute cannot clobber */
1101
+ if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
1102
+ return false;
1103
+ }
1104
+ /* Allow valid data-* attributes: At least one character after "-"
1105
+ (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
1106
+ XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
1107
+ We don't need to check the value; it's always URI safe. */
1108
+ if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) ; else if (EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
1109
+ if (
1110
+ // First condition does a very basic check if a) it's basically a valid custom element tagname AND
1111
+ // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1112
+ // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
1113
+ _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName, lcTag)) ||
1114
+ // Alternative, second condition checks if it's an `is`-attribute, AND
1115
+ // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1116
+ lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else {
1117
+ return false;
1118
+ }
1119
+ /* Check value is safe. First, is attr inert? If so, is safe */
1120
+ } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if (value) {
1121
+ return false;
1122
+ } else ;
1123
+ return true;
1100
1124
  };
1101
- let l = attributes.length;
1102
- /* Go backwards over all attributes; safely remove bad ones */
1103
- while (l--) {
1104
- const attr = attributes[l];
1105
- const {
1106
- name,
1107
- namespaceURI,
1108
- value: attrValue
1109
- } = attr;
1110
- const lcName = transformCaseFunc(name);
1111
- const initValue = attrValue;
1112
- let value = name === 'value' ? initValue : stringTrim(initValue);
1125
+ /* Names the HTML spec reserves from valid-custom-element-name; these must
1126
+ * never be treated as basic custom elements even when a permissive
1127
+ * CUSTOM_ELEMENT_HANDLING.tagNameCheck is configured. */
1128
+ const RESERVED_CUSTOM_ELEMENT_NAMES = addToSet({}, ['annotation-xml', 'color-profile', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'missing-glyph']);
1129
+ /**
1130
+ * _isBasicCustomElement
1131
+ * checks if at least one dash is included in tagName, and it's not the first char
1132
+ * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name
1133
+ *
1134
+ * @param tagName name of the tag of the node to sanitize
1135
+ * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.
1136
+ */
1137
+ const _isBasicCustomElement = function _isBasicCustomElement(tagName) {
1138
+ return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT, tagName);
1139
+ };
1140
+ /**
1141
+ * _sanitizeAttributes
1142
+ *
1143
+ * @protect attributes
1144
+ * @protect nodeName
1145
+ * @protect removeAttribute
1146
+ * @protect setAttribute
1147
+ *
1148
+ * @param currentNode to sanitize
1149
+ */
1150
+ const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
1113
1151
  /* Execute a hook if present */
1114
- hookEvent.attrName = lcName;
1115
- hookEvent.attrValue = value;
1116
- hookEvent.keepAttr = true;
1117
- hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
1118
- _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);
1119
- value = hookEvent.attrValue;
1120
- /* Full DOM Clobbering protection via namespace isolation,
1121
- * Prefix id and name attributes with `user-content-`
1122
- */
1123
- if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {
1124
- // Remove the attribute with this value
1125
- _removeAttribute(name, currentNode);
1126
- // Prefix the value and later re-create the attribute with the sanitized value
1127
- value = SANITIZE_NAMED_PROPS_PREFIX + value;
1128
- }
1129
- /* Work around a security issue with comments inside attributes */
1130
- if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {
1131
- _removeAttribute(name, currentNode);
1132
- continue;
1133
- }
1134
- /* Make sure we cannot easily use animated hrefs, even if animations are allowed */
1135
- if (lcName === 'attributename' && stringMatch(value, 'href')) {
1136
- _removeAttribute(name, currentNode);
1137
- continue;
1138
- }
1139
- /* Did the hooks approve of the attribute? */
1140
- if (hookEvent.forceKeepAttr) {
1141
- continue;
1142
- }
1143
- /* Did the hooks approve of the attribute? */
1144
- if (!hookEvent.keepAttr) {
1145
- _removeAttribute(name, currentNode);
1146
- continue;
1147
- }
1148
- /* Work around a security issue in jQuery 3.0 */
1149
- if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
1150
- _removeAttribute(name, currentNode);
1151
- continue;
1152
- }
1153
- /* Sanitize attribute content to be template-safe */
1154
- if (SAFE_FOR_TEMPLATES) {
1155
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1156
- value = stringReplace(value, expr, ' ');
1157
- });
1152
+ _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);
1153
+ const {
1154
+ attributes
1155
+ } = currentNode;
1156
+ /* Check if we have attributes; if not we might have a text node */
1157
+ if (!attributes || _isClobbered(currentNode)) {
1158
+ return;
1158
1159
  }
1159
- /* Is `value` valid for this attribute? */
1160
- const lcTag = transformCaseFunc(currentNode.nodeName);
1161
- if (!_isValidAttribute(lcTag, lcName, value)) {
1162
- _removeAttribute(name, currentNode);
1163
- continue;
1164
- }
1165
- /* Handle attributes that require Trusted Types */
1166
- if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {
1167
- if (namespaceURI) ; else {
1168
- switch (trustedTypes.getAttributeType(lcTag, lcName)) {
1169
- case 'TrustedHTML':
1170
- {
1171
- value = trustedTypesPolicy.createHTML(value);
1172
- break;
1173
- }
1174
- case 'TrustedScriptURL':
1175
- {
1176
- value = trustedTypesPolicy.createScriptURL(value);
1177
- break;
1178
- }
1179
- }
1160
+ const hookEvent = {
1161
+ attrName: '',
1162
+ attrValue: '',
1163
+ keepAttr: true,
1164
+ allowedAttributes: ALLOWED_ATTR,
1165
+ forceKeepAttr: undefined
1166
+ };
1167
+ let l = attributes.length;
1168
+ /* Go backwards over all attributes; safely remove bad ones */
1169
+ while (l--) {
1170
+ const attr = attributes[l];
1171
+ const {
1172
+ name,
1173
+ namespaceURI,
1174
+ value: attrValue
1175
+ } = attr;
1176
+ const lcName = transformCaseFunc(name);
1177
+ const initValue = attrValue;
1178
+ let value = name === 'value' ? initValue : stringTrim(initValue);
1179
+ /* Execute a hook if present */
1180
+ hookEvent.attrName = lcName;
1181
+ hookEvent.attrValue = value;
1182
+ hookEvent.keepAttr = true;
1183
+ hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
1184
+ _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);
1185
+ value = hookEvent.attrValue;
1186
+ /* Full DOM Clobbering protection via namespace isolation,
1187
+ * Prefix id and name attributes with `user-content-`
1188
+ */
1189
+ if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name') && stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0) {
1190
+ // Remove the attribute with this value
1191
+ _removeAttribute(name, currentNode);
1192
+ // Prefix the value and later re-create the attribute with the sanitized value
1193
+ value = SANITIZE_NAMED_PROPS_PREFIX + value;
1180
1194
  }
1181
- }
1182
- /* Handle invalid data-* attribute set by try-catching it */
1183
- if (value !== initValue) {
1184
- try {
1185
- if (namespaceURI) {
1186
- currentNode.setAttributeNS(namespaceURI, name, value);
1187
- } else {
1188
- /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
1189
- currentNode.setAttribute(name, value);
1195
+ // Else: already prefixed, leave the attribute alone — the prefix is
1196
+ // itself the clobbering protection, and re-applying it is incorrect.
1197
+ /* Work around a security issue with comments inside attributes */
1198
+ if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {
1199
+ _removeAttribute(name, currentNode);
1200
+ continue;
1201
+ }
1202
+ /* Make sure we cannot easily use animated hrefs, even if animations are allowed */
1203
+ if (lcName === 'attributename' && stringMatch(value, 'href')) {
1204
+ _removeAttribute(name, currentNode);
1205
+ continue;
1206
+ }
1207
+ /* Did the hooks approve of the attribute? */
1208
+ if (hookEvent.forceKeepAttr) {
1209
+ continue;
1210
+ }
1211
+ /* Did the hooks approve of the attribute? */
1212
+ if (!hookEvent.keepAttr) {
1213
+ _removeAttribute(name, currentNode);
1214
+ continue;
1215
+ }
1216
+ /* Work around a security issue in jQuery 3.0 */
1217
+ if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
1218
+ _removeAttribute(name, currentNode);
1219
+ continue;
1220
+ }
1221
+ /* Sanitize attribute content to be template-safe */
1222
+ if (SAFE_FOR_TEMPLATES) {
1223
+ arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1224
+ value = stringReplace(value, expr, ' ');
1225
+ });
1226
+ }
1227
+ /* Is `value` valid for this attribute? */
1228
+ const lcTag = transformCaseFunc(currentNode.nodeName);
1229
+ if (!_isValidAttribute(lcTag, lcName, value)) {
1230
+ _removeAttribute(name, currentNode);
1231
+ continue;
1232
+ }
1233
+ /* Handle attributes that require Trusted Types */
1234
+ if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {
1235
+ if (namespaceURI) ; else {
1236
+ switch (trustedTypes.getAttributeType(lcTag, lcName)) {
1237
+ case 'TrustedHTML':
1238
+ {
1239
+ value = trustedTypesPolicy.createHTML(value);
1240
+ break;
1241
+ }
1242
+ case 'TrustedScriptURL':
1243
+ {
1244
+ value = trustedTypesPolicy.createScriptURL(value);
1245
+ break;
1246
+ }
1247
+ }
1190
1248
  }
1191
- if (_isClobbered(currentNode)) {
1192
- _forceRemove(currentNode);
1193
- } else {
1194
- arrayPop(DOMPurify.removed);
1249
+ }
1250
+ /* Handle invalid data-* attribute set by try-catching it */
1251
+ if (value !== initValue) {
1252
+ try {
1253
+ if (namespaceURI) {
1254
+ currentNode.setAttributeNS(namespaceURI, name, value);
1255
+ } else {
1256
+ /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
1257
+ currentNode.setAttribute(name, value);
1258
+ }
1259
+ if (_isClobbered(currentNode)) {
1260
+ _forceRemove(currentNode);
1261
+ } else {
1262
+ arrayPop(DOMPurify.removed);
1263
+ }
1264
+ } catch (_) {
1265
+ _removeAttribute(name, currentNode);
1195
1266
  }
1196
- } catch (_) {
1197
- _removeAttribute(name, currentNode);
1198
1267
  }
1199
1268
  }
1200
- }
1201
- /* Execute a hook if present */
1202
- _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);
1203
- };
1204
- /**
1205
- * _sanitizeShadowDOM
1206
- *
1207
- * @param fragment to iterate over recursively
1208
- */
1209
- const _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {
1210
- let shadowNode = null;
1211
- const shadowIterator = _createNodeIterator(fragment);
1212
- /* Execute a hook if present */
1213
- _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);
1214
- while (shadowNode = shadowIterator.nextNode()) {
1215
1269
  /* Execute a hook if present */
1216
- _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);
1217
- /* Sanitize tags and elements */
1218
- _sanitizeElements(shadowNode);
1219
- /* Check attributes next */
1220
- _sanitizeAttributes(shadowNode);
1221
- /* Deep shadow DOM detected */
1222
- if (shadowNode.content instanceof DocumentFragment) {
1223
- _sanitizeShadowDOM(shadowNode.content);
1270
+ _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);
1271
+ };
1272
+ /**
1273
+ * _sanitizeShadowDOM
1274
+ *
1275
+ * @param fragment to iterate over recursively
1276
+ */
1277
+ const _sanitizeShadowDOM2 = function _sanitizeShadowDOM(fragment) {
1278
+ let shadowNode = null;
1279
+ const shadowIterator = _createNodeIterator(fragment);
1280
+ /* Execute a hook if present */
1281
+ _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);
1282
+ while (shadowNode = shadowIterator.nextNode()) {
1283
+ /* Execute a hook if present */
1284
+ _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);
1285
+ /* Sanitize tags and elements */
1286
+ _sanitizeElements(shadowNode);
1287
+ /* Check attributes next */
1288
+ _sanitizeAttributes(shadowNode);
1289
+ /* Deep shadow DOM detected */
1290
+ if (shadowNode.content instanceof DocumentFragment) {
1291
+ _sanitizeShadowDOM2(shadowNode.content);
1292
+ }
1224
1293
  }
1225
- }
1226
- /* Execute a hook if present */
1227
- _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
1228
- };
1229
- // eslint-disable-next-line complexity
1230
- DOMPurify.sanitize = function (dirty) {
1231
- let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1232
- let body = null;
1233
- let importedNode = null;
1234
- let currentNode = null;
1235
- let returnNode = null;
1236
- /* Make sure we have a string to sanitize.
1237
- DO NOT return early, as this will return the wrong type if
1238
- the user has requested a DOM object rather than a string */
1239
- IS_EMPTY_INPUT = !dirty;
1240
- if (IS_EMPTY_INPUT) {
1241
- dirty = '<!-->';
1242
- }
1243
- /* Stringify, in case dirty is an object */
1244
- if (typeof dirty !== 'string' && !_isNode(dirty)) {
1245
- if (typeof dirty.toString === 'function') {
1246
- dirty = dirty.toString();
1294
+ /* Execute a hook if present */
1295
+ _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
1296
+ };
1297
+ // eslint-disable-next-line complexity
1298
+ DOMPurify.sanitize = function (dirty) {
1299
+ let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1300
+ let body = null;
1301
+ let importedNode = null;
1302
+ let currentNode = null;
1303
+ let returnNode = null;
1304
+ /* Make sure we have a string to sanitize.
1305
+ DO NOT return early, as this will return the wrong type if
1306
+ the user has requested a DOM object rather than a string */
1307
+ IS_EMPTY_INPUT = !dirty;
1308
+ if (IS_EMPTY_INPUT) {
1309
+ dirty = '<!-->';
1310
+ }
1311
+ /* Stringify, in case dirty is an object */
1312
+ if (typeof dirty !== 'string' && !_isNode(dirty)) {
1313
+ dirty = stringifyValue(dirty);
1247
1314
  if (typeof dirty !== 'string') {
1248
1315
  throw typeErrorCreate('dirty is not a string, aborting');
1249
1316
  }
1250
- } else {
1251
- throw typeErrorCreate('toString is not a function');
1252
1317
  }
1253
- }
1254
- /* Return dirty HTML if DOMPurify cannot run */
1255
- if (!DOMPurify.isSupported) {
1256
- return dirty;
1257
- }
1258
- /* Assign config vars */
1259
- if (!SET_CONFIG) {
1260
- _parseConfig(cfg);
1261
- }
1262
- /* Clean up removed elements */
1263
- DOMPurify.removed = [];
1264
- /* Check if dirty is correctly typed for IN_PLACE */
1265
- if (typeof dirty === 'string') {
1266
- IN_PLACE = false;
1267
- }
1268
- if (IN_PLACE) {
1269
- /* Do some early pre-sanitization to avoid unsafe root nodes */
1270
- if (dirty.nodeName) {
1271
- const tagName = transformCaseFunc(dirty.nodeName);
1272
- if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
1273
- throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
1274
- }
1318
+ /* Return dirty HTML if DOMPurify cannot run */
1319
+ if (!DOMPurify.isSupported) {
1320
+ return dirty;
1321
+ }
1322
+ /* Assign config vars */
1323
+ if (!SET_CONFIG) {
1324
+ _parseConfig(cfg);
1325
+ }
1326
+ /* Clean up removed elements */
1327
+ DOMPurify.removed = [];
1328
+ /* Check if dirty is correctly typed for IN_PLACE */
1329
+ if (typeof dirty === 'string') {
1330
+ IN_PLACE = false;
1275
1331
  }
1276
- } else if (dirty instanceof Node) {
1277
- /* If dirty is a DOM element, append to an empty document to avoid
1278
- elements being stripped by the parser */
1279
- body = _initDocument('<!---->');
1280
- importedNode = body.ownerDocument.importNode(dirty, true);
1281
- if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') {
1282
- /* Node is already a body, use as is */
1283
- body = importedNode;
1284
- } else if (importedNode.nodeName === 'HTML') {
1285
- body = importedNode;
1332
+ if (IN_PLACE) {
1333
+ /* Do some early pre-sanitization to avoid unsafe root nodes */
1334
+ const nn = dirty.nodeName;
1335
+ if (typeof nn === 'string') {
1336
+ const tagName = transformCaseFunc(nn);
1337
+ if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
1338
+ throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
1339
+ }
1340
+ }
1341
+ } else if (dirty instanceof Node) {
1342
+ /* If dirty is a DOM element, append to an empty document to avoid
1343
+ elements being stripped by the parser */
1344
+ body = _initDocument('<!---->');
1345
+ importedNode = body.ownerDocument.importNode(dirty, true);
1346
+ if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') {
1347
+ /* Node is already a body, use as is */
1348
+ body = importedNode;
1349
+ } else if (importedNode.nodeName === 'HTML') {
1350
+ body = importedNode;
1351
+ } else {
1352
+ // eslint-disable-next-line unicorn/prefer-dom-node-append
1353
+ body.appendChild(importedNode);
1354
+ }
1286
1355
  } else {
1287
- // eslint-disable-next-line unicorn/prefer-dom-node-append
1288
- body.appendChild(importedNode);
1356
+ /* Exit directly if we have nothing to do */
1357
+ if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
1358
+ // eslint-disable-next-line unicorn/prefer-includes
1359
+ dirty.indexOf('<') === -1) {
1360
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
1361
+ }
1362
+ /* Initialize the document to work on */
1363
+ body = _initDocument(dirty);
1364
+ /* Check we have a DOM node from the data */
1365
+ if (!body) {
1366
+ return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
1367
+ }
1289
1368
  }
1290
- } else {
1291
- /* Exit directly if we have nothing to do */
1292
- if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
1293
- // eslint-disable-next-line unicorn/prefer-includes
1294
- dirty.indexOf('<') === -1) {
1295
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
1369
+ /* Remove first element node (ours) if FORCE_BODY is set */
1370
+ if (body && FORCE_BODY) {
1371
+ _forceRemove(body.firstChild);
1296
1372
  }
1297
- /* Initialize the document to work on */
1298
- body = _initDocument(dirty);
1299
- /* Check we have a DOM node from the data */
1300
- if (!body) {
1301
- return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
1373
+ /* Get node iterator */
1374
+ const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);
1375
+ /* Now start iterating over the created document */
1376
+ while (currentNode = nodeIterator.nextNode()) {
1377
+ /* Sanitize tags and elements */
1378
+ _sanitizeElements(currentNode);
1379
+ /* Check attributes next */
1380
+ _sanitizeAttributes(currentNode);
1381
+ /* Shadow DOM detected, sanitize it */
1382
+ if (currentNode.content instanceof DocumentFragment) {
1383
+ _sanitizeShadowDOM2(currentNode.content);
1384
+ }
1302
1385
  }
1303
- }
1304
- /* Remove first element node (ours) if FORCE_BODY is set */
1305
- if (body && FORCE_BODY) {
1306
- _forceRemove(body.firstChild);
1307
- }
1308
- /* Get node iterator */
1309
- const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);
1310
- /* Now start iterating over the created document */
1311
- while (currentNode = nodeIterator.nextNode()) {
1312
- /* Sanitize tags and elements */
1313
- _sanitizeElements(currentNode);
1314
- /* Check attributes next */
1315
- _sanitizeAttributes(currentNode);
1316
- /* Shadow DOM detected, sanitize it */
1317
- if (currentNode.content instanceof DocumentFragment) {
1318
- _sanitizeShadowDOM(currentNode.content);
1386
+ /* If we sanitized `dirty` in-place, return it. */
1387
+ if (IN_PLACE) {
1388
+ return dirty;
1319
1389
  }
1320
- }
1321
- /* If we sanitized `dirty` in-place, return it. */
1322
- if (IN_PLACE) {
1323
- return dirty;
1324
- }
1325
- /* Return sanitized string or DOM */
1326
- if (RETURN_DOM) {
1327
- if (RETURN_DOM_FRAGMENT) {
1328
- returnNode = createDocumentFragment.call(body.ownerDocument);
1329
- while (body.firstChild) {
1330
- // eslint-disable-next-line unicorn/prefer-dom-node-append
1331
- returnNode.appendChild(body.firstChild);
1390
+ /* Return sanitized string or DOM */
1391
+ if (RETURN_DOM) {
1392
+ if (SAFE_FOR_TEMPLATES) {
1393
+ body.normalize();
1394
+ let html = body.innerHTML;
1395
+ arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1396
+ html = stringReplace(html, expr, ' ');
1397
+ });
1398
+ body.innerHTML = html;
1332
1399
  }
1333
- } else {
1334
- returnNode = body;
1335
- }
1336
- if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {
1337
- /*
1338
- AdoptNode() is not used because internal state is not reset
1339
- (e.g. the past names map of a HTMLFormElement), this is safe
1340
- in theory but we would rather not risk another attack vector.
1341
- The state that is cloned by importNode() is explicitly defined
1342
- by the specs.
1343
- */
1344
- returnNode = importNode.call(originalDocument, returnNode, true);
1345
- }
1346
- return returnNode;
1347
- }
1348
- let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
1349
- /* Serialize doctype if allowed */
1350
- if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
1351
- serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
1352
- }
1353
- /* Sanitize final string template-safe */
1354
- if (SAFE_FOR_TEMPLATES) {
1355
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1356
- serializedHTML = stringReplace(serializedHTML, expr, ' ');
1357
- });
1358
- }
1359
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
1360
- };
1361
- DOMPurify.setConfig = function () {
1362
- let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1363
- _parseConfig(cfg);
1364
- SET_CONFIG = true;
1365
- };
1366
- DOMPurify.clearConfig = function () {
1367
- CONFIG = null;
1368
- SET_CONFIG = false;
1369
- };
1370
- DOMPurify.isValidAttribute = function (tag, attr, value) {
1371
- /* Initialize shared config vars if necessary. */
1372
- if (!CONFIG) {
1373
- _parseConfig({});
1374
- }
1375
- const lcTag = transformCaseFunc(tag);
1376
- const lcName = transformCaseFunc(attr);
1377
- return _isValidAttribute(lcTag, lcName, value);
1378
- };
1379
- DOMPurify.addHook = function (entryPoint, hookFunction) {
1380
- if (typeof hookFunction !== 'function') {
1381
- return;
1382
- }
1383
- arrayPush(hooks[entryPoint], hookFunction);
1384
- };
1385
- DOMPurify.removeHook = function (entryPoint, hookFunction) {
1386
- if (hookFunction !== undefined) {
1387
- const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);
1388
- return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];
1389
- }
1390
- return arrayPop(hooks[entryPoint]);
1391
- };
1392
- DOMPurify.removeHooks = function (entryPoint) {
1393
- hooks[entryPoint] = [];
1394
- };
1395
- DOMPurify.removeAllHooks = function () {
1396
- hooks = _createHooksMap();
1397
- };
1398
- return DOMPurify;
1399
- }
1400
- var purify = createDOMPurify();
1400
+ if (RETURN_DOM_FRAGMENT) {
1401
+ returnNode = createDocumentFragment.call(body.ownerDocument);
1402
+ while (body.firstChild) {
1403
+ // eslint-disable-next-line unicorn/prefer-dom-node-append
1404
+ returnNode.appendChild(body.firstChild);
1405
+ }
1406
+ } else {
1407
+ returnNode = body;
1408
+ }
1409
+ if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {
1410
+ /*
1411
+ AdoptNode() is not used because internal state is not reset
1412
+ (e.g. the past names map of a HTMLFormElement), this is safe
1413
+ in theory but we would rather not risk another attack vector.
1414
+ The state that is cloned by importNode() is explicitly defined
1415
+ by the specs.
1416
+ */
1417
+ returnNode = importNode.call(originalDocument, returnNode, true);
1418
+ }
1419
+ return returnNode;
1420
+ }
1421
+ let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
1422
+ /* Serialize doctype if allowed */
1423
+ if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
1424
+ serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
1425
+ }
1426
+ /* Sanitize final string template-safe */
1427
+ if (SAFE_FOR_TEMPLATES) {
1428
+ arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1429
+ serializedHTML = stringReplace(serializedHTML, expr, ' ');
1430
+ });
1431
+ }
1432
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
1433
+ };
1434
+ DOMPurify.setConfig = function () {
1435
+ let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1436
+ _parseConfig(cfg);
1437
+ SET_CONFIG = true;
1438
+ };
1439
+ DOMPurify.clearConfig = function () {
1440
+ CONFIG = null;
1441
+ SET_CONFIG = false;
1442
+ };
1443
+ DOMPurify.isValidAttribute = function (tag, attr, value) {
1444
+ /* Initialize shared config vars if necessary. */
1445
+ if (!CONFIG) {
1446
+ _parseConfig({});
1447
+ }
1448
+ const lcTag = transformCaseFunc(tag);
1449
+ const lcName = transformCaseFunc(attr);
1450
+ return _isValidAttribute(lcTag, lcName, value);
1451
+ };
1452
+ DOMPurify.addHook = function (entryPoint, hookFunction) {
1453
+ if (typeof hookFunction !== 'function') {
1454
+ return;
1455
+ }
1456
+ arrayPush(hooks[entryPoint], hookFunction);
1457
+ };
1458
+ DOMPurify.removeHook = function (entryPoint, hookFunction) {
1459
+ if (hookFunction !== undefined) {
1460
+ const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);
1461
+ return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];
1462
+ }
1463
+ return arrayPop(hooks[entryPoint]);
1464
+ };
1465
+ DOMPurify.removeHooks = function (entryPoint) {
1466
+ hooks[entryPoint] = [];
1467
+ };
1468
+ DOMPurify.removeAllHooks = function () {
1469
+ hooks = _createHooksMap();
1470
+ };
1471
+ return DOMPurify;
1472
+ }
1473
+ var purify = createDOMPurify();
1401
1474
 
1402
- return purify;
1475
+ return purify;
1403
1476
 
1404
1477
  }));
1405
1478
  //# sourceMappingURL=purify.js.map