dompurify 3.4.0 → 3.4.2

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,1406 +1,1479 @@
1
- /*! @license DOMPurify 3.4.0 | (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.0/LICENSE */
1
+ /*! @license DOMPurify 3.4.2 | (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.2/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', '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']);
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
- text: 3,
244
- // Deprecated
245
- progressingInstruction: 7,
246
- comment: 8,
247
- document: 9};
248
- const getGlobal = function getGlobal() {
249
- return typeof window === 'undefined' ? null : window;
250
- };
251
- /**
252
- * Creates a no-op policy for internal use only.
253
- * Don't export this function outside this module!
254
- * @param trustedTypes The policy factory.
255
- * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).
256
- * @return The policy created (or null, if Trusted Types
257
- * are not supported or creating the policy failed).
258
- */
259
- const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {
260
- if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
261
- return null;
262
- }
263
- // Allow the callers to control the unique policy name
264
- // by adding a data-tt-policy-suffix to the script element with the DOMPurify.
265
- // Policy creation with duplicate names throws in Trusted Types.
266
- let suffix = null;
267
- const ATTR_NAME = 'data-tt-policy-suffix';
268
- if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {
269
- suffix = purifyHostElement.getAttribute(ATTR_NAME);
270
- }
271
- const policyName = 'dompurify' + (suffix ? '#' + suffix : '');
272
- try {
273
- return trustedTypes.createPolicy(policyName, {
274
- createHTML(html) {
275
- return html;
276
- },
277
- createScriptURL(scriptUrl) {
278
- return scriptUrl;
279
- }
280
- });
281
- } catch (_) {
282
- // Policy creation failed (most likely another DOMPurify script has
283
- // already run). Skip creating the policy, as this will only cause errors
284
- // if TT are enforced.
285
- console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
286
- return null;
287
- }
288
- };
289
- const _createHooksMap = function _createHooksMap() {
290
- return {
291
- afterSanitizeAttributes: [],
292
- afterSanitizeElements: [],
293
- afterSanitizeShadowDOM: [],
294
- beforeSanitizeAttributes: [],
295
- beforeSanitizeElements: [],
296
- beforeSanitizeShadowDOM: [],
297
- uponSanitizeAttribute: [],
298
- uponSanitizeElement: [],
299
- uponSanitizeShadowNode: []
300
- };
301
- };
302
- function createDOMPurify() {
303
- let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
304
- const DOMPurify = root => createDOMPurify(root);
305
- DOMPurify.version = '3.4.0';
306
- DOMPurify.removed = [];
307
- if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {
308
- // Not running in a browser, provide a factory function
309
- // so that you can pass your own Window
310
- DOMPurify.isSupported = false;
311
- return DOMPurify;
312
- }
313
- let {
314
- document
315
- } = window;
316
- const originalDocument = document;
317
- const currentScript = originalDocument.currentScript;
318
- const {
319
- DocumentFragment,
320
- HTMLTemplateElement,
321
- Node,
322
- Element,
323
- NodeFilter,
324
- NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap,
325
- HTMLFormElement,
326
- DOMParser,
327
- trustedTypes
328
- } = window;
329
- const ElementPrototype = Element.prototype;
330
- const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
331
- const remove = lookupGetter(ElementPrototype, 'remove');
332
- const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
333
- const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
334
- const getParentNode = lookupGetter(ElementPrototype, 'parentNode');
335
- // As per issue #47, the web-components registry is inherited by a
336
- // new document created via createHTMLDocument. As per the spec
337
- // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
338
- // a new empty registry is used when creating a template contents owner
339
- // document, so we use that as our parent document to ensure nothing
340
- // is inherited.
341
- if (typeof HTMLTemplateElement === 'function') {
342
- const template = document.createElement('template');
343
- if (template.content && template.content.ownerDocument) {
344
- document = template.content.ownerDocument;
345
- }
48
+ return new Func(...args);
49
+ };
346
50
  }
347
- let trustedTypesPolicy;
348
- let emptyHTML = '';
349
- const {
350
- implementation,
351
- createNodeIterator,
352
- createDocumentFragment,
353
- getElementsByTagName
354
- } = document;
355
- const {
356
- importNode
357
- } = originalDocument;
358
- let hooks = _createHooksMap();
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);
359
71
  /**
360
- * Expose whether this browser supports running the full DOMPurify.
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.
361
76
  */
362
- DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;
363
- const {
364
- MUSTACHE_EXPR,
365
- ERB_EXPR,
366
- TMPLIT_EXPR,
367
- DATA_ATTR,
368
- ARIA_ATTR,
369
- IS_SCRIPT_OR_DATA,
370
- ATTR_WHITESPACE,
371
- CUSTOM_ELEMENT
372
- } = EXPRESSIONS;
373
- let {
374
- IS_ALLOWED_URI: IS_ALLOWED_URI$1
375
- } = EXPRESSIONS;
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
+ };
87
+ }
376
88
  /**
377
- * We consider the elements and attributes below to be safe. Ideally
378
- * don't add any new ones but feel free to remove unwanted ones.
379
- */
380
- /* allowed element names */
381
- let ALLOWED_TAGS = null;
382
- const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);
383
- /* Allowed attribute names */
384
- let ALLOWED_ATTR = null;
385
- const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);
386
- /*
387
- * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.
388
- * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)
389
- * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)
390
- * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.
391
- */
392
- let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {
393
- tagNameCheck: {
394
- writable: true,
395
- configurable: false,
396
- enumerable: true,
397
- value: null
398
- },
399
- attributeNameCheck: {
400
- writable: true,
401
- configurable: false,
402
- enumerable: true,
403
- value: null
404
- },
405
- allowCustomizedBuiltInElements: {
406
- writable: true,
407
- configurable: false,
408
- enumerable: true,
409
- value: false
410
- }
411
- }));
412
- /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
413
- let FORBID_TAGS = null;
414
- /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
415
- let FORBID_ATTR = null;
416
- /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */
417
- const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, {
418
- tagCheck: {
419
- writable: true,
420
- configurable: false,
421
- enumerable: true,
422
- value: null
423
- },
424
- attributeCheck: {
425
- writable: true,
426
- configurable: false,
427
- enumerable: true,
428
- value: null
429
- }
430
- }));
431
- /* Decide if ARIA attributes are okay */
432
- let ALLOW_ARIA_ATTR = true;
433
- /* Decide if custom data attributes are okay */
434
- let ALLOW_DATA_ATTR = true;
435
- /* Decide if unknown protocols are okay */
436
- let ALLOW_UNKNOWN_PROTOCOLS = false;
437
- /* Decide if self-closing tags in attributes are allowed.
438
- * Usually removed due to a mXSS issue in jQuery 3.0 */
439
- let ALLOW_SELF_CLOSE_IN_ATTR = true;
440
- /* Output should be safe for common template engines.
441
- * This means, DOMPurify removes data attributes, mustaches and ERB
442
- */
443
- let SAFE_FOR_TEMPLATES = false;
444
- /* Output should be safe even for XML used within HTML and alike.
445
- * This means, DOMPurify removes comments when containing risky content.
446
- */
447
- let SAFE_FOR_XML = true;
448
- /* Decide if document with <html>... should be returned */
449
- let WHOLE_DOCUMENT = false;
450
- /* Track whether config is already set on this instance of DOMPurify. */
451
- let SET_CONFIG = false;
452
- /* Decide if all elements (e.g. style, script) must be children of
453
- * document.body. By default, browsers might move them to document.head */
454
- let FORCE_BODY = false;
455
- /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
456
- * string (or a TrustedHTML object if Trusted Types are supported).
457
- * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
458
- */
459
- let RETURN_DOM = false;
460
- /* Decide if a DOM `DocumentFragment` should be returned, instead of a html
461
- * string (or a TrustedHTML object if Trusted Types are supported) */
462
- let RETURN_DOM_FRAGMENT = false;
463
- /* Try to return a Trusted Type object instead of a string, return a string in
464
- * case Trusted Types are not supported */
465
- let RETURN_TRUSTED_TYPE = false;
466
- /* Output should be free from DOM clobbering attacks?
467
- * This sanitizes markups named with colliding, clobberable built-in DOM APIs.
468
- */
469
- let SANITIZE_DOM = true;
470
- /* Achieve full DOM Clobbering protection by isolating the namespace of named
471
- * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.
89
+ * Creates a new function that constructs an instance of the given constructor function with the provided arguments.
472
90
  *
473
- * HTML/DOM spec rules that enable DOM Clobbering:
474
- * - Named Access on Window (§7.3.3)
475
- * - DOM Tree Accessors (§3.1.5)
476
- * - Form Element Parent-Child Relations (§4.10.3)
477
- * - Iframe srcdoc / Nested WindowProxies (§4.8.5)
478
- * - HTMLCollection (§4.2.10.2)
479
- *
480
- * Namespace isolation is implemented by prefixing `id` and `name` attributes
481
- * with a constant string, i.e., `user-content-`
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.
482
93
  */
483
- let SANITIZE_NAMED_PROPS = false;
484
- const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';
485
- /* Keep element content when removing element? */
486
- let KEEP_CONTENT = true;
487
- /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
488
- * of importing it into a new Document and returning a sanitized copy */
489
- let IN_PLACE = false;
490
- /* Allow usage of profiles like html, svg and mathMl */
491
- let USE_PROFILES = {};
492
- /* Tags to ignore content of when KEEP_CONTENT is true */
493
- let FORBID_CONTENTS = null;
494
- 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']);
495
- /* Tags that are safe for data: URIs */
496
- let DATA_URI_TAGS = null;
497
- const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
498
- /* Attributes safe for values like "javascript:" */
499
- let URI_SAFE_ATTRIBUTES = null;
500
- const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);
501
- const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
502
- const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
503
- const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
504
- /* Document namespace */
505
- let NAMESPACE = HTML_NAMESPACE;
506
- let IS_EMPTY_INPUT = false;
507
- /* Allowed XHTML+XML namespaces */
508
- let ALLOWED_NAMESPACES = null;
509
- const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
510
- let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
511
- let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);
512
- // Certain elements are allowed in both SVG and HTML
513
- // namespace. We need to specify them explicitly
514
- // so that they don't get erroneously deleted from
515
- // HTML namespace.
516
- const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
517
- /* Parsing of strict XHTML documents */
518
- let PARSER_MEDIA_TYPE = null;
519
- const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
520
- const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
521
- let transformCaseFunc = null;
522
- /* Keep a reference to config to pass to hooks */
523
- let CONFIG = null;
524
- /* Ideally, do not touch anything below this line */
525
- /* ______________________________________________ */
526
- const formElement = document.createElement('form');
527
- const isRegexOrFunction = function isRegexOrFunction(testValue) {
528
- return testValue instanceof RegExp || testValue instanceof Function;
529
- };
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
+ };
101
+ }
530
102
  /**
531
- * _parseConfig
103
+ * Add properties to a lookup table
532
104
  *
533
- * @param cfg optional config literal
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.
534
109
  */
535
- // eslint-disable-next-line complexity
536
- const _parseConfig = function _parseConfig() {
537
- let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
538
- if (CONFIG && CONFIG === cfg) {
539
- return;
540
- }
541
- /* Shield configuration object from tampering */
542
- if (!cfg || typeof cfg !== 'object') {
543
- cfg = {};
544
- }
545
- /* Shield configuration object from prototype pollution */
546
- cfg = clone(cfg);
547
- PARSER_MEDIA_TYPE =
548
- // eslint-disable-next-line unicorn/prefer-includes
549
- SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;
550
- // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
551
- transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
552
- /* Set configuration parameters */
553
- ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
554
- ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
555
- ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
556
- 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;
557
- 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;
558
- FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
559
- FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({});
560
- FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({});
561
- USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES : false;
562
- ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
563
- ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
564
- ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
565
- ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true
566
- SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
567
- SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true
568
- WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
569
- RETURN_DOM = cfg.RETURN_DOM || false; // Default false
570
- RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
571
- RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false
572
- FORCE_BODY = cfg.FORCE_BODY || false; // Default false
573
- SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
574
- SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
575
- KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
576
- IN_PLACE = cfg.IN_PLACE || false; // Default false
577
- IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI;
578
- NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
579
- MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS;
580
- HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS;
581
- CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || create(null);
582
- if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
583
- CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
584
- }
585
- if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
586
- CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
587
- }
588
- if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {
589
- CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
590
- }
591
- if (SAFE_FOR_TEMPLATES) {
592
- ALLOW_DATA_ATTR = false;
593
- }
594
- if (RETURN_DOM_FRAGMENT) {
595
- RETURN_DOM = true;
596
- }
597
- /* Parse profile info */
598
- if (USE_PROFILES) {
599
- ALLOWED_TAGS = addToSet({}, text);
600
- ALLOWED_ATTR = create(null);
601
- if (USE_PROFILES.html === true) {
602
- addToSet(ALLOWED_TAGS, html$1);
603
- addToSet(ALLOWED_ATTR, html);
604
- }
605
- if (USE_PROFILES.svg === true) {
606
- addToSet(ALLOWED_TAGS, svg$1);
607
- addToSet(ALLOWED_ATTR, svg);
608
- addToSet(ALLOWED_ATTR, xml);
609
- }
610
- if (USE_PROFILES.svgFilters === true) {
611
- addToSet(ALLOWED_TAGS, svgFilters);
612
- addToSet(ALLOWED_ATTR, svg);
613
- addToSet(ALLOWED_ATTR, xml);
614
- }
615
- if (USE_PROFILES.mathMl === true) {
616
- addToSet(ALLOWED_TAGS, mathMl$1);
617
- addToSet(ALLOWED_ATTR, mathMl);
618
- addToSet(ALLOWED_ATTR, xml);
619
- }
620
- }
621
- /* Always reset function-based ADD_TAGS / ADD_ATTR checks to prevent
622
- * leaking across calls when switching from function to array config */
623
- EXTRA_ELEMENT_HANDLING.tagCheck = null;
624
- EXTRA_ELEMENT_HANDLING.attributeCheck = null;
625
- /* Merge configuration parameters */
626
- if (cfg.ADD_TAGS) {
627
- if (typeof cfg.ADD_TAGS === 'function') {
628
- EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;
629
- } else {
630
- if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
631
- ALLOWED_TAGS = clone(ALLOWED_TAGS);
632
- }
633
- addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
634
- }
635
- }
636
- if (cfg.ADD_ATTR) {
637
- if (typeof cfg.ADD_ATTR === 'function') {
638
- EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;
639
- } else {
640
- if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
641
- ALLOWED_ATTR = clone(ALLOWED_ATTR);
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;
642
132
  }
643
- addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
644
- }
645
- }
646
- if (cfg.ADD_URI_SAFE_ATTR) {
647
- addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
648
- }
649
- if (cfg.FORBID_CONTENTS) {
650
- if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
651
- FORBID_CONTENTS = clone(FORBID_CONTENTS);
652
133
  }
653
- addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
654
- }
655
- if (cfg.ADD_FORBID_CONTENTS) {
656
- if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
657
- FORBID_CONTENTS = clone(FORBID_CONTENTS);
658
- }
659
- addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);
660
- }
661
- /* Add #text in case KEEP_CONTENT is set to true */
662
- if (KEEP_CONTENT) {
663
- ALLOWED_TAGS['#text'] = true;
134
+ set[element] = true;
664
135
  }
665
- /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
666
- if (WHOLE_DOCUMENT) {
667
- addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
668
- }
669
- /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */
670
- if (ALLOWED_TAGS.table) {
671
- addToSet(ALLOWED_TAGS, ['tbody']);
672
- delete FORBID_TAGS.tbody;
673
- }
674
- if (cfg.TRUSTED_TYPES_POLICY) {
675
- if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
676
- throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
677
- }
678
- if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
679
- throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
680
- }
681
- // Overwrite existing TrustedTypes policy.
682
- trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
683
- // Sign local variables required by `sanitize`.
684
- emptyHTML = trustedTypesPolicy.createHTML('');
685
- } else {
686
- // Uninitialized policy, attempt to initialize the internal dompurify policy.
687
- if (trustedTypesPolicy === undefined) {
688
- trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
689
- }
690
- // If creating the internal policy succeeded sign internal variables.
691
- if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {
692
- emptyHTML = trustedTypesPolicy.createHTML('');
693
- }
694
- }
695
- // Prevent further manipulation of configuration.
696
- // Not available in IE8, Safari 5, etc.
697
- if (freeze) {
698
- freeze(cfg);
699
- }
700
- CONFIG = cfg;
701
- };
702
- /* Keep track of all possible SVG and MathML tags
703
- * so that we can perform the namespace checks
704
- * correctly. */
705
- const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
706
- const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
136
+ return set;
137
+ }
707
138
  /**
708
- * @param element a DOM element whose namespace is being checked
709
- * @returns Return false if the element has a
710
- * namespace that a spec-compliant parser would never
711
- * return. Return true otherwise.
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
712
143
  */
713
- const _checkValidNamespace = function _checkValidNamespace(element) {
714
- let parent = getParentNode(element);
715
- // In JSDOM, if we're inside shadow DOM, then parentNode
716
- // can be null. We just simulate parent in this case.
717
- if (!parent || !parent.tagName) {
718
- parent = {
719
- namespaceURI: NAMESPACE,
720
- tagName: 'template'
721
- };
722
- }
723
- const tagName = stringToLowerCase(element.tagName);
724
- const parentTagName = stringToLowerCase(parent.tagName);
725
- if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
726
- return false;
727
- }
728
- if (element.namespaceURI === SVG_NAMESPACE) {
729
- // The only way to switch from HTML namespace to SVG
730
- // is via <svg>. If it happens via any other tag, then
731
- // it should be killed.
732
- if (parent.namespaceURI === HTML_NAMESPACE) {
733
- return tagName === 'svg';
734
- }
735
- // The only way to switch from MathML to SVG is via`
736
- // svg if parent is either <annotation-xml> or MathML
737
- // text integration points.
738
- if (parent.namespaceURI === MATHML_NAMESPACE) {
739
- return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
740
- }
741
- // We only allow elements that are defined in SVG
742
- // spec. All others are disallowed in SVG namespace.
743
- return Boolean(ALL_SVG_TAGS[tagName]);
744
- }
745
- if (element.namespaceURI === MATHML_NAMESPACE) {
746
- // The only way to switch from HTML namespace to MathML
747
- // is via <math>. If it happens via any other tag, then
748
- // it should be killed.
749
- if (parent.namespaceURI === HTML_NAMESPACE) {
750
- return tagName === 'math';
751
- }
752
- // The only way to switch from SVG to MathML is via
753
- // <math> and HTML integration points
754
- if (parent.namespaceURI === SVG_NAMESPACE) {
755
- return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
756
- }
757
- // We only allow elements that are defined in MathML
758
- // spec. All others are disallowed in MathML namespace.
759
- return Boolean(ALL_MATHML_TAGS[tagName]);
760
- }
761
- if (element.namespaceURI === HTML_NAMESPACE) {
762
- // The only way to switch from SVG to HTML is via
763
- // HTML integration points, and from MathML to HTML
764
- // is via MathML text integration points
765
- if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
766
- return false;
767
- }
768
- if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
769
- return false;
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;
770
149
  }
771
- // We disallow tags that are specific for MathML
772
- // or SVG and should never appear in HTML namespace
773
- return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
774
150
  }
775
- // For XHTML and XML documents that support custom namespaces
776
- if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
777
- return true;
778
- }
779
- // The code should never reach this place (this means
780
- // that the element somehow got namespace that is not
781
- // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).
782
- // Return false just in case.
783
- return false;
784
- };
151
+ return array;
152
+ }
785
153
  /**
786
- * _forceRemove
154
+ * Shallow clone an object
787
155
  *
788
- * @param node a DOM node
156
+ * @param object - The object to be cloned.
157
+ * @returns A new object that copies the original.
789
158
  */
790
- const _forceRemove = function _forceRemove(node) {
791
- arrayPush(DOMPurify.removed, {
792
- element: node
793
- });
794
- try {
795
- // eslint-disable-next-line unicorn/prefer-dom-node-remove
796
- getParentNode(node).removeChild(node);
797
- } catch (_) {
798
- remove(node);
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
+ }
799
172
  }
800
- };
173
+ return newObject;
174
+ }
801
175
  /**
802
- * _removeAttribute
176
+ * Convert non-node values into strings without depending on direct property access.
803
177
  *
804
- * @param name an Attribute name
805
- * @param element a DOM node
178
+ * @param value - The value to stringify.
179
+ * @returns A string representation of the provided value.
806
180
  */
807
- const _removeAttribute = function _removeAttribute(name, element) {
808
- try {
809
- arrayPush(DOMPurify.removed, {
810
- attribute: element.getAttributeNode(name),
811
- from: element
812
- });
813
- } catch (_) {
814
- arrayPush(DOMPurify.removed, {
815
- attribute: null,
816
- from: element
817
- });
818
- }
819
- element.removeAttribute(name);
820
- // We void attribute values for unremovable "is" attributes
821
- if (name === 'is') {
822
- if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
823
- try {
824
- _forceRemove(element);
825
- } catch (_) {}
826
- } else {
827
- try {
828
- element.setAttribute(name, '');
829
- } catch (_) {}
830
- }
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
+ }
831
225
  }
832
- };
226
+ }
833
227
  /**
834
- * _initDocument
228
+ * This method automatically checks if the prop is function or getter and behaves accordingly.
835
229
  *
836
- * @param dirty - a string of dirty markup
837
- * @return a DOM, filled with the dirty markup
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.
838
233
  */
839
- const _initDocument = function _initDocument(dirty) {
840
- /* Create a HTML document */
841
- let doc = null;
842
- let leadingWhitespace = null;
843
- if (FORCE_BODY) {
844
- dirty = '<remove></remove>' + dirty;
845
- } else {
846
- /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
847
- const matches = stringMatch(dirty, /^[\r\n\t ]+/);
848
- leadingWhitespace = matches && matches[0];
849
- }
850
- if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {
851
- // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
852
- dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
853
- }
854
- const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
855
- /*
856
- * Use the DOMParser API by default, fallback later if needs be
857
- * DOMParser not work for svg when has multiple root element.
858
- */
859
- if (NAMESPACE === HTML_NAMESPACE) {
860
- try {
861
- doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
862
- } catch (_) {}
863
- }
864
- /* Use createHTMLDocument in case DOMParser is not available */
865
- if (!doc || !doc.documentElement) {
866
- doc = implementation.createDocument(NAMESPACE, 'template', null);
867
- try {
868
- doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;
869
- } catch (_) {
870
- // Syntax error if dirtyPayload is invalid xml
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
+ }
871
244
  }
245
+ object = getPrototypeOf(object);
872
246
  }
873
- const body = doc.body || doc.documentElement;
874
- if (dirty && leadingWhitespace) {
875
- body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
247
+ function fallbackValue() {
248
+ return null;
876
249
  }
877
- /* Work on whole document or just its body */
878
- if (NAMESPACE === HTML_NAMESPACE) {
879
- return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
250
+ return fallbackValue;
251
+ }
252
+ function isRegex(value) {
253
+ try {
254
+ regExpTest(value, '');
255
+ return true;
256
+ } catch (_unused) {
257
+ return false;
880
258
  }
881
- return WHOLE_DOCUMENT ? doc.documentElement : body;
882
- };
883
- /**
884
- * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.
885
- *
886
- * @param root The root element or node to start traversing on.
887
- * @return The created NodeIterator
888
- */
889
- const _createNodeIterator = function _createNodeIterator(root) {
890
- return createNodeIterator.call(root.ownerDocument || root, root,
891
- // eslint-disable-next-line no-bitwise
892
- NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
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;
893
319
  };
894
320
  /**
895
- * _isClobbered
896
- *
897
- * @param element element to check for clobbering attacks
898
- * @return true if clobbered, false if safe
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).
899
327
  */
900
- const _isClobbered = function _isClobbered(element) {
901
- 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');
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;
356
+ }
902
357
  };
903
- /**
904
- * Checks whether the given object is a DOM node.
905
- *
906
- * @param value object to check whether it's a DOM node
907
- * @return true is object is a DOM node
908
- */
909
- const _isNode = function _isNode(value) {
910
- return typeof Node === 'function' && value instanceof Node;
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
+ };
911
370
  };
912
- function _executeHooks(hooks, currentNode, data) {
913
- arrayForEach(hooks, hook => {
914
- hook.call(DOMPurify, currentNode, data, CONFIG);
915
- });
916
- }
917
- /**
918
- * _sanitizeElements
919
- *
920
- * @protect nodeName
921
- * @protect textContent
922
- * @protect removeChild
923
- * @param currentNode to check for permission to exist
924
- * @return true if node was killed, false if left alive
925
- */
926
- const _sanitizeElements = function _sanitizeElements(currentNode) {
927
- let content = null;
928
- /* Execute a hook if present */
929
- _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
930
- /* Check if element is clobbered or can clobber */
931
- if (_isClobbered(currentNode)) {
932
- _forceRemove(currentNode);
933
- return true;
934
- }
935
- /* Now let's check the element's type and name */
936
- const tagName = transformCaseFunc(currentNode.nodeName);
937
- /* Execute a hook if present */
938
- _executeHooks(hooks.uponSanitizeElement, currentNode, {
939
- tagName,
940
- allowedTags: ALLOWED_TAGS
941
- });
942
- /* Detect mXSS attempts abusing namespace confusion */
943
- if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) {
944
- _forceRemove(currentNode);
945
- return true;
946
- }
947
- /* Remove risky CSS construction leading to mXSS */
948
- if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {
949
- _forceRemove(currentNode);
950
- return true;
951
- }
952
- /* Remove any occurrence of processing instructions */
953
- if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {
954
- _forceRemove(currentNode);
955
- return true;
956
- }
957
- /* Remove any kind of possibly harmful comments */
958
- if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) {
959
- _forceRemove(currentNode);
960
- return true;
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.2';
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;
414
+ }
961
415
  }
962
- /* Remove element if anything forbids its presence */
963
- if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) {
964
- /* Check if we have a custom element to handle */
965
- if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
966
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
967
- return false;
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);
968
674
  }
969
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
970
- return false;
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);
971
689
  }
972
690
  }
973
- /* Keep content except for bad-listed elements */
974
- if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
975
- const parentNode = getParentNode(currentNode) || currentNode.parentNode;
976
- const childNodes = getChildNodes(currentNode) || currentNode.childNodes;
977
- if (childNodes && parentNode) {
978
- const childCount = childNodes.length;
979
- for (let i = childCount - 1; i >= 0; --i) {
980
- const childClone = cloneNode(childNodes[i], true);
981
- childClone.__removalCount = (currentNode.__removalCount || 0) + 1;
982
- parentNode.insertBefore(childClone, getNextSibling(currentNode));
691
+ /* Always reset function-based ADD_TAGS / ADD_ATTR checks to prevent
692
+ * leaking across calls when switching from function to array config */
693
+ EXTRA_ELEMENT_HANDLING.tagCheck = null;
694
+ EXTRA_ELEMENT_HANDLING.attributeCheck = null;
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);
983
702
  }
703
+ addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
984
704
  }
985
705
  }
986
- _forceRemove(currentNode);
987
- return true;
988
- }
989
- /* Check whether element has a valid namespace */
990
- if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
991
- _forceRemove(currentNode);
992
- return true;
993
- }
994
- /* Make sure that older browsers don't get fallback-tag mXSS */
995
- if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {
996
- _forceRemove(currentNode);
997
- return true;
998
- }
999
- /* Sanitize element content to be template-safe */
1000
- if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
1001
- /* Get the element's text content */
1002
- content = currentNode.textContent;
1003
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1004
- content = stringReplace(content, expr, ' ');
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);
714
+ }
715
+ }
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);
718
+ }
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);
724
+ }
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`.
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
+ }
764
+ }
765
+ // Prevent further manipulation of configuration.
766
+ // Not available in IE8, Safari 5, etc.
767
+ if (freeze) {
768
+ freeze(cfg);
769
+ }
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]) {
796
+ return false;
797
+ }
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) {
861
+ arrayPush(DOMPurify.removed, {
862
+ element: node
1005
863
  });
1006
- if (currentNode.textContent !== content) {
864
+ try {
865
+ // eslint-disable-next-line unicorn/prefer-dom-node-remove
866
+ getParentNode(node).removeChild(node);
867
+ } catch (_) {
868
+ remove(node);
869
+ }
870
+ };
871
+ /**
872
+ * _removeAttribute
873
+ *
874
+ * @param name an Attribute name
875
+ * @param element a DOM node
876
+ */
877
+ const _removeAttribute = function _removeAttribute(name, element) {
878
+ try {
1007
879
  arrayPush(DOMPurify.removed, {
1008
- element: currentNode.cloneNode()
880
+ attribute: element.getAttributeNode(name),
881
+ from: element
882
+ });
883
+ } catch (_) {
884
+ arrayPush(DOMPurify.removed, {
885
+ attribute: null,
886
+ from: element
1009
887
  });
1010
- currentNode.textContent = content;
1011
888
  }
1012
- }
1013
- /* Execute a hook if present */
1014
- _executeHooks(hooks.afterSanitizeElements, currentNode, null);
1015
- return false;
1016
- };
1017
- /**
1018
- * _isValidAttribute
1019
- *
1020
- * @param lcTag Lowercase tag name of containing element.
1021
- * @param lcName Lowercase attribute name.
1022
- * @param value Attribute value.
1023
- * @return Returns true if `value` is valid, otherwise false.
1024
- */
1025
- // eslint-disable-next-line complexity
1026
- const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
1027
- /* FORBID_ATTR must always win, even if ADD_ATTR predicate would allow it */
1028
- if (FORBID_ATTR[lcName]) {
1029
- return false;
1030
- }
1031
- /* Make sure attribute cannot clobber */
1032
- if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
1033
- return false;
1034
- }
1035
- /* Allow valid data-* attributes: At least one character after "-"
1036
- (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
1037
- XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
1038
- We don't need to check the value; it's always URI safe. */
1039
- 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]) {
1040
- if (
1041
- // First condition does a very basic check if a) it's basically a valid custom element tagname AND
1042
- // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1043
- // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
1044
- _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)) ||
1045
- // Alternative, second condition checks if it's an `is`-attribute, AND
1046
- // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1047
- 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 {
1048
- 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 (_) {}
900
+ }
1049
901
  }
1050
- /* Check value is safe. First, is attr inert? If so, is safe */
1051
- } 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) {
1052
- return false;
1053
- } else ;
1054
- return true;
1055
- };
1056
- /**
1057
- * _isBasicCustomElement
1058
- * checks if at least one dash is included in tagName, and it's not the first char
1059
- * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name
1060
- *
1061
- * @param tagName name of the tag of the node to sanitize
1062
- * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.
1063
- */
1064
- const _isBasicCustomElement = function _isBasicCustomElement(tagName) {
1065
- return tagName !== 'annotation-xml' && stringMatch(tagName, CUSTOM_ELEMENT);
1066
- };
1067
- /**
1068
- * _sanitizeAttributes
1069
- *
1070
- * @protect attributes
1071
- * @protect nodeName
1072
- * @protect removeAttribute
1073
- * @protect setAttribute
1074
- *
1075
- * @param currentNode to sanitize
1076
- */
1077
- const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
1078
- /* Execute a hook if present */
1079
- _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);
1080
- const {
1081
- attributes
1082
- } = currentNode;
1083
- /* Check if we have attributes; if not we might have a text node */
1084
- if (!attributes || _isClobbered(currentNode)) {
1085
- return;
1086
- }
1087
- const hookEvent = {
1088
- attrName: '',
1089
- attrValue: '',
1090
- keepAttr: true,
1091
- allowedAttributes: ALLOWED_ATTR,
1092
- forceKeepAttr: undefined
1093
902
  };
1094
- let l = attributes.length;
1095
- /* Go backwards over all attributes; safely remove bad ones */
1096
- while (l--) {
1097
- const attr = attributes[l];
1098
- const {
1099
- name,
1100
- namespaceURI,
1101
- value: attrValue
1102
- } = attr;
1103
- const lcName = transformCaseFunc(name);
1104
- const initValue = attrValue;
1105
- let value = name === 'value' ? initValue : stringTrim(initValue);
1106
- /* Execute a hook if present */
1107
- hookEvent.attrName = lcName;
1108
- hookEvent.attrValue = value;
1109
- hookEvent.keepAttr = true;
1110
- hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
1111
- _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);
1112
- value = hookEvent.attrValue;
1113
- /* Full DOM Clobbering protection via namespace isolation,
1114
- * Prefix id and name attributes with `user-content-`
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.
1115
928
  */
1116
- if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {
1117
- // Remove the attribute with this value
1118
- _removeAttribute(name, currentNode);
1119
- // Prefix the value and later re-create the attribute with the sanitized value
1120
- value = SANITIZE_NAMED_PROPS_PREFIX + value;
1121
- }
1122
- /* Work around a security issue with comments inside attributes */
1123
- if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {
1124
- _removeAttribute(name, currentNode);
1125
- continue;
1126
- }
1127
- /* Make sure we cannot easily use animated hrefs, even if animations are allowed */
1128
- if (lcName === 'attributename' && stringMatch(value, 'href')) {
1129
- _removeAttribute(name, currentNode);
1130
- continue;
1131
- }
1132
- /* Did the hooks approve of the attribute? */
1133
- if (hookEvent.forceKeepAttr) {
1134
- continue;
1135
- }
1136
- /* Did the hooks approve of the attribute? */
1137
- if (!hookEvent.keepAttr) {
1138
- _removeAttribute(name, currentNode);
1139
- continue;
1140
- }
1141
- /* Work around a security issue in jQuery 3.0 */
1142
- if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
1143
- _removeAttribute(name, currentNode);
1144
- continue;
1145
- }
1146
- /* Sanitize attribute content to be template-safe */
1147
- if (SAFE_FOR_TEMPLATES) {
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
941
+ }
942
+ }
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
+ });
986
+ }
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
1011
+ });
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;
1148
1072
  arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1149
- value = stringReplace(value, expr, ' ');
1073
+ content = stringReplace(content, expr, ' ');
1150
1074
  });
1075
+ if (currentNode.textContent !== content) {
1076
+ arrayPush(DOMPurify.removed, {
1077
+ element: currentNode.cloneNode()
1078
+ });
1079
+ currentNode.textContent = content;
1080
+ }
1151
1081
  }
1152
- /* Is `value` valid for this attribute? */
1153
- const lcTag = transformCaseFunc(currentNode.nodeName);
1154
- if (!_isValidAttribute(lcTag, lcName, value)) {
1155
- _removeAttribute(name, currentNode);
1156
- continue;
1157
- }
1158
- /* Handle attributes that require Trusted Types */
1159
- if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {
1160
- if (namespaceURI) ; else {
1161
- switch (trustedTypes.getAttributeType(lcTag, lcName)) {
1162
- case 'TrustedHTML':
1163
- {
1164
- value = trustedTypesPolicy.createHTML(value);
1165
- break;
1166
- }
1167
- case 'TrustedScriptURL':
1168
- {
1169
- value = trustedTypesPolicy.createScriptURL(value);
1170
- break;
1171
- }
1172
- }
1082
+ /* Execute a hook if present */
1083
+ _executeHooks(hooks.afterSanitizeElements, currentNode, null);
1084
+ return false;
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]) {
1098
+ return false;
1099
+ }
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
+ const nameIsPermitted = ALLOWED_ATTR[lcName] || EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag);
1105
+ /* Allow valid data-* attributes: At least one character after "-"
1106
+ (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
1107
+ XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
1108
+ We don't need to check the value; it's always URI safe. */
1109
+ if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) ; else if (!nameIsPermitted || FORBID_ATTR[lcName]) {
1110
+ if (
1111
+ // First condition does a very basic check if a) it's basically a valid custom element tagname AND
1112
+ // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1113
+ // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
1114
+ _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)) ||
1115
+ // Alternative, second condition checks if it's an `is`-attribute, AND
1116
+ // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1117
+ 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 {
1118
+ return false;
1173
1119
  }
1120
+ /* Check value is safe. First, is attr inert? If so, is safe */
1121
+ } 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) {
1122
+ return false;
1123
+ } else ;
1124
+ return true;
1125
+ };
1126
+ /* Names the HTML spec reserves from valid-custom-element-name; these must
1127
+ * never be treated as basic custom elements even when a permissive
1128
+ * CUSTOM_ELEMENT_HANDLING.tagNameCheck is configured. */
1129
+ 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']);
1130
+ /**
1131
+ * _isBasicCustomElement
1132
+ * checks if at least one dash is included in tagName, and it's not the first char
1133
+ * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name
1134
+ *
1135
+ * @param tagName name of the tag of the node to sanitize
1136
+ * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.
1137
+ */
1138
+ const _isBasicCustomElement = function _isBasicCustomElement(tagName) {
1139
+ return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT, tagName);
1140
+ };
1141
+ /**
1142
+ * _sanitizeAttributes
1143
+ *
1144
+ * @protect attributes
1145
+ * @protect nodeName
1146
+ * @protect removeAttribute
1147
+ * @protect setAttribute
1148
+ *
1149
+ * @param currentNode to sanitize
1150
+ */
1151
+ const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
1152
+ /* Execute a hook if present */
1153
+ _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);
1154
+ const {
1155
+ attributes
1156
+ } = currentNode;
1157
+ /* Check if we have attributes; if not we might have a text node */
1158
+ if (!attributes || _isClobbered(currentNode)) {
1159
+ return;
1174
1160
  }
1175
- /* Handle invalid data-* attribute set by try-catching it */
1176
- if (value !== initValue) {
1177
- try {
1178
- if (namespaceURI) {
1179
- currentNode.setAttributeNS(namespaceURI, name, value);
1180
- } else {
1181
- /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
1182
- currentNode.setAttribute(name, value);
1161
+ const hookEvent = {
1162
+ attrName: '',
1163
+ attrValue: '',
1164
+ keepAttr: true,
1165
+ allowedAttributes: ALLOWED_ATTR,
1166
+ forceKeepAttr: undefined
1167
+ };
1168
+ let l = attributes.length;
1169
+ /* Go backwards over all attributes; safely remove bad ones */
1170
+ while (l--) {
1171
+ const attr = attributes[l];
1172
+ const {
1173
+ name,
1174
+ namespaceURI,
1175
+ value: attrValue
1176
+ } = attr;
1177
+ const lcName = transformCaseFunc(name);
1178
+ const initValue = attrValue;
1179
+ let value = name === 'value' ? initValue : stringTrim(initValue);
1180
+ /* Execute a hook if present */
1181
+ hookEvent.attrName = lcName;
1182
+ hookEvent.attrValue = value;
1183
+ hookEvent.keepAttr = true;
1184
+ hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
1185
+ _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);
1186
+ value = hookEvent.attrValue;
1187
+ /* Full DOM Clobbering protection via namespace isolation,
1188
+ * Prefix id and name attributes with `user-content-`
1189
+ */
1190
+ if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name') && stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0) {
1191
+ // Remove the attribute with this value
1192
+ _removeAttribute(name, currentNode);
1193
+ // Prefix the value and later re-create the attribute with the sanitized value
1194
+ value = SANITIZE_NAMED_PROPS_PREFIX + value;
1195
+ }
1196
+ // Else: already prefixed, leave the attribute alone — the prefix is
1197
+ // itself the clobbering protection, and re-applying it is incorrect.
1198
+ /* Work around a security issue with comments inside attributes */
1199
+ if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {
1200
+ _removeAttribute(name, currentNode);
1201
+ continue;
1202
+ }
1203
+ /* Make sure we cannot easily use animated hrefs, even if animations are allowed */
1204
+ if (lcName === 'attributename' && stringMatch(value, 'href')) {
1205
+ _removeAttribute(name, currentNode);
1206
+ continue;
1207
+ }
1208
+ /* Did the hooks approve of the attribute? */
1209
+ if (hookEvent.forceKeepAttr) {
1210
+ continue;
1211
+ }
1212
+ /* Did the hooks approve of the attribute? */
1213
+ if (!hookEvent.keepAttr) {
1214
+ _removeAttribute(name, currentNode);
1215
+ continue;
1216
+ }
1217
+ /* Work around a security issue in jQuery 3.0 */
1218
+ if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
1219
+ _removeAttribute(name, currentNode);
1220
+ continue;
1221
+ }
1222
+ /* Sanitize attribute content to be template-safe */
1223
+ if (SAFE_FOR_TEMPLATES) {
1224
+ arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1225
+ value = stringReplace(value, expr, ' ');
1226
+ });
1227
+ }
1228
+ /* Is `value` valid for this attribute? */
1229
+ const lcTag = transformCaseFunc(currentNode.nodeName);
1230
+ if (!_isValidAttribute(lcTag, lcName, value)) {
1231
+ _removeAttribute(name, currentNode);
1232
+ continue;
1233
+ }
1234
+ /* Handle attributes that require Trusted Types */
1235
+ if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {
1236
+ if (namespaceURI) ; else {
1237
+ switch (trustedTypes.getAttributeType(lcTag, lcName)) {
1238
+ case 'TrustedHTML':
1239
+ {
1240
+ value = trustedTypesPolicy.createHTML(value);
1241
+ break;
1242
+ }
1243
+ case 'TrustedScriptURL':
1244
+ {
1245
+ value = trustedTypesPolicy.createScriptURL(value);
1246
+ break;
1247
+ }
1248
+ }
1183
1249
  }
1184
- if (_isClobbered(currentNode)) {
1185
- _forceRemove(currentNode);
1186
- } else {
1187
- arrayPop(DOMPurify.removed);
1250
+ }
1251
+ /* Handle invalid data-* attribute set by try-catching it */
1252
+ if (value !== initValue) {
1253
+ try {
1254
+ if (namespaceURI) {
1255
+ currentNode.setAttributeNS(namespaceURI, name, value);
1256
+ } else {
1257
+ /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
1258
+ currentNode.setAttribute(name, value);
1259
+ }
1260
+ if (_isClobbered(currentNode)) {
1261
+ _forceRemove(currentNode);
1262
+ } else {
1263
+ arrayPop(DOMPurify.removed);
1264
+ }
1265
+ } catch (_) {
1266
+ _removeAttribute(name, currentNode);
1188
1267
  }
1189
- } catch (_) {
1190
- _removeAttribute(name, currentNode);
1191
1268
  }
1192
1269
  }
1193
- }
1194
- /* Execute a hook if present */
1195
- _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);
1196
- };
1197
- /**
1198
- * _sanitizeShadowDOM
1199
- *
1200
- * @param fragment to iterate over recursively
1201
- */
1202
- const _sanitizeShadowDOM2 = function _sanitizeShadowDOM(fragment) {
1203
- let shadowNode = null;
1204
- const shadowIterator = _createNodeIterator(fragment);
1205
- /* Execute a hook if present */
1206
- _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);
1207
- while (shadowNode = shadowIterator.nextNode()) {
1208
1270
  /* Execute a hook if present */
1209
- _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);
1210
- /* Sanitize tags and elements */
1211
- _sanitizeElements(shadowNode);
1212
- /* Check attributes next */
1213
- _sanitizeAttributes(shadowNode);
1214
- /* Deep shadow DOM detected */
1215
- if (shadowNode.content instanceof DocumentFragment) {
1216
- _sanitizeShadowDOM2(shadowNode.content);
1271
+ _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);
1272
+ };
1273
+ /**
1274
+ * _sanitizeShadowDOM
1275
+ *
1276
+ * @param fragment to iterate over recursively
1277
+ */
1278
+ const _sanitizeShadowDOM2 = function _sanitizeShadowDOM(fragment) {
1279
+ let shadowNode = null;
1280
+ const shadowIterator = _createNodeIterator(fragment);
1281
+ /* Execute a hook if present */
1282
+ _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);
1283
+ while (shadowNode = shadowIterator.nextNode()) {
1284
+ /* Execute a hook if present */
1285
+ _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);
1286
+ /* Sanitize tags and elements */
1287
+ _sanitizeElements(shadowNode);
1288
+ /* Check attributes next */
1289
+ _sanitizeAttributes(shadowNode);
1290
+ /* Deep shadow DOM detected */
1291
+ if (shadowNode.content instanceof DocumentFragment) {
1292
+ _sanitizeShadowDOM2(shadowNode.content);
1293
+ }
1217
1294
  }
1218
- }
1219
- /* Execute a hook if present */
1220
- _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
1221
- };
1222
- // eslint-disable-next-line complexity
1223
- DOMPurify.sanitize = function (dirty) {
1224
- let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1225
- let body = null;
1226
- let importedNode = null;
1227
- let currentNode = null;
1228
- let returnNode = null;
1229
- /* Make sure we have a string to sanitize.
1230
- DO NOT return early, as this will return the wrong type if
1231
- the user has requested a DOM object rather than a string */
1232
- IS_EMPTY_INPUT = !dirty;
1233
- if (IS_EMPTY_INPUT) {
1234
- dirty = '<!-->';
1235
- }
1236
- /* Stringify, in case dirty is an object */
1237
- if (typeof dirty !== 'string' && !_isNode(dirty)) {
1238
- if (typeof dirty.toString === 'function') {
1239
- dirty = dirty.toString();
1295
+ /* Execute a hook if present */
1296
+ _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
1297
+ };
1298
+ // eslint-disable-next-line complexity
1299
+ DOMPurify.sanitize = function (dirty) {
1300
+ let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1301
+ let body = null;
1302
+ let importedNode = null;
1303
+ let currentNode = null;
1304
+ let returnNode = null;
1305
+ /* Make sure we have a string to sanitize.
1306
+ DO NOT return early, as this will return the wrong type if
1307
+ the user has requested a DOM object rather than a string */
1308
+ IS_EMPTY_INPUT = !dirty;
1309
+ if (IS_EMPTY_INPUT) {
1310
+ dirty = '<!-->';
1311
+ }
1312
+ /* Stringify, in case dirty is an object */
1313
+ if (typeof dirty !== 'string' && !_isNode(dirty)) {
1314
+ dirty = stringifyValue(dirty);
1240
1315
  if (typeof dirty !== 'string') {
1241
1316
  throw typeErrorCreate('dirty is not a string, aborting');
1242
1317
  }
1243
- } else {
1244
- throw typeErrorCreate('toString is not a function');
1245
1318
  }
1246
- }
1247
- /* Return dirty HTML if DOMPurify cannot run */
1248
- if (!DOMPurify.isSupported) {
1249
- return dirty;
1250
- }
1251
- /* Assign config vars */
1252
- if (!SET_CONFIG) {
1253
- _parseConfig(cfg);
1254
- }
1255
- /* Clean up removed elements */
1256
- DOMPurify.removed = [];
1257
- /* Check if dirty is correctly typed for IN_PLACE */
1258
- if (typeof dirty === 'string') {
1259
- IN_PLACE = false;
1260
- }
1261
- if (IN_PLACE) {
1262
- /* Do some early pre-sanitization to avoid unsafe root nodes */
1263
- if (dirty.nodeName) {
1264
- const tagName = transformCaseFunc(dirty.nodeName);
1265
- if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
1266
- throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
1267
- }
1319
+ /* Return dirty HTML if DOMPurify cannot run */
1320
+ if (!DOMPurify.isSupported) {
1321
+ return dirty;
1268
1322
  }
1269
- } else if (dirty instanceof Node) {
1270
- /* If dirty is a DOM element, append to an empty document to avoid
1271
- elements being stripped by the parser */
1272
- body = _initDocument('<!---->');
1273
- importedNode = body.ownerDocument.importNode(dirty, true);
1274
- if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') {
1275
- /* Node is already a body, use as is */
1276
- body = importedNode;
1277
- } else if (importedNode.nodeName === 'HTML') {
1278
- body = importedNode;
1323
+ /* Assign config vars */
1324
+ if (!SET_CONFIG) {
1325
+ _parseConfig(cfg);
1326
+ }
1327
+ /* Clean up removed elements */
1328
+ DOMPurify.removed = [];
1329
+ /* Check if dirty is correctly typed for IN_PLACE */
1330
+ if (typeof dirty === 'string') {
1331
+ IN_PLACE = false;
1332
+ }
1333
+ if (IN_PLACE) {
1334
+ /* Do some early pre-sanitization to avoid unsafe root nodes */
1335
+ const nn = dirty.nodeName;
1336
+ if (typeof nn === 'string') {
1337
+ const tagName = transformCaseFunc(nn);
1338
+ if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
1339
+ throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
1340
+ }
1341
+ }
1342
+ } else if (dirty instanceof Node) {
1343
+ /* If dirty is a DOM element, append to an empty document to avoid
1344
+ elements being stripped by the parser */
1345
+ body = _initDocument('<!---->');
1346
+ importedNode = body.ownerDocument.importNode(dirty, true);
1347
+ if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') {
1348
+ /* Node is already a body, use as is */
1349
+ body = importedNode;
1350
+ } else if (importedNode.nodeName === 'HTML') {
1351
+ body = importedNode;
1352
+ } else {
1353
+ // eslint-disable-next-line unicorn/prefer-dom-node-append
1354
+ body.appendChild(importedNode);
1355
+ }
1279
1356
  } else {
1280
- // eslint-disable-next-line unicorn/prefer-dom-node-append
1281
- body.appendChild(importedNode);
1357
+ /* Exit directly if we have nothing to do */
1358
+ if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
1359
+ // eslint-disable-next-line unicorn/prefer-includes
1360
+ dirty.indexOf('<') === -1) {
1361
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
1362
+ }
1363
+ /* Initialize the document to work on */
1364
+ body = _initDocument(dirty);
1365
+ /* Check we have a DOM node from the data */
1366
+ if (!body) {
1367
+ return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
1368
+ }
1282
1369
  }
1283
- } else {
1284
- /* Exit directly if we have nothing to do */
1285
- if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
1286
- // eslint-disable-next-line unicorn/prefer-includes
1287
- dirty.indexOf('<') === -1) {
1288
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
1370
+ /* Remove first element node (ours) if FORCE_BODY is set */
1371
+ if (body && FORCE_BODY) {
1372
+ _forceRemove(body.firstChild);
1289
1373
  }
1290
- /* Initialize the document to work on */
1291
- body = _initDocument(dirty);
1292
- /* Check we have a DOM node from the data */
1293
- if (!body) {
1294
- return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
1374
+ /* Get node iterator */
1375
+ const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);
1376
+ /* Now start iterating over the created document */
1377
+ while (currentNode = nodeIterator.nextNode()) {
1378
+ /* Sanitize tags and elements */
1379
+ _sanitizeElements(currentNode);
1380
+ /* Check attributes next */
1381
+ _sanitizeAttributes(currentNode);
1382
+ /* Shadow DOM detected, sanitize it */
1383
+ if (currentNode.content instanceof DocumentFragment) {
1384
+ _sanitizeShadowDOM2(currentNode.content);
1385
+ }
1295
1386
  }
1296
- }
1297
- /* Remove first element node (ours) if FORCE_BODY is set */
1298
- if (body && FORCE_BODY) {
1299
- _forceRemove(body.firstChild);
1300
- }
1301
- /* Get node iterator */
1302
- const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);
1303
- /* Now start iterating over the created document */
1304
- while (currentNode = nodeIterator.nextNode()) {
1305
- /* Sanitize tags and elements */
1306
- _sanitizeElements(currentNode);
1307
- /* Check attributes next */
1308
- _sanitizeAttributes(currentNode);
1309
- /* Shadow DOM detected, sanitize it */
1310
- if (currentNode.content instanceof DocumentFragment) {
1311
- _sanitizeShadowDOM2(currentNode.content);
1387
+ /* If we sanitized `dirty` in-place, return it. */
1388
+ if (IN_PLACE) {
1389
+ return dirty;
1312
1390
  }
1313
- }
1314
- /* If we sanitized `dirty` in-place, return it. */
1315
- if (IN_PLACE) {
1316
- return dirty;
1317
- }
1318
- /* Return sanitized string or DOM */
1319
- if (RETURN_DOM) {
1391
+ /* Return sanitized string or DOM */
1392
+ if (RETURN_DOM) {
1393
+ if (SAFE_FOR_TEMPLATES) {
1394
+ body.normalize();
1395
+ let html = body.innerHTML;
1396
+ arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1397
+ html = stringReplace(html, expr, ' ');
1398
+ });
1399
+ body.innerHTML = html;
1400
+ }
1401
+ if (RETURN_DOM_FRAGMENT) {
1402
+ returnNode = createDocumentFragment.call(body.ownerDocument);
1403
+ while (body.firstChild) {
1404
+ // eslint-disable-next-line unicorn/prefer-dom-node-append
1405
+ returnNode.appendChild(body.firstChild);
1406
+ }
1407
+ } else {
1408
+ returnNode = body;
1409
+ }
1410
+ if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {
1411
+ /*
1412
+ AdoptNode() is not used because internal state is not reset
1413
+ (e.g. the past names map of a HTMLFormElement), this is safe
1414
+ in theory but we would rather not risk another attack vector.
1415
+ The state that is cloned by importNode() is explicitly defined
1416
+ by the specs.
1417
+ */
1418
+ returnNode = importNode.call(originalDocument, returnNode, true);
1419
+ }
1420
+ return returnNode;
1421
+ }
1422
+ let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
1423
+ /* Serialize doctype if allowed */
1424
+ if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
1425
+ serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
1426
+ }
1427
+ /* Sanitize final string template-safe */
1320
1428
  if (SAFE_FOR_TEMPLATES) {
1321
- body.normalize();
1322
- let html = body.innerHTML;
1323
1429
  arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1324
- html = stringReplace(html, expr, ' ');
1430
+ serializedHTML = stringReplace(serializedHTML, expr, ' ');
1325
1431
  });
1326
- body.innerHTML = html;
1327
1432
  }
1328
- if (RETURN_DOM_FRAGMENT) {
1329
- returnNode = createDocumentFragment.call(body.ownerDocument);
1330
- while (body.firstChild) {
1331
- // eslint-disable-next-line unicorn/prefer-dom-node-append
1332
- returnNode.appendChild(body.firstChild);
1333
- }
1334
- } else {
1335
- returnNode = body;
1336
- }
1337
- if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {
1338
- /*
1339
- AdoptNode() is not used because internal state is not reset
1340
- (e.g. the past names map of a HTMLFormElement), this is safe
1341
- in theory but we would rather not risk another attack vector.
1342
- The state that is cloned by importNode() is explicitly defined
1343
- by the specs.
1344
- */
1345
- returnNode = importNode.call(originalDocument, returnNode, true);
1346
- }
1347
- return returnNode;
1348
- }
1349
- let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
1350
- /* Serialize doctype if allowed */
1351
- if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
1352
- serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
1353
- }
1354
- /* Sanitize final string template-safe */
1355
- if (SAFE_FOR_TEMPLATES) {
1356
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1357
- serializedHTML = stringReplace(serializedHTML, expr, ' ');
1358
- });
1359
- }
1360
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
1361
- };
1362
- DOMPurify.setConfig = function () {
1363
- let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1364
- _parseConfig(cfg);
1365
- SET_CONFIG = true;
1366
- };
1367
- DOMPurify.clearConfig = function () {
1368
- CONFIG = null;
1369
- SET_CONFIG = false;
1370
- };
1371
- DOMPurify.isValidAttribute = function (tag, attr, value) {
1372
- /* Initialize shared config vars if necessary. */
1373
- if (!CONFIG) {
1374
- _parseConfig({});
1375
- }
1376
- const lcTag = transformCaseFunc(tag);
1377
- const lcName = transformCaseFunc(attr);
1378
- return _isValidAttribute(lcTag, lcName, value);
1379
- };
1380
- DOMPurify.addHook = function (entryPoint, hookFunction) {
1381
- if (typeof hookFunction !== 'function') {
1382
- return;
1383
- }
1384
- arrayPush(hooks[entryPoint], hookFunction);
1385
- };
1386
- DOMPurify.removeHook = function (entryPoint, hookFunction) {
1387
- if (hookFunction !== undefined) {
1388
- const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);
1389
- return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];
1390
- }
1391
- return arrayPop(hooks[entryPoint]);
1392
- };
1393
- DOMPurify.removeHooks = function (entryPoint) {
1394
- hooks[entryPoint] = [];
1395
- };
1396
- DOMPurify.removeAllHooks = function () {
1397
- hooks = _createHooksMap();
1398
- };
1399
- return DOMPurify;
1400
- }
1401
- var purify = createDOMPurify();
1433
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
1434
+ };
1435
+ DOMPurify.setConfig = function () {
1436
+ let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1437
+ _parseConfig(cfg);
1438
+ SET_CONFIG = true;
1439
+ };
1440
+ DOMPurify.clearConfig = function () {
1441
+ CONFIG = null;
1442
+ SET_CONFIG = false;
1443
+ };
1444
+ DOMPurify.isValidAttribute = function (tag, attr, value) {
1445
+ /* Initialize shared config vars if necessary. */
1446
+ if (!CONFIG) {
1447
+ _parseConfig({});
1448
+ }
1449
+ const lcTag = transformCaseFunc(tag);
1450
+ const lcName = transformCaseFunc(attr);
1451
+ return _isValidAttribute(lcTag, lcName, value);
1452
+ };
1453
+ DOMPurify.addHook = function (entryPoint, hookFunction) {
1454
+ if (typeof hookFunction !== 'function') {
1455
+ return;
1456
+ }
1457
+ arrayPush(hooks[entryPoint], hookFunction);
1458
+ };
1459
+ DOMPurify.removeHook = function (entryPoint, hookFunction) {
1460
+ if (hookFunction !== undefined) {
1461
+ const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);
1462
+ return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];
1463
+ }
1464
+ return arrayPop(hooks[entryPoint]);
1465
+ };
1466
+ DOMPurify.removeHooks = function (entryPoint) {
1467
+ hooks[entryPoint] = [];
1468
+ };
1469
+ DOMPurify.removeAllHooks = function () {
1470
+ hooks = _createHooksMap();
1471
+ };
1472
+ return DOMPurify;
1473
+ }
1474
+ var purify = createDOMPurify();
1402
1475
 
1403
- return purify;
1476
+ return purify;
1404
1477
 
1405
1478
  }));
1406
1479
  //# sourceMappingURL=purify.js.map