@vaadin/bundles 24.10.3 → 24.10.5

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.
@@ -6,29 +6,70 @@
6
6
  \***********************************************/
7
7
  /***/ (function(module) {
8
8
 
9
- /*! @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 */
9
+ /*! @license DOMPurify 3.4.11 | (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.11/LICENSE */
10
10
 
11
11
  (function (global, factory) {
12
12
  true ? module.exports = factory() :
13
13
  0;
14
14
  })(this, (function () { 'use strict';
15
15
 
16
- const {
17
- entries,
18
- setPrototypeOf,
19
- isFrozen,
20
- getPrototypeOf,
21
- getOwnPropertyDescriptor
22
- } = Object;
23
- let {
24
- freeze,
25
- seal,
26
- create
27
- } = Object; // eslint-disable-line import/no-mutable-exports
28
- let {
29
- apply,
30
- construct
31
- } = typeof Reflect !== 'undefined' && Reflect;
16
+ function _arrayLikeToArray(r, a) {
17
+ (null == a || a > r.length) && (a = r.length);
18
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
19
+ return n;
20
+ }
21
+ function _arrayWithHoles(r) {
22
+ if (Array.isArray(r)) return r;
23
+ }
24
+ function _iterableToArrayLimit(r, l) {
25
+ var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
26
+ if (null != t) {
27
+ var e,
28
+ n,
29
+ i,
30
+ u,
31
+ a = [],
32
+ f = true,
33
+ o = false;
34
+ try {
35
+ if (i = (t = t.call(r)).next, 0 === l) ; else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
36
+ } catch (r) {
37
+ o = true, n = r;
38
+ } finally {
39
+ try {
40
+ if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
41
+ } finally {
42
+ if (o) throw n;
43
+ }
44
+ }
45
+ return a;
46
+ }
47
+ }
48
+ function _nonIterableRest() {
49
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
50
+ }
51
+ function _slicedToArray(r, e) {
52
+ return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
53
+ }
54
+ function _unsupportedIterableToArray(r, a) {
55
+ if (r) {
56
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
57
+ var t = {}.toString.call(r).slice(8, -1);
58
+ return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
59
+ }
60
+ }
61
+
62
+ const entries = Object.entries,
63
+ setPrototypeOf = Object.setPrototypeOf,
64
+ isFrozen = Object.isFrozen,
65
+ getPrototypeOf = Object.getPrototypeOf,
66
+ getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
67
+ let freeze = Object.freeze,
68
+ seal = Object.seal,
69
+ create = Object.create; // eslint-disable-line import/no-mutable-exports
70
+ let _ref = typeof Reflect !== 'undefined' && Reflect,
71
+ apply = _ref.apply,
72
+ construct = _ref.construct;
32
73
  if (!freeze) {
33
74
  freeze = function freeze(x) {
34
75
  return x;
@@ -60,13 +101,19 @@
60
101
  const arrayPop = unapply(Array.prototype.pop);
61
102
  const arrayPush = unapply(Array.prototype.push);
62
103
  const arraySplice = unapply(Array.prototype.splice);
104
+ const arrayIsArray = Array.isArray;
63
105
  const stringToLowerCase = unapply(String.prototype.toLowerCase);
64
106
  const stringToString = unapply(String.prototype.toString);
65
107
  const stringMatch = unapply(String.prototype.match);
66
108
  const stringReplace = unapply(String.prototype.replace);
67
109
  const stringIndexOf = unapply(String.prototype.indexOf);
68
110
  const stringTrim = unapply(String.prototype.trim);
111
+ const numberToString = unapply(Number.prototype.toString);
112
+ const booleanToString = unapply(Boolean.prototype.toString);
113
+ const bigintToString = typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString);
114
+ const symbolToString = typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString);
69
115
  const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);
116
+ const objectToString = unapply(Object.prototype.toString);
70
117
  const regExpTest = unapply(RegExp.prototype.test);
71
118
  const typeErrorCreate = unconstruct(TypeError);
72
119
  /**
@@ -116,6 +163,9 @@
116
163
  // Prevent prototype setters from intercepting set as a this value.
117
164
  setPrototypeOf(set, null);
118
165
  }
166
+ if (!arrayIsArray(array)) {
167
+ return set;
168
+ }
119
169
  let l = array.length;
120
170
  while (l--) {
121
171
  let element = array[l];
@@ -156,10 +206,13 @@
156
206
  */
157
207
  function clone(object) {
158
208
  const newObject = create(null);
159
- for (const [property, value] of entries(object)) {
209
+ for (const _ref2 of entries(object)) {
210
+ var _ref3 = _slicedToArray(_ref2, 2);
211
+ const property = _ref3[0];
212
+ const value = _ref3[1];
160
213
  const isPropertyExist = objectHasOwnProperty(object, property);
161
214
  if (isPropertyExist) {
162
- if (Array.isArray(value)) {
215
+ if (arrayIsArray(value)) {
163
216
  newObject[property] = cleanArray(value);
164
217
  } else if (value && typeof value === 'object' && value.constructor === Object) {
165
218
  newObject[property] = clone(value);
@@ -170,6 +223,58 @@
170
223
  }
171
224
  return newObject;
172
225
  }
226
+ /**
227
+ * Convert non-node values into strings without depending on direct property access.
228
+ *
229
+ * @param value - The value to stringify.
230
+ * @returns A string representation of the provided value.
231
+ */
232
+ function stringifyValue(value) {
233
+ switch (typeof value) {
234
+ case 'string':
235
+ {
236
+ return value;
237
+ }
238
+ case 'number':
239
+ {
240
+ return numberToString(value);
241
+ }
242
+ case 'boolean':
243
+ {
244
+ return booleanToString(value);
245
+ }
246
+ case 'bigint':
247
+ {
248
+ return bigintToString ? bigintToString(value) : '0';
249
+ }
250
+ case 'symbol':
251
+ {
252
+ return symbolToString ? symbolToString(value) : 'Symbol()';
253
+ }
254
+ case 'undefined':
255
+ {
256
+ return objectToString(value);
257
+ }
258
+ case 'function':
259
+ case 'object':
260
+ {
261
+ if (value === null) {
262
+ return objectToString(value);
263
+ }
264
+ const valueAsRecord = value;
265
+ const valueToString = lookupGetter(valueAsRecord, 'toString');
266
+ if (typeof valueToString === 'function') {
267
+ const stringified = valueToString(valueAsRecord);
268
+ return typeof stringified === 'string' ? stringified : objectToString(stringified);
269
+ }
270
+ return objectToString(value);
271
+ }
272
+ default:
273
+ {
274
+ return objectToString(value);
275
+ }
276
+ }
277
+ }
173
278
  /**
174
279
  * This method automatically checks if the prop is function or getter and behaves accordingly.
175
280
  *
@@ -195,6 +300,14 @@
195
300
  }
196
301
  return fallbackValue;
197
302
  }
303
+ function isRegex(value) {
304
+ try {
305
+ regExpTest(value, '');
306
+ return true;
307
+ } catch (_unused) {
308
+ return false;
309
+ }
310
+ }
198
311
 
199
312
  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']);
200
313
  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']);
@@ -210,15 +323,14 @@
210
323
  const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
211
324
  const text = freeze(['#text']);
212
325
 
213
- 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']);
326
+ const html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'command', 'commandfor', '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']);
214
327
  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']);
215
328
  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']);
216
329
  const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
217
330
 
218
- // eslint-disable-next-line unicorn/better-regex
219
- const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode
220
- const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
221
- const TMPLIT_EXPR = seal(/\$\{[\w\W]*/gm); // eslint-disable-line unicorn/better-regex
331
+ const MUSTACHE_EXPR = seal(/{{[\w\W]*|^[\w\W]*}}/g);
332
+ const ERB_EXPR = seal(/<%[\w\W]*|^[\w\W]*%>/g);
333
+ const TMPLIT_EXPR = seal(/\${[\w\W]*/g);
222
334
  const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape
223
335
  const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
224
336
  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
@@ -228,30 +340,31 @@
228
340
  );
229
341
  const DOCTYPE_NAME = seal(/^html$/i);
230
342
  const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);
343
+ // Markup-significant character probes used by _sanitizeElements.
344
+ // Shared module-level instances are safe despite the sticky /g flags:
345
+ // unapply() resets lastIndex for RegExp receivers before every call.
346
+ const ELEMENT_MARKUP_PROBE = seal(/<[/\w!]/g);
347
+ const COMMENT_MARKUP_PROBE = seal(/<[/\w]/g);
348
+ const FALLBACK_TAG_CLOSE = seal(/<\/no(script|embed|frames)/i);
349
+ const SELF_CLOSING_TAG = seal(/\/>/i);
231
350
 
232
- var EXPRESSIONS = /*#__PURE__*/Object.freeze({
233
- __proto__: null,
234
- ARIA_ATTR: ARIA_ATTR,
235
- ATTR_WHITESPACE: ATTR_WHITESPACE,
236
- CUSTOM_ELEMENT: CUSTOM_ELEMENT,
237
- DATA_ATTR: DATA_ATTR,
238
- DOCTYPE_NAME: DOCTYPE_NAME,
239
- ERB_EXPR: ERB_EXPR,
240
- IS_ALLOWED_URI: IS_ALLOWED_URI,
241
- IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA,
242
- MUSTACHE_EXPR: MUSTACHE_EXPR,
243
- TMPLIT_EXPR: TMPLIT_EXPR
244
- });
245
-
246
- /* eslint-disable @typescript-eslint/indent */
247
351
  // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
248
352
  const NODE_TYPE = {
249
353
  element: 1,
354
+ attribute: 2,
250
355
  text: 3,
356
+ cdataSection: 4,
357
+ entityReference: 5,
251
358
  // Deprecated
252
- progressingInstruction: 7,
359
+ entityNode: 6,
360
+ // Deprecated
361
+ processingInstruction: 7,
253
362
  comment: 8,
254
- document: 9};
363
+ document: 9,
364
+ documentType: 10,
365
+ documentFragment: 11,
366
+ notation: 12 // Deprecated
367
+ };
255
368
  const getGlobal = function getGlobal() {
256
369
  return typeof window === 'undefined' ? null : window;
257
370
  };
@@ -306,10 +419,25 @@
306
419
  uponSanitizeShadowNode: []
307
420
  };
308
421
  };
422
+ /**
423
+ * Resolve a set-valued configuration option: a fresh set built from
424
+ * cfg[key] when it is an own array property (seeded with a clone of
425
+ * options.base when given, case-normalized via options.transform),
426
+ * the fallback set otherwise.
427
+ *
428
+ * @param cfg the cloned, prototype-free configuration object
429
+ * @param key the configuration property to read
430
+ * @param fallback the set to use when the option is absent or not an array
431
+ * @param options transform and optional base set to merge into
432
+ * @returns the resolved set
433
+ */
434
+ const _resolveSetOption = function _resolveSetOption(cfg, key, fallback, options) {
435
+ return objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key]) ? addToSet(options.base ? clone(options.base) : {}, cfg[key], options.transform) : fallback;
436
+ };
309
437
  function createDOMPurify() {
310
438
  let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
311
439
  const DOMPurify = root => createDOMPurify(root);
312
- DOMPurify.version = '3.4.0';
440
+ DOMPurify.version = '3.4.11';
313
441
  DOMPurify.removed = [];
314
442
  if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {
315
443
  // Not running in a browser, provide a factory function
@@ -317,28 +445,29 @@
317
445
  DOMPurify.isSupported = false;
318
446
  return DOMPurify;
319
447
  }
320
- let {
321
- document
322
- } = window;
448
+ let document = window.document;
323
449
  const originalDocument = document;
324
450
  const currentScript = originalDocument.currentScript;
325
- const {
326
- DocumentFragment,
327
- HTMLTemplateElement,
328
- Node,
329
- Element,
330
- NodeFilter,
331
- NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap,
332
- HTMLFormElement,
333
- DOMParser,
334
- trustedTypes
335
- } = window;
451
+ window.DocumentFragment;
452
+ const HTMLTemplateElement = window.HTMLTemplateElement,
453
+ Node = window.Node,
454
+ Element = window.Element,
455
+ NodeFilter = window.NodeFilter,
456
+ _window$NamedNodeMap = window.NamedNodeMap;
457
+ _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap;
458
+ window.HTMLFormElement;
459
+ const DOMParser = window.DOMParser,
460
+ trustedTypes = window.trustedTypes;
336
461
  const ElementPrototype = Element.prototype;
337
462
  const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
338
463
  const remove = lookupGetter(ElementPrototype, 'remove');
339
464
  const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
340
465
  const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
341
466
  const getParentNode = lookupGetter(ElementPrototype, 'parentNode');
467
+ const getShadowRoot = lookupGetter(ElementPrototype, 'shadowRoot');
468
+ const getAttributes = lookupGetter(ElementPrototype, 'attributes');
469
+ const getNodeType = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeType') : null;
470
+ const getNodeName = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeName') : null;
342
471
  // As per issue #47, the web-components registry is inherited by a
343
472
  // new document created via createHTMLDocument. As per the spec
344
473
  // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
@@ -353,33 +482,74 @@
353
482
  }
354
483
  let trustedTypesPolicy;
355
484
  let emptyHTML = '';
356
- const {
357
- implementation,
358
- createNodeIterator,
359
- createDocumentFragment,
360
- getElementsByTagName
361
- } = document;
362
- const {
363
- importNode
364
- } = originalDocument;
485
+ // The instance's own internal Trusted Types policy. Unlike a caller-supplied
486
+ // `TRUSTED_TYPES_POLICY`, this is created at most once — Trusted Types throws
487
+ // on duplicate policy names — and is the only policy allowed to persist
488
+ // across configurations and survive `clearConfig()`.
489
+ let defaultTrustedTypesPolicy;
490
+ let defaultTrustedTypesPolicyResolved = false;
491
+ // Tracks whether we are already inside a call to the configured Trusted Types
492
+ // policy (`createHTML` or `createScriptURL`). If a supplied policy callback
493
+ // itself calls `DOMPurify.sanitize` (the cause of #1422), `sanitize` would
494
+ // re-enter the policy and recurse until the stack overflows. We detect that
495
+ // re-entry and throw a clear, actionable error instead. The guard is shared
496
+ // across both callbacks, because either one re-entering `sanitize` triggers
497
+ // the same unbounded recursion.
498
+ let IN_TRUSTED_TYPES_POLICY = 0;
499
+ const _assertNotInTrustedTypesPolicy = function _assertNotInTrustedTypesPolicy() {
500
+ if (IN_TRUSTED_TYPES_POLICY > 0) {
501
+ throw typeErrorCreate('A configured TRUSTED_TYPES_POLICY callback (createHTML or ' + 'createScriptURL) must not call DOMPurify.sanitize, as that causes ' + 'infinite recursion. Do not pass a policy whose callbacks wrap ' + 'DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted ' + 'Types" section of the README.');
502
+ }
503
+ };
504
+ const _createTrustedHTML = function _createTrustedHTML(html) {
505
+ _assertNotInTrustedTypesPolicy();
506
+ IN_TRUSTED_TYPES_POLICY++;
507
+ try {
508
+ return trustedTypesPolicy.createHTML(html);
509
+ } finally {
510
+ IN_TRUSTED_TYPES_POLICY--;
511
+ }
512
+ };
513
+ const _createTrustedScriptURL = function _createTrustedScriptURL(scriptUrl) {
514
+ _assertNotInTrustedTypesPolicy();
515
+ IN_TRUSTED_TYPES_POLICY++;
516
+ try {
517
+ return trustedTypesPolicy.createScriptURL(scriptUrl);
518
+ } finally {
519
+ IN_TRUSTED_TYPES_POLICY--;
520
+ }
521
+ };
522
+ // Lazily resolve (and cache) the instance's internal default policy.
523
+ // Resolution is attempted at most once: a successful `createPolicy` cannot be
524
+ // repeated (Trusted Types throws on duplicate names), and a failed or
525
+ // unsupported attempt must not be retried on every parse.
526
+ const _getDefaultTrustedTypesPolicy = function _getDefaultTrustedTypesPolicy() {
527
+ if (!defaultTrustedTypesPolicyResolved) {
528
+ defaultTrustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
529
+ defaultTrustedTypesPolicyResolved = true;
530
+ }
531
+ return defaultTrustedTypesPolicy;
532
+ };
533
+ const _document = document,
534
+ implementation = _document.implementation,
535
+ createNodeIterator = _document.createNodeIterator,
536
+ createDocumentFragment = _document.createDocumentFragment,
537
+ getElementsByTagName = _document.getElementsByTagName;
538
+ const importNode = originalDocument.importNode;
365
539
  let hooks = _createHooksMap();
366
540
  /**
367
541
  * Expose whether this browser supports running the full DOMPurify.
368
542
  */
369
543
  DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;
370
- const {
371
- MUSTACHE_EXPR,
372
- ERB_EXPR,
373
- TMPLIT_EXPR,
374
- DATA_ATTR,
375
- ARIA_ATTR,
376
- IS_SCRIPT_OR_DATA,
377
- ATTR_WHITESPACE,
378
- CUSTOM_ELEMENT
379
- } = EXPRESSIONS;
380
- let {
381
- IS_ALLOWED_URI: IS_ALLOWED_URI$1
382
- } = EXPRESSIONS;
544
+ const MUSTACHE_EXPR$1 = MUSTACHE_EXPR,
545
+ ERB_EXPR$1 = ERB_EXPR,
546
+ TMPLIT_EXPR$1 = TMPLIT_EXPR,
547
+ DATA_ATTR$1 = DATA_ATTR,
548
+ ARIA_ATTR$1 = ARIA_ATTR,
549
+ IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA,
550
+ ATTR_WHITESPACE$1 = ATTR_WHITESPACE,
551
+ CUSTOM_ELEMENT$1 = CUSTOM_ELEMENT;
552
+ let IS_ALLOWED_URI$1 = IS_ALLOWED_URI;
383
553
  /**
384
554
  * We consider the elements and attributes below to be safe. Ideally
385
555
  * don't add any new ones but feel free to remove unwanted ones.
@@ -456,6 +626,13 @@
456
626
  let WHOLE_DOCUMENT = false;
457
627
  /* Track whether config is already set on this instance of DOMPurify. */
458
628
  let SET_CONFIG = false;
629
+ /* Pristine allowlist bindings captured at setConfig() time. On the
630
+ * persistent-config path sanitize() restores the sets from these before
631
+ * the per-walk hook clone-guard, so a hook's in-call widening cannot
632
+ * carry across calls. Null until setConfig() is called; reset by
633
+ * clearConfig(). */
634
+ let SET_CONFIG_ALLOWED_TAGS = null;
635
+ let SET_CONFIG_ALLOWED_ATTR = null;
459
636
  /* Decide if all elements (e.g. style, script) must be children of
460
637
  * document.body. By default, browsers might move them to document.head */
461
638
  let FORCE_BODY = false;
@@ -498,7 +675,17 @@
498
675
  let USE_PROFILES = {};
499
676
  /* Tags to ignore content of when KEEP_CONTENT is true */
500
677
  let FORBID_CONTENTS = null;
501
- 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']);
678
+ const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script',
679
+ // <selectedcontent> mirrors the selected <option>'s subtree, cloned by
680
+ // the UA (customizable <select>) — including any on* handlers — and the
681
+ // engine re-mirrors synchronously whenever a removal changes which
682
+ // option/selectedcontent is current, even inside DOMPurify's inert
683
+ // DOMParser document. Hoisting its children on removal re-inserts a fresh
684
+ // mirror target ahead of the walk, which the engine refills, looping
685
+ // forever (DoS) and amplifying output. Dropping its content on removal
686
+ // (rather than hoisting) breaks that cascade; the content is a duplicate
687
+ // of the option, which is sanitized on its own. See campaign-3 F1/F6.
688
+ 'selectedcontent', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
502
689
  /* Tags that are safe for data: URIs */
503
690
  let DATA_URI_TAGS = null;
504
691
  const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
@@ -514,8 +701,10 @@
514
701
  /* Allowed XHTML+XML namespaces */
515
702
  let ALLOWED_NAMESPACES = null;
516
703
  const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
517
- let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
518
- let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);
704
+ const DEFAULT_MATHML_TEXT_INTEGRATION_POINTS = freeze(['mi', 'mo', 'mn', 'ms', 'mtext']);
705
+ let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS);
706
+ const DEFAULT_HTML_INTEGRATION_POINTS = freeze(['annotation-xml']);
707
+ let HTML_INTEGRATION_POINTS = addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS);
519
708
  // Certain elements are allowed in both SVG and HTML
520
709
  // namespace. We need to specify them explicitly
521
710
  // so that they don't get erroneously deleted from
@@ -557,15 +746,33 @@
557
746
  // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
558
747
  transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
559
748
  /* Set configuration parameters */
560
- ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
561
- ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
562
- ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
563
- 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;
564
- 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;
565
- FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
566
- FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({});
567
- FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({});
568
- USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES : false;
749
+ ALLOWED_TAGS = _resolveSetOption(cfg, 'ALLOWED_TAGS', DEFAULT_ALLOWED_TAGS, {
750
+ transform: transformCaseFunc
751
+ });
752
+ ALLOWED_ATTR = _resolveSetOption(cfg, 'ALLOWED_ATTR', DEFAULT_ALLOWED_ATTR, {
753
+ transform: transformCaseFunc
754
+ });
755
+ ALLOWED_NAMESPACES = _resolveSetOption(cfg, 'ALLOWED_NAMESPACES', DEFAULT_ALLOWED_NAMESPACES, {
756
+ transform: stringToString
757
+ });
758
+ URI_SAFE_ATTRIBUTES = _resolveSetOption(cfg, 'ADD_URI_SAFE_ATTR', DEFAULT_URI_SAFE_ATTRIBUTES, {
759
+ transform: transformCaseFunc,
760
+ base: DEFAULT_URI_SAFE_ATTRIBUTES
761
+ });
762
+ DATA_URI_TAGS = _resolveSetOption(cfg, 'ADD_DATA_URI_TAGS', DEFAULT_DATA_URI_TAGS, {
763
+ transform: transformCaseFunc,
764
+ base: DEFAULT_DATA_URI_TAGS
765
+ });
766
+ FORBID_CONTENTS = _resolveSetOption(cfg, 'FORBID_CONTENTS', DEFAULT_FORBID_CONTENTS, {
767
+ transform: transformCaseFunc
768
+ });
769
+ FORBID_TAGS = _resolveSetOption(cfg, 'FORBID_TAGS', clone({}), {
770
+ transform: transformCaseFunc
771
+ });
772
+ FORBID_ATTR = _resolveSetOption(cfg, 'FORBID_ATTR', clone({}), {
773
+ transform: transformCaseFunc
774
+ });
775
+ USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;
569
776
  ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
570
777
  ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
571
778
  ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
@@ -581,20 +788,22 @@
581
788
  SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
582
789
  KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
583
790
  IN_PLACE = cfg.IN_PLACE || false; // Default false
584
- IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI;
585
- NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
586
- MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS;
587
- HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS;
588
- CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || create(null);
589
- if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
590
- CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
591
- }
592
- if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
593
- CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
594
- }
595
- if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {
596
- CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
597
- }
791
+ IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp
792
+ NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace
793
+ 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({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS); // Default built-in map
794
+ HTML_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'HTML_INTEGRATION_POINTS') && cfg.HTML_INTEGRATION_POINTS && typeof cfg.HTML_INTEGRATION_POINTS === 'object' ? clone(cfg.HTML_INTEGRATION_POINTS) : addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS); // Default built-in map
795
+ const customElementHandling = objectHasOwnProperty(cfg, 'CUSTOM_ELEMENT_HANDLING') && cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING === 'object' ? clone(cfg.CUSTOM_ELEMENT_HANDLING) : create(null);
796
+ CUSTOM_ELEMENT_HANDLING = create(null);
797
+ if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) {
798
+ CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined
799
+ }
800
+ if (objectHasOwnProperty(customElementHandling, 'attributeNameCheck') && isRegexOrFunction(customElementHandling.attributeNameCheck)) {
801
+ CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck; // Default undefined
802
+ }
803
+ if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') {
804
+ CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined
805
+ }
806
+ seal(CUSTOM_ELEMENT_HANDLING);
598
807
  if (SAFE_FOR_TEMPLATES) {
599
808
  ALLOW_DATA_ATTR = false;
600
809
  }
@@ -630,36 +839,36 @@
630
839
  EXTRA_ELEMENT_HANDLING.tagCheck = null;
631
840
  EXTRA_ELEMENT_HANDLING.attributeCheck = null;
632
841
  /* Merge configuration parameters */
633
- if (cfg.ADD_TAGS) {
842
+ if (objectHasOwnProperty(cfg, 'ADD_TAGS')) {
634
843
  if (typeof cfg.ADD_TAGS === 'function') {
635
844
  EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;
636
- } else {
845
+ } else if (arrayIsArray(cfg.ADD_TAGS)) {
637
846
  if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
638
847
  ALLOWED_TAGS = clone(ALLOWED_TAGS);
639
848
  }
640
849
  addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
641
850
  }
642
851
  }
643
- if (cfg.ADD_ATTR) {
852
+ if (objectHasOwnProperty(cfg, 'ADD_ATTR')) {
644
853
  if (typeof cfg.ADD_ATTR === 'function') {
645
854
  EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;
646
- } else {
855
+ } else if (arrayIsArray(cfg.ADD_ATTR)) {
647
856
  if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
648
857
  ALLOWED_ATTR = clone(ALLOWED_ATTR);
649
858
  }
650
859
  addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
651
860
  }
652
861
  }
653
- if (cfg.ADD_URI_SAFE_ATTR) {
862
+ if (objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR)) {
654
863
  addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
655
864
  }
656
- if (cfg.FORBID_CONTENTS) {
865
+ if (objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS)) {
657
866
  if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
658
867
  FORBID_CONTENTS = clone(FORBID_CONTENTS);
659
868
  }
660
869
  addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
661
870
  }
662
- if (cfg.ADD_FORBID_CONTENTS) {
871
+ if (objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) {
663
872
  if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
664
873
  FORBID_CONTENTS = clone(FORBID_CONTENTS);
665
874
  }
@@ -678,6 +887,13 @@
678
887
  addToSet(ALLOWED_TAGS, ['tbody']);
679
888
  delete FORBID_TAGS.tbody;
680
889
  }
890
+ // Re-derive the active Trusted Types policy from this configuration on
891
+ // every parse. The active policy must never be sticky closure state that
892
+ // outlives the config that set it: a caller-supplied policy left in place
893
+ // after `clearConfig()` — or after a later call that supplied none, or
894
+ // `TRUSTED_TYPES_POLICY: null` — could sign a subsequent "default"
895
+ // `RETURN_TRUSTED_TYPE` result with a foreign, possibly unsafe policy.
896
+ // See GHSA-vxr8-fq34-vvx9.
681
897
  if (cfg.TRUSTED_TYPES_POLICY) {
682
898
  if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
683
899
  throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
@@ -685,18 +901,45 @@
685
901
  if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
686
902
  throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
687
903
  }
688
- // Overwrite existing TrustedTypes policy.
904
+ // A caller-supplied policy applies to this configuration only.
905
+ const previousTrustedTypesPolicy = trustedTypesPolicy;
689
906
  trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
690
- // Sign local variables required by `sanitize`.
691
- emptyHTML = trustedTypesPolicy.createHTML('');
907
+ // Sign local variables required by `sanitize`. If the supplied policy's
908
+ // `createHTML` is circular (i.e. it calls `DOMPurify.sanitize`), this
909
+ // throws via the re-entrancy guard. Restore the previous policy first so
910
+ // the instance is not left in a poisoned state. See #1422.
911
+ try {
912
+ emptyHTML = _createTrustedHTML('');
913
+ } catch (error) {
914
+ trustedTypesPolicy = previousTrustedTypesPolicy;
915
+ throw error;
916
+ }
917
+ } else if (cfg.TRUSTED_TYPES_POLICY === null) {
918
+ // Explicit opt-out for this call: perform no Trusted Types signing and
919
+ // create nothing (so a strict `trusted-types` CSP that disallows a
920
+ // `dompurify` policy can still call `sanitize` from inside its own
921
+ // policy — see #1422). Resetting to `undefined` rather than a sticky
922
+ // `null` also drops any previously retained caller policy, so it cannot
923
+ // resurface on a later call, while still allowing the next config-less
924
+ // call to restore the internal default policy. See GHSA-vxr8-fq34-vvx9.
925
+ trustedTypesPolicy = undefined;
926
+ emptyHTML = '';
692
927
  } else {
693
- // Uninitialized policy, attempt to initialize the internal dompurify policy.
928
+ // No policy supplied: keep the currently active policy if one is set — a
929
+ // previously supplied policy is intentionally sticky across config-less
930
+ // calls — otherwise fall back to the instance's own internal policy,
931
+ // created at most once. (A policy supplied for a *single* call still
932
+ // lingers by design; what must not linger is a policy whose configuration
933
+ // has been torn down via `clearConfig()`, which restores the default.)
694
934
  if (trustedTypesPolicy === undefined) {
695
- trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
935
+ trustedTypesPolicy = _getDefaultTrustedTypesPolicy();
696
936
  }
697
- // If creating the internal policy succeeded sign internal variables.
698
- if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {
699
- emptyHTML = trustedTypesPolicy.createHTML('');
937
+ // Sign internal variables only when a policy is active. A falsy policy
938
+ // (Trusted Types unsupported, creation failed, or an explicit opt-out)
939
+ // leaves `emptyHTML` as a plain string, so we never call `.createHTML` on
940
+ // a non-policy and throw. See #1422.
941
+ if (trustedTypesPolicy && typeof emptyHTML === 'string') {
942
+ emptyHTML = _createTrustedHTML('');
700
943
  }
701
944
  }
702
945
  // Prevent further manipulation of configuration.
@@ -711,6 +954,77 @@
711
954
  * correctly. */
712
955
  const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
713
956
  const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
957
+ /**
958
+ * Namespace rules for an element in the SVG namespace.
959
+ *
960
+ * @param tagName the element's lowercase tag name
961
+ * @param parent the (possibly simulated) parent node
962
+ * @param parentTagName the parent's lowercase tag name
963
+ * @returns true if a spec-compliant parser could produce this element
964
+ */
965
+ const _checkSvgNamespace = function _checkSvgNamespace(tagName, parent, parentTagName) {
966
+ // The only way to switch from HTML namespace to SVG
967
+ // is via <svg>. If it happens via any other tag, then
968
+ // it should be killed.
969
+ if (parent.namespaceURI === HTML_NAMESPACE) {
970
+ return tagName === 'svg';
971
+ }
972
+ // The only way to switch from MathML to SVG is via <svg>
973
+ // if the parent is either <annotation-xml> or a MathML
974
+ // text integration point.
975
+ if (parent.namespaceURI === MATHML_NAMESPACE) {
976
+ return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
977
+ }
978
+ // We only allow elements that are defined in SVG
979
+ // spec. All others are disallowed in SVG namespace.
980
+ return Boolean(ALL_SVG_TAGS[tagName]);
981
+ };
982
+ /**
983
+ * Namespace rules for an element in the MathML namespace.
984
+ *
985
+ * @param tagName the element's lowercase tag name
986
+ * @param parent the (possibly simulated) parent node
987
+ * @param parentTagName the parent's lowercase tag name
988
+ * @returns true if a spec-compliant parser could produce this element
989
+ */
990
+ const _checkMathMlNamespace = function _checkMathMlNamespace(tagName, parent, parentTagName) {
991
+ // The only way to switch from HTML namespace to MathML
992
+ // is via <math>. If it happens via any other tag, then
993
+ // it should be killed.
994
+ if (parent.namespaceURI === HTML_NAMESPACE) {
995
+ return tagName === 'math';
996
+ }
997
+ // The only way to switch from SVG to MathML is via
998
+ // <math> and HTML integration points
999
+ if (parent.namespaceURI === SVG_NAMESPACE) {
1000
+ return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
1001
+ }
1002
+ // We only allow elements that are defined in MathML
1003
+ // spec. All others are disallowed in MathML namespace.
1004
+ return Boolean(ALL_MATHML_TAGS[tagName]);
1005
+ };
1006
+ /**
1007
+ * Namespace rules for an element in the HTML namespace.
1008
+ *
1009
+ * @param tagName the element's lowercase tag name
1010
+ * @param parent the (possibly simulated) parent node
1011
+ * @param parentTagName the parent's lowercase tag name
1012
+ * @returns true if a spec-compliant parser could produce this element
1013
+ */
1014
+ const _checkHtmlNamespace = function _checkHtmlNamespace(tagName, parent, parentTagName) {
1015
+ // The only way to switch from SVG to HTML is via
1016
+ // HTML integration points, and from MathML to HTML
1017
+ // is via MathML text integration points
1018
+ if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
1019
+ return false;
1020
+ }
1021
+ if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
1022
+ return false;
1023
+ }
1024
+ // We disallow tags that are specific for MathML
1025
+ // or SVG and should never appear in HTML namespace
1026
+ return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
1027
+ };
714
1028
  /**
715
1029
  * @param element a DOM element whose namespace is being checked
716
1030
  * @returns Return false if the element has a
@@ -733,51 +1047,13 @@
733
1047
  return false;
734
1048
  }
735
1049
  if (element.namespaceURI === SVG_NAMESPACE) {
736
- // The only way to switch from HTML namespace to SVG
737
- // is via <svg>. If it happens via any other tag, then
738
- // it should be killed.
739
- if (parent.namespaceURI === HTML_NAMESPACE) {
740
- return tagName === 'svg';
741
- }
742
- // The only way to switch from MathML to SVG is via`
743
- // svg if parent is either <annotation-xml> or MathML
744
- // text integration points.
745
- if (parent.namespaceURI === MATHML_NAMESPACE) {
746
- return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
747
- }
748
- // We only allow elements that are defined in SVG
749
- // spec. All others are disallowed in SVG namespace.
750
- return Boolean(ALL_SVG_TAGS[tagName]);
1050
+ return _checkSvgNamespace(tagName, parent, parentTagName);
751
1051
  }
752
1052
  if (element.namespaceURI === MATHML_NAMESPACE) {
753
- // The only way to switch from HTML namespace to MathML
754
- // is via <math>. If it happens via any other tag, then
755
- // it should be killed.
756
- if (parent.namespaceURI === HTML_NAMESPACE) {
757
- return tagName === 'math';
758
- }
759
- // The only way to switch from SVG to MathML is via
760
- // <math> and HTML integration points
761
- if (parent.namespaceURI === SVG_NAMESPACE) {
762
- return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
763
- }
764
- // We only allow elements that are defined in MathML
765
- // spec. All others are disallowed in MathML namespace.
766
- return Boolean(ALL_MATHML_TAGS[tagName]);
1053
+ return _checkMathMlNamespace(tagName, parent, parentTagName);
767
1054
  }
768
1055
  if (element.namespaceURI === HTML_NAMESPACE) {
769
- // The only way to switch from SVG to HTML is via
770
- // HTML integration points, and from MathML to HTML
771
- // is via MathML text integration points
772
- if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
773
- return false;
774
- }
775
- if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
776
- return false;
777
- }
778
- // We disallow tags that are specific for MathML
779
- // or SVG and should never appear in HTML namespace
780
- return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
1056
+ return _checkHtmlNamespace(tagName, parent, parentTagName);
781
1057
  }
782
1058
  // For XHTML and XML documents that support custom namespaces
783
1059
  if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
@@ -802,7 +1078,74 @@
802
1078
  // eslint-disable-next-line unicorn/prefer-dom-node-remove
803
1079
  getParentNode(node).removeChild(node);
804
1080
  } catch (_) {
1081
+ /* The normal detach failed — this is reached for a parentless node
1082
+ (getParentNode() is null, so .removeChild throws). Element.prototype
1083
+ .remove() is itself a spec no-op on a parentless node, so a recorded
1084
+ "removal" would otherwise hand the caller back an intact,
1085
+ payload-bearing node (e.g. a detached IN_PLACE root the mXSS canary or
1086
+ the style-with-element-child rule decided to kill). Fail closed by
1087
+ throwing — exactly as a clobbered root does at the IN_PLACE entry —
1088
+ rather than trying to "neutralize" the node via its own methods.
1089
+ Neutralizing would mean calling getAttributeNames()/removeAttribute()
1090
+ on the node, both of which a <form> root can clobber via a named child
1091
+ (and _isClobbered does not even probe getAttributeNames), so the
1092
+ neutralize step could itself be silently defeated, leaving the payload
1093
+ intact. A throw touches only the cached, clobber-safe remove() and
1094
+ getParentNode(). Generalizes GHSA-r47g-fvhr-h676 (clobbered-form root)
1095
+ to every root-kill reason. REPORT-3.
1096
+ This lives inside the catch, so it never fires for a normally-removed
1097
+ in-tree node: those have a parent, removeChild() succeeds, and the
1098
+ catch is not entered. Only a kept (parentless) root reaches here. */
805
1099
  remove(node);
1100
+ if (!getParentNode(node)) {
1101
+ throw typeErrorCreate('a node selected for removal could not be detached from its tree ' + 'and cannot be safely returned; refusing to sanitize in place');
1102
+ }
1103
+ }
1104
+ };
1105
+ /**
1106
+ * _neutralizeRoot
1107
+ *
1108
+ * Fail-closed teardown of an in-place root after the sanitize walk aborts
1109
+ * (campaign-3 F2). An internal throw mid-walk — e.g. a page-registered
1110
+ * custom element's reaction detaches a node so `_forceRemove`'s deliberate
1111
+ * parentless guard throws, or any other re-entrant engine mutation — would
1112
+ * otherwise leave the caller's *live* tree half-sanitized, with everything
1113
+ * after the abort point still carrying its handlers. There is no safe way
1114
+ * to resume the walk (the tree mutated under us), so we strip the root bare:
1115
+ * remove every child and every attribute, then let the caller's catch see
1116
+ * the original error. Clobber-safe (cached `remove`/`childNodes`/`attributes`
1117
+ * getters; the root was already clobber-pre-flighted at the IN_PLACE entry).
1118
+ *
1119
+ * @param root the in-place root to empty
1120
+ */
1121
+ const _neutralizeRoot = function _neutralizeRoot(root) {
1122
+ const childNodes = getChildNodes(root);
1123
+ if (childNodes) {
1124
+ const snapshot = [];
1125
+ arrayForEach(childNodes, child => {
1126
+ arrayPush(snapshot, child);
1127
+ });
1128
+ arrayForEach(snapshot, child => {
1129
+ try {
1130
+ remove(child);
1131
+ } catch (_) {
1132
+ /* Best-effort teardown; a still-attached child is handled below */
1133
+ }
1134
+ });
1135
+ }
1136
+ const attributes = getAttributes(root);
1137
+ if (attributes) {
1138
+ for (let i = attributes.length - 1; i >= 0; --i) {
1139
+ const attribute = attributes[i];
1140
+ const name = attribute && attribute.name;
1141
+ if (typeof name === 'string') {
1142
+ try {
1143
+ root.removeAttribute(name);
1144
+ } catch (_) {
1145
+ /* Clobbered removeAttribute — ignore (fail-closed best effort) */
1146
+ }
1147
+ }
1148
+ }
806
1149
  }
807
1150
  };
808
1151
  /**
@@ -837,6 +1180,72 @@
837
1180
  }
838
1181
  }
839
1182
  };
1183
+ /**
1184
+ * _stripDisallowedAttributes
1185
+ *
1186
+ * Removes every attribute the active configuration does not allow from a
1187
+ * single element, using the same allowlist as the main attribute pass (so
1188
+ * `on*` handlers go, but no `/^on/` blocklist is introduced). Used only to
1189
+ * neutralise nodes that are being discarded from an in-place tree.
1190
+ *
1191
+ * @param element the element to strip
1192
+ */
1193
+ const _stripDisallowedAttributes = function _stripDisallowedAttributes(element) {
1194
+ const attributes = getAttributes(element);
1195
+ if (!attributes) {
1196
+ return;
1197
+ }
1198
+ for (let i = attributes.length - 1; i >= 0; --i) {
1199
+ const attribute = attributes[i];
1200
+ const name = attribute && attribute.name;
1201
+ if (typeof name !== 'string' || ALLOWED_ATTR[transformCaseFunc(name)]) {
1202
+ continue;
1203
+ }
1204
+ try {
1205
+ element.removeAttribute(name);
1206
+ } catch (_) {
1207
+ /* Clobbered removeAttribute on a doomed node — ignore */
1208
+ }
1209
+ }
1210
+ };
1211
+ /**
1212
+ * _neutralizeSubtree
1213
+ *
1214
+ * Completes the audit-5 F1 fix across every removal path. The KEEP_CONTENT
1215
+ * move-hoist neutralises only disallowed-tag removals; clobber, mXSS-canary,
1216
+ * namespace, comment, processing-instruction and KEEP_CONTENT:false removals
1217
+ * all drop their subtree wholesale via `_forceRemove`. On the IN_PLACE path
1218
+ * those dropped nodes are detached from the caller's LIVE tree but a
1219
+ * handler-bearing original among them (an `<img onerror>`/`<video>` that was
1220
+ * loading) keeps its queued resource event, which fires in page scope after
1221
+ * sanitize returns. This walks a removed subtree and strips every attribute
1222
+ * the active configuration does not allow — so `on*` handlers are cancelled
1223
+ * through the SAME allowlist that governs kept nodes, not a separate `/^on/`
1224
+ * blocklist. Run synchronously before sanitize returns, i.e. before any
1225
+ * queued event can fire. Hook-free by design: these nodes leave the output,
1226
+ * so firing attribute hooks for them would be surprising. Clobber-safe reads;
1227
+ * a doomed clobbered node may shadow `removeAttribute` (its own attributes are
1228
+ * irrelevant — it is discarded — while its non-clobbered descendants, e.g.
1229
+ * the `<img>`, are reached and scrubbed).
1230
+ *
1231
+ * @param root the root of a removed subtree to neutralise
1232
+ */
1233
+ const _neutralizeSubtree = function _neutralizeSubtree(root) {
1234
+ const stack = [root];
1235
+ while (stack.length > 0) {
1236
+ const node = stack.pop();
1237
+ const nodeType = getNodeType ? getNodeType(node) : node.nodeType;
1238
+ if (nodeType === NODE_TYPE.element) {
1239
+ _stripDisallowedAttributes(node);
1240
+ }
1241
+ const childNodes = getChildNodes(node);
1242
+ if (childNodes) {
1243
+ for (let i = childNodes.length - 1; i >= 0; --i) {
1244
+ stack.push(childNodes[i]);
1245
+ }
1246
+ }
1247
+ }
1248
+ };
840
1249
  /**
841
1250
  * _initDocument
842
1251
  *
@@ -858,7 +1267,7 @@
858
1267
  // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
859
1268
  dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
860
1269
  }
861
- const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
1270
+ const dirtyPayload = trustedTypesPolicy ? _createTrustedHTML(dirty) : dirty;
862
1271
  /*
863
1272
  * Use the DOMParser API by default, fallback later if needs be
864
1273
  * DOMParser not work for svg when has multiple root element.
@@ -898,29 +1307,254 @@
898
1307
  // eslint-disable-next-line no-bitwise
899
1308
  NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
900
1309
  };
1310
+ /**
1311
+ * Replace template expression syntax (mustache, ERB, template
1312
+ * literal) with a space; shared by all SAFE_FOR_TEMPLATES scrub
1313
+ * sites. Order matters: mustache, then ERB, then template literal.
1314
+ *
1315
+ * @param value the string to scrub
1316
+ * @returns the scrubbed string
1317
+ */
1318
+ const _stripTemplateExpressions = function _stripTemplateExpressions(value) {
1319
+ value = stringReplace(value, MUSTACHE_EXPR$1, ' ');
1320
+ value = stringReplace(value, ERB_EXPR$1, ' ');
1321
+ value = stringReplace(value, TMPLIT_EXPR$1, ' ');
1322
+ return value;
1323
+ };
1324
+ /**
1325
+ * Strip template-engine expressions ({{...}}, ${...}, <%...%>) from the
1326
+ * character data of an element subtree. Used as the final safety net for
1327
+ * SAFE_FOR_TEMPLATES on every DOM-returning code path so that expressions
1328
+ * which only form after text-node normalization (e.g. fragments split across
1329
+ * stripped elements) cannot survive into a template-evaluating framework.
1330
+ *
1331
+ * Walks text/comment/CDATA/processing-instruction nodes and mutates `.data`
1332
+ * in place rather than round-tripping through innerHTML. This preserves
1333
+ * descendant node references (important for IN_PLACE callers), avoids a
1334
+ * serialize/reparse cycle, and reads literal character data — which means
1335
+ * `<%...%>` in text content matches the ERB regex against its real bytes
1336
+ * instead of the HTML-entity-escaped form innerHTML would produce.
1337
+ *
1338
+ * Attribute values are not visited here; SAFE_FOR_TEMPLATES handling for
1339
+ * attributes is performed during the per-node `_sanitizeAttributes` pass.
1340
+ *
1341
+ * @param node The root element whose character data should be scrubbed.
1342
+ */
1343
+ const _scrubTemplateExpressions2 = function _scrubTemplateExpressions(node) {
1344
+ var _node$querySelectorAl;
1345
+ node.normalize();
1346
+ const walker = createNodeIterator.call(node.ownerDocument || node, node,
1347
+ // eslint-disable-next-line no-bitwise
1348
+ NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_CDATA_SECTION | NodeFilter.SHOW_PROCESSING_INSTRUCTION, null);
1349
+ let currentNode = walker.nextNode();
1350
+ while (currentNode) {
1351
+ currentNode.data = _stripTemplateExpressions(currentNode.data);
1352
+ currentNode = walker.nextNode();
1353
+ }
1354
+ // NodeIterator does not descend into <template>.content per the DOM spec,
1355
+ // so we must explicitly recurse into each template's content fragment,
1356
+ // mirroring the approach used by _sanitizeShadowDOM.
1357
+ const templates = (_node$querySelectorAl = node.querySelectorAll) === null || _node$querySelectorAl === void 0 ? void 0 : _node$querySelectorAl.call(node, 'template');
1358
+ if (templates) {
1359
+ arrayForEach(templates, tmpl => {
1360
+ if (_isDocumentFragment(tmpl.content)) {
1361
+ _scrubTemplateExpressions2(tmpl.content);
1362
+ }
1363
+ });
1364
+ }
1365
+ };
901
1366
  /**
902
1367
  * _isClobbered
903
1368
  *
1369
+ * Detect DOM-clobbering on HTMLFormElement nodes. Form is the only HTML
1370
+ * interface with [LegacyOverrideBuiltIns]; a descendant element with a
1371
+ * `name` attribute matching a prototype property shadows that property
1372
+ * on direct reads. We use this check at the IN_PLACE entry-point and
1373
+ * during attribute sanitization to refuse clobbered forms.
1374
+ *
904
1375
  * @param element element to check for clobbering attacks
905
1376
  * @return true if clobbered, false if safe
906
1377
  */
907
1378
  const _isClobbered = function _isClobbered(element) {
908
- 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');
1379
+ // Realm-independent tag-name probe. If we can't determine the tag
1380
+ // name at all, we can't reason about clobbering — return false
1381
+ // (the caller's other defences still apply).
1382
+ const realTagName = getNodeName ? getNodeName(element) : null;
1383
+ if (typeof realTagName !== 'string') {
1384
+ return false;
1385
+ }
1386
+ if (transformCaseFunc(realTagName) !== 'form') {
1387
+ return false;
1388
+ }
1389
+ return typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' ||
1390
+ // Realm-safe NamedNodeMap detection: equality against the cached
1391
+ // prototype getter. Clobbered .attributes (e.g. <input name="attributes">)
1392
+ // makes the direct read diverge from the cached read; a clean form
1393
+ // (same-realm OR foreign-realm) has both reads pointing at the same
1394
+ // canonical NamedNodeMap.
1395
+ element.attributes !== getAttributes(element) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function' ||
1396
+ // NodeType clobbering probe. Cached Node.prototype.nodeType getter
1397
+ // returns the integer 1 for any Element regardless of realm; direct
1398
+ // read on a clobbered form (e.g. <input name="nodeType">) returns
1399
+ // the named child element. Cheap addition — nodeType is read from
1400
+ // an internal slot, no serialization cost — and removes a residual
1401
+ // clobbering surface used by several mXSS / PI / comment branches
1402
+ // in _sanitizeElements that compare currentNode.nodeType directly.
1403
+ element.nodeType !== getNodeType(element) ||
1404
+ // HTMLFormElement has [LegacyOverrideBuiltIns]: a descendant named
1405
+ // "childNodes" shadows the prototype getter. Direct reads of
1406
+ // form.childNodes from a clobbered form return the named child
1407
+ // instead of the real NodeList, so any walk that reads it directly
1408
+ // skips the form's real children. Compare the direct read to the
1409
+ // cached Node.prototype getter — when the form's named-property
1410
+ // getter intercepts the read, the two values differ and we flag
1411
+ // the form. This catches every clobbering child type (input,
1412
+ // select, etc.) regardless of whether the named child happens to
1413
+ // carry a numeric .length, which a typeof-based probe would miss
1414
+ // (e.g. HTMLSelectElement.length is a defined unsigned-long).
1415
+ element.childNodes !== getChildNodes(element);
909
1416
  };
910
1417
  /**
911
- * Checks whether the given object is a DOM node.
1418
+ * Checks whether the given value is a DocumentFragment from any realm.
1419
+ *
1420
+ * The realm-independent replacement reads `nodeType` through the cached
1421
+ * Node.prototype getter and compares to the DOCUMENT_FRAGMENT_NODE
1422
+ * constant (11). nodeType is a numeric value resolved from the node's
1423
+ * internal slot, identical across realms for the same kind of node.
1424
+ *
1425
+ * @param value object to check
1426
+ * @return true if value is a DocumentFragment-shaped node from any realm
1427
+ */
1428
+ const _isDocumentFragment = function _isDocumentFragment(value) {
1429
+ if (!getNodeType || typeof value !== 'object' || value === null) {
1430
+ return false;
1431
+ }
1432
+ try {
1433
+ return getNodeType(value) === NODE_TYPE.documentFragment;
1434
+ } catch (_) {
1435
+ return false;
1436
+ }
1437
+ };
1438
+ /**
1439
+ * Checks whether the given object is a DOM node, including nodes that
1440
+ * originate from a different window/realm (e.g. an iframe's
1441
+ * contentDocument). The previous `value instanceof Node` check was
1442
+ * realm-bound: nodes from a different window failed it, causing
1443
+ * sanitize() to silently stringify them and reset IN_PLACE to false,
1444
+ * returning the original node unsanitized. See GHSA-4w3q-35jp-p934.
912
1445
  *
913
1446
  * @param value object to check whether it's a DOM node
914
- * @return true is object is a DOM node
1447
+ * @return true if value is a DOM node from any realm
915
1448
  */
916
1449
  const _isNode = function _isNode(value) {
917
- return typeof Node === 'function' && value instanceof Node;
1450
+ if (!getNodeType || typeof value !== 'object' || value === null) {
1451
+ return false;
1452
+ }
1453
+ try {
1454
+ return typeof getNodeType(value) === 'number';
1455
+ } catch (_) {
1456
+ return false;
1457
+ }
918
1458
  };
919
1459
  function _executeHooks(hooks, currentNode, data) {
1460
+ if (hooks.length === 0) {
1461
+ return;
1462
+ }
920
1463
  arrayForEach(hooks, hook => {
921
1464
  hook.call(DOMPurify, currentNode, data, CONFIG);
922
1465
  });
923
1466
  }
1467
+ /**
1468
+ * Structural-threat checks that condemn a node regardless of the
1469
+ * allowlists: mXSS via namespace confusion, risky CSS construction,
1470
+ * processing instructions, markup-bearing comments. Pure predicate;
1471
+ * the caller removes. Check order is load-bearing.
1472
+ *
1473
+ * @param currentNode the node to inspect
1474
+ * @param tagName the node's transformCaseFunc'd tag name
1475
+ * @return true if the node must be removed
1476
+ */
1477
+ const _isUnsafeNode = function _isUnsafeNode(currentNode, tagName) {
1478
+ /* Detect mXSS attempts abusing namespace confusion */
1479
+ if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.textContent) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.innerHTML)) {
1480
+ return true;
1481
+ }
1482
+ /* Remove risky CSS construction leading to mXSS */
1483
+ if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {
1484
+ return true;
1485
+ }
1486
+ /* Remove any occurrence of processing instructions */
1487
+ if (currentNode.nodeType === NODE_TYPE.processingInstruction) {
1488
+ return true;
1489
+ }
1490
+ /* Remove any kind of possibly harmful comments */
1491
+ if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, currentNode.data)) {
1492
+ return true;
1493
+ }
1494
+ return false;
1495
+ };
1496
+ /**
1497
+ * Handle a node whose tag is forbidden or not allowlisted: keep
1498
+ * allowed custom elements (false return exits _sanitizeElements
1499
+ * early - namespace/fallback checks and the afterSanitizeElements
1500
+ * hook are intentionally skipped for kept custom elements), else
1501
+ * hoist content per KEEP_CONTENT and remove.
1502
+ *
1503
+ * @param currentNode the disallowed node
1504
+ * @param tagName the node's transformCaseFunc'd tag name
1505
+ * @return true if the node was removed, false if kept
1506
+ */
1507
+ const _sanitizeDisallowedNode = function _sanitizeDisallowedNode(currentNode, tagName) {
1508
+ /* Check if we have a custom element to handle */
1509
+ if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
1510
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
1511
+ return false;
1512
+ }
1513
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
1514
+ return false;
1515
+ }
1516
+ }
1517
+ /* Keep content except for bad-listed elements.
1518
+ Use the cached prototype getters exclusively — the previous code
1519
+ had `|| currentNode.parentNode` / `|| currentNode.childNodes`
1520
+ fallbacks, but the cached getters always return the canonical
1521
+ value (or null for a real parent-less node), so the fallback
1522
+ path was dead in safe cases and a clobbering surface in unsafe
1523
+ ones. Falsy cached results stay falsy; the `if (childNodes &&
1524
+ parentNode)` check already gates correctly. */
1525
+ if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
1526
+ const parentNode = getParentNode(currentNode);
1527
+ const childNodes = getChildNodes(currentNode);
1528
+ if (childNodes && parentNode) {
1529
+ const childCount = childNodes.length;
1530
+ /* In-place: hoist the *original* children so the iterator visits
1531
+ and sanitises them through the same allowlist pass as every other
1532
+ node. The caller built the tree in the live document, so the
1533
+ originals carry already-queued resource events (`<img onerror>`,
1534
+ `<video>`/`<audio>` error, lazy/`onload`, …); cloning would leave
1535
+ those originals detached but still armed, firing in page scope
1536
+ while the returned tree looked clean. Moving is safe in-place: the
1537
+ root is pre-validated as an allowed tag and so is never the node
1538
+ being removed, which keeps `parentNode` inside the iterator root
1539
+ and the relocated child inside the serialised tree.
1540
+ Otherwise (string / DOM-copy paths): clone. The iterator is rooted
1541
+ at — and the result serialised from — `body`, so a restrictive
1542
+ ALLOWED_TAGS that removes `body` itself must leave its content in
1543
+ place, which only cloning does; and those paths parse into an
1544
+ inert document, so their discarded originals never had a queued
1545
+ event to neutralise.
1546
+ `childNodes` is live; a tail-to-head walk keeps `childNodes[i]`
1547
+ valid whether we move (drops the trailing entry) or clone (leaves
1548
+ the list intact). */
1549
+ for (let i = childCount - 1; i >= 0; --i) {
1550
+ const hoisted = IN_PLACE ? childNodes[i] : cloneNode(childNodes[i], true);
1551
+ parentNode.insertBefore(hoisted, getNextSibling(currentNode));
1552
+ }
1553
+ }
1554
+ }
1555
+ _forceRemove(currentNode);
1556
+ return true;
1557
+ };
924
1558
  /**
925
1559
  * _sanitizeElements
926
1560
  *
@@ -931,7 +1565,6 @@
931
1565
  * @return true if node was killed, false if left alive
932
1566
  */
933
1567
  const _sanitizeElements = function _sanitizeElements(currentNode) {
934
- let content = null;
935
1568
  /* Execute a hook if present */
936
1569
  _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
937
1570
  /* Check if element is clobbered or can clobber */
@@ -940,76 +1573,41 @@
940
1573
  return true;
941
1574
  }
942
1575
  /* Now let's check the element's type and name */
943
- const tagName = transformCaseFunc(currentNode.nodeName);
1576
+ const tagName = transformCaseFunc(getNodeName ? getNodeName(currentNode) : currentNode.nodeName);
944
1577
  /* Execute a hook if present */
945
1578
  _executeHooks(hooks.uponSanitizeElement, currentNode, {
946
1579
  tagName,
947
1580
  allowedTags: ALLOWED_TAGS
948
1581
  });
949
- /* Detect mXSS attempts abusing namespace confusion */
950
- if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) {
951
- _forceRemove(currentNode);
952
- return true;
953
- }
954
- /* Remove risky CSS construction leading to mXSS */
955
- if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {
956
- _forceRemove(currentNode);
957
- return true;
958
- }
959
- /* Remove any occurrence of processing instructions */
960
- if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {
961
- _forceRemove(currentNode);
962
- return true;
963
- }
964
- /* Remove any kind of possibly harmful comments */
965
- if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) {
1582
+ /* Remove mXSS vectors, processing instructions and risky comments */
1583
+ if (_isUnsafeNode(currentNode, tagName)) {
966
1584
  _forceRemove(currentNode);
967
1585
  return true;
968
1586
  }
969
1587
  /* Remove element if anything forbids its presence */
970
1588
  if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) {
971
- /* Check if we have a custom element to handle */
972
- if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
973
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
974
- return false;
975
- }
976
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
977
- return false;
978
- }
979
- }
980
- /* Keep content except for bad-listed elements */
981
- if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
982
- const parentNode = getParentNode(currentNode) || currentNode.parentNode;
983
- const childNodes = getChildNodes(currentNode) || currentNode.childNodes;
984
- if (childNodes && parentNode) {
985
- const childCount = childNodes.length;
986
- for (let i = childCount - 1; i >= 0; --i) {
987
- const childClone = cloneNode(childNodes[i], true);
988
- childClone.__removalCount = (currentNode.__removalCount || 0) + 1;
989
- parentNode.insertBefore(childClone, getNextSibling(currentNode));
990
- }
991
- }
992
- }
993
- _forceRemove(currentNode);
994
- return true;
995
- }
996
- /* Check whether element has a valid namespace */
997
- if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
1589
+ return _sanitizeDisallowedNode(currentNode, tagName);
1590
+ }
1591
+ /* Check whether element has a valid namespace.
1592
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): use the cached Node.prototype
1593
+ nodeType getter rather than `instanceof Element`, which is realm-
1594
+ bound and short-circuits to false for any node minted in a different
1595
+ realm — letting a foreign-realm element with a forbidden namespace
1596
+ slip past the namespace check entirely. */
1597
+ const nt = getNodeType ? getNodeType(currentNode) : currentNode.nodeType;
1598
+ if (nt === NODE_TYPE.element && !_checkValidNamespace(currentNode)) {
998
1599
  _forceRemove(currentNode);
999
1600
  return true;
1000
1601
  }
1001
1602
  /* Make sure that older browsers don't get fallback-tag mXSS */
1002
- if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {
1603
+ if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(FALLBACK_TAG_CLOSE, currentNode.innerHTML)) {
1003
1604
  _forceRemove(currentNode);
1004
1605
  return true;
1005
1606
  }
1006
1607
  /* Sanitize element content to be template-safe */
1007
1608
  if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
1008
1609
  /* Get the element's text content */
1009
- content = currentNode.textContent;
1010
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1011
- content = stringReplace(content, expr, ' ');
1012
- });
1610
+ const content = _stripTemplateExpressions(currentNode.textContent);
1013
1611
  if (currentNode.textContent !== content) {
1014
1612
  arrayPush(DOMPurify.removed, {
1015
1613
  element: currentNode.cloneNode()
@@ -1039,11 +1637,12 @@
1039
1637
  if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
1040
1638
  return false;
1041
1639
  }
1640
+ const nameIsPermitted = ALLOWED_ATTR[lcName] || EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag);
1042
1641
  /* Allow valid data-* attributes: At least one character after "-"
1043
1642
  (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
1044
1643
  XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
1045
1644
  We don't need to check the value; it's always URI safe. */
1046
- if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) ; else if (EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
1645
+ if (ALLOW_DATA_ATTR && regExpTest(DATA_ATTR$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) ; else if (!nameIsPermitted) {
1047
1646
  if (
1048
1647
  // First condition does a very basic check if a) it's basically a valid custom element tagname AND
1049
1648
  // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
@@ -1055,11 +1654,15 @@
1055
1654
  return false;
1056
1655
  }
1057
1656
  /* Check value is safe. First, is attr inert? If so, is safe */
1058
- } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if (value) {
1657
+ } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; 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$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if (value) {
1059
1658
  return false;
1060
1659
  } else ;
1061
1660
  return true;
1062
1661
  };
1662
+ /* Names the HTML spec reserves from valid-custom-element-name; these must
1663
+ * never be treated as basic custom elements even when a permissive
1664
+ * CUSTOM_ELEMENT_HANDLING.tagNameCheck is configured. */
1665
+ 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']);
1063
1666
  /**
1064
1667
  * _isBasicCustomElement
1065
1668
  * checks if at least one dash is included in tagName, and it's not the first char
@@ -1069,7 +1672,64 @@
1069
1672
  * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.
1070
1673
  */
1071
1674
  const _isBasicCustomElement = function _isBasicCustomElement(tagName) {
1072
- return tagName !== 'annotation-xml' && stringMatch(tagName, CUSTOM_ELEMENT);
1675
+ return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT$1, tagName);
1676
+ };
1677
+ /**
1678
+ * Wrap an attribute value in the matching Trusted Types object when
1679
+ * the active policy requires it. Namespaced attributes pass through
1680
+ * unchanged (no TT support yet, see
1681
+ * https://bugs.chromium.org/p/chromium/issues/detail?id=1305293).
1682
+ *
1683
+ * @param lcTag lowercase tag name of the containing element
1684
+ * @param lcName lowercase attribute name
1685
+ * @param namespaceURI the attribute's namespace, if any
1686
+ * @param value the attribute value to wrap
1687
+ * @return the value, wrapped when Trusted Types demand it
1688
+ */
1689
+ const _applyTrustedTypesToAttribute = function _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value) {
1690
+ if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function' && !namespaceURI) {
1691
+ switch (trustedTypes.getAttributeType(lcTag, lcName)) {
1692
+ case 'TrustedHTML':
1693
+ {
1694
+ return _createTrustedHTML(value);
1695
+ }
1696
+ case 'TrustedScriptURL':
1697
+ {
1698
+ return _createTrustedScriptURL(value);
1699
+ }
1700
+ }
1701
+ }
1702
+ return value;
1703
+ };
1704
+ /**
1705
+ * Write a modified attribute value back onto the element. On
1706
+ * success, re-probe for clobbering introduced by the new value and
1707
+ * remove the element when found; otherwise pop the removal entry
1708
+ * recorded by the earlier _removeAttribute (long-standing pairing
1709
+ * with the SANITIZE_NAMED_PROPS path - do not "fix" casually). On
1710
+ * failure, remove the attribute instead.
1711
+ *
1712
+ * @param currentNode the element carrying the attribute
1713
+ * @param name the attribute name as present on the element
1714
+ * @param namespaceURI the attribute's namespace, if any
1715
+ * @param value the new attribute value
1716
+ */
1717
+ const _setAttributeValue = function _setAttributeValue(currentNode, name, namespaceURI, value) {
1718
+ try {
1719
+ if (namespaceURI) {
1720
+ currentNode.setAttributeNS(namespaceURI, name, value);
1721
+ } else {
1722
+ /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
1723
+ currentNode.setAttribute(name, value);
1724
+ }
1725
+ if (_isClobbered(currentNode)) {
1726
+ _forceRemove(currentNode);
1727
+ } else {
1728
+ arrayPop(DOMPurify.removed);
1729
+ }
1730
+ } catch (_) {
1731
+ _removeAttribute(name, currentNode);
1732
+ }
1073
1733
  };
1074
1734
  /**
1075
1735
  * _sanitizeAttributes
@@ -1084,9 +1744,7 @@
1084
1744
  const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
1085
1745
  /* Execute a hook if present */
1086
1746
  _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);
1087
- const {
1088
- attributes
1089
- } = currentNode;
1747
+ const attributes = currentNode.attributes;
1090
1748
  /* Check if we have attributes; if not we might have a text node */
1091
1749
  if (!attributes || _isClobbered(currentNode)) {
1092
1750
  return;
@@ -1099,14 +1757,13 @@
1099
1757
  forceKeepAttr: undefined
1100
1758
  };
1101
1759
  let l = attributes.length;
1760
+ const lcTag = transformCaseFunc(currentNode.nodeName);
1102
1761
  /* Go backwards over all attributes; safely remove bad ones */
1103
1762
  while (l--) {
1104
1763
  const attr = attributes[l];
1105
- const {
1106
- name,
1107
- namespaceURI,
1108
- value: attrValue
1109
- } = attr;
1764
+ const name = attr.name,
1765
+ namespaceURI = attr.namespaceURI,
1766
+ attrValue = attr.value;
1110
1767
  const lcName = transformCaseFunc(name);
1111
1768
  const initValue = attrValue;
1112
1769
  let value = name === 'value' ? initValue : stringTrim(initValue);
@@ -1120,12 +1777,14 @@
1120
1777
  /* Full DOM Clobbering protection via namespace isolation,
1121
1778
  * Prefix id and name attributes with `user-content-`
1122
1779
  */
1123
- if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {
1780
+ if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name') && stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0) {
1124
1781
  // Remove the attribute with this value
1125
1782
  _removeAttribute(name, currentNode);
1126
1783
  // Prefix the value and later re-create the attribute with the sanitized value
1127
1784
  value = SANITIZE_NAMED_PROPS_PREFIX + value;
1128
1785
  }
1786
+ // Else: already prefixed, leave the attribute alone — the prefix is
1787
+ // itself the clobbering protection, and re-applying it is incorrect.
1129
1788
  /* Work around a security issue with comments inside attributes */
1130
1789
  if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {
1131
1790
  _removeAttribute(name, currentNode);
@@ -1136,7 +1795,7 @@
1136
1795
  _removeAttribute(name, currentNode);
1137
1796
  continue;
1138
1797
  }
1139
- /* Did the hooks approve of the attribute? */
1798
+ /* Did the hooks force-keep the attribute? */
1140
1799
  if (hookEvent.forceKeepAttr) {
1141
1800
  continue;
1142
1801
  }
@@ -1146,56 +1805,24 @@
1146
1805
  continue;
1147
1806
  }
1148
1807
  /* Work around a security issue in jQuery 3.0 */
1149
- if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
1808
+ if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(SELF_CLOSING_TAG, value)) {
1150
1809
  _removeAttribute(name, currentNode);
1151
1810
  continue;
1152
1811
  }
1153
1812
  /* Sanitize attribute content to be template-safe */
1154
1813
  if (SAFE_FOR_TEMPLATES) {
1155
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1156
- value = stringReplace(value, expr, ' ');
1157
- });
1814
+ value = _stripTemplateExpressions(value);
1158
1815
  }
1159
1816
  /* Is `value` valid for this attribute? */
1160
- const lcTag = transformCaseFunc(currentNode.nodeName);
1161
1817
  if (!_isValidAttribute(lcTag, lcName, value)) {
1162
1818
  _removeAttribute(name, currentNode);
1163
1819
  continue;
1164
1820
  }
1165
1821
  /* Handle attributes that require Trusted Types */
1166
- if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {
1167
- if (namespaceURI) ; else {
1168
- switch (trustedTypes.getAttributeType(lcTag, lcName)) {
1169
- case 'TrustedHTML':
1170
- {
1171
- value = trustedTypesPolicy.createHTML(value);
1172
- break;
1173
- }
1174
- case 'TrustedScriptURL':
1175
- {
1176
- value = trustedTypesPolicy.createScriptURL(value);
1177
- break;
1178
- }
1179
- }
1180
- }
1181
- }
1822
+ value = _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value);
1182
1823
  /* Handle invalid data-* attribute set by try-catching it */
1183
1824
  if (value !== initValue) {
1184
- try {
1185
- if (namespaceURI) {
1186
- currentNode.setAttributeNS(namespaceURI, name, value);
1187
- } else {
1188
- /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
1189
- currentNode.setAttribute(name, value);
1190
- }
1191
- if (_isClobbered(currentNode)) {
1192
- _forceRemove(currentNode);
1193
- } else {
1194
- arrayPop(DOMPurify.removed);
1195
- }
1196
- } catch (_) {
1197
- _removeAttribute(name, currentNode);
1198
- }
1825
+ _setAttributeValue(currentNode, name, namespaceURI, value);
1199
1826
  }
1200
1827
  }
1201
1828
  /* Execute a hook if present */
@@ -1218,14 +1845,133 @@
1218
1845
  _sanitizeElements(shadowNode);
1219
1846
  /* Check attributes next */
1220
1847
  _sanitizeAttributes(shadowNode);
1221
- /* Deep shadow DOM detected */
1222
- if (shadowNode.content instanceof DocumentFragment) {
1848
+ /* Deep shadow DOM detected.
1849
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): use nodeType against the
1850
+ DOCUMENT_FRAGMENT_NODE constant rather than instanceof, so we
1851
+ recurse into <template>.content from foreign realms too. */
1852
+ if (_isDocumentFragment(shadowNode.content)) {
1223
1853
  _sanitizeShadowDOM2(shadowNode.content);
1224
1854
  }
1855
+ /* An element iterated here may itself host an attached
1856
+ shadow root. The default NodeIterator does not enter shadow
1857
+ trees, so a shadow root nested inside template.content was
1858
+ previously reached by no walk at all (the pre-pass at
1859
+ _sanitizeAttachedShadowRoots descends via childNodes, which
1860
+ doesn't enter template.content; the template-content recursion
1861
+ above iterates the content but never inspected shadowRoot).
1862
+ Walk it explicitly. The nodeType guard avoids reading
1863
+ shadowRoot off text / comment / CDATA / PI nodes that the
1864
+ iterator also surfaces. */
1865
+ const shadowNodeType = getNodeType ? getNodeType(shadowNode) : shadowNode.nodeType;
1866
+ if (shadowNodeType === NODE_TYPE.element) {
1867
+ const innerSr = getShadowRoot(shadowNode);
1868
+ if (_isDocumentFragment(innerSr)) {
1869
+ _sanitizeAttachedShadowRoots(innerSr);
1870
+ _sanitizeShadowDOM2(innerSr);
1871
+ }
1872
+ }
1225
1873
  }
1226
1874
  /* Execute a hook if present */
1227
1875
  _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
1228
1876
  };
1877
+ /**
1878
+ * _sanitizeAttachedShadowRoots
1879
+ *
1880
+ * Walks `root` and feeds every attached shadow root we encounter into
1881
+ * the existing _sanitizeShadowDOM pipeline. The default node iterator
1882
+ * does not descend into shadow trees, so nodes inside an attached
1883
+ * shadow root would otherwise be skipped entirely.
1884
+ *
1885
+ * Two real input paths put attached shadow roots in front of us:
1886
+ * 1. IN_PLACE on a DOM node that already has shadow roots attached.
1887
+ * 2. DOM-node input where importNode(dirty, true) deep-clones the
1888
+ * shadow root because it was created with `clonable: true`.
1889
+ *
1890
+ * This pass runs once, up front, so the main iteration loop (and the
1891
+ * existing _sanitizeShadowDOM template-content recursion) stay
1892
+ * untouched — string-input paths are not affected.
1893
+ *
1894
+ * @param root the subtree root to walk for attached shadow roots
1895
+ */
1896
+ const _sanitizeAttachedShadowRoots = function _sanitizeAttachedShadowRoots(root) {
1897
+ /* Iterative (explicit stack) rather than per-child recursion. DOM APIs
1898
+ impose no depth cap, so an attacker-shaped tree (JSON/CRDT/editor data
1899
+ built straight into the DOM — the IN_PLACE surface) deeper than the JS
1900
+ call-stack budget would otherwise overflow native recursion here and
1901
+ throw at the IN_PLACE entry pre-pass, before a single node is
1902
+ sanitized, leaving the caller's live tree untouched (fail-open). See
1903
+ campaign-3 F4. A heap stack keeps depth off the call stack.
1904
+ Each work item is either a node to descend into, or a deferred
1905
+ `_sanitizeShadowDOM` for an already-walked shadow root. The deferred
1906
+ form preserves the original post-order discipline: a shadow root's
1907
+ nested shadow roots are discovered before the outer shadow is
1908
+ sanitized (which may remove hosts). Pushes are in reverse of the
1909
+ desired processing order (LIFO): template content, then children, then
1910
+ the shadow-sanitize, then the shadow walk — so the order matches the
1911
+ previous recursion exactly. */
1912
+ const stack = [{
1913
+ node: root,
1914
+ shadow: null
1915
+ }];
1916
+ while (stack.length > 0) {
1917
+ const item = stack.pop();
1918
+ /* Deferred shadow-DOM sanitisation: runs after its subtree was walked. */
1919
+ if (item.shadow) {
1920
+ _sanitizeShadowDOM2(item.shadow);
1921
+ continue;
1922
+ }
1923
+ const node = item.node;
1924
+ const nodeType = getNodeType ? getNodeType(node) : node.nodeType;
1925
+ const isElement = nodeType === NODE_TYPE.element;
1926
+ /* (pushed last → processed first) Children, snapshotted in reverse so
1927
+ the first child is processed first. Snapshotting matters because a
1928
+ hook may detach siblings mid-walk. */
1929
+ const childNodes = getChildNodes(node);
1930
+ if (childNodes) {
1931
+ for (let i = childNodes.length - 1; i >= 0; --i) {
1932
+ stack.push({
1933
+ node: childNodes[i],
1934
+ shadow: null
1935
+ });
1936
+ }
1937
+ }
1938
+ /* (pushed before children → processed after them, matching the old
1939
+ "template content last" order) When the node is a <template>,
1940
+ descend into its content. */
1941
+ if (isElement) {
1942
+ const rootName = getNodeName ? getNodeName(node) : null;
1943
+ if (typeof rootName === 'string' && transformCaseFunc(rootName) === 'template') {
1944
+ const content = node.content;
1945
+ if (_isDocumentFragment(content)) {
1946
+ stack.push({
1947
+ node: content,
1948
+ shadow: null
1949
+ });
1950
+ }
1951
+ }
1952
+ }
1953
+ /* Shadow root (processed first): walk its subtree, then sanitise it.
1954
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
1955
+ rather than `instanceof DocumentFragment`, which is realm-bound and
1956
+ silently skipped foreign-realm shadow roots (e.g.
1957
+ iframe.contentDocument attachShadow). */
1958
+ if (isElement) {
1959
+ const sr = getShadowRoot(node);
1960
+ if (_isDocumentFragment(sr)) {
1961
+ /* Push the deferred sanitise first so it pops after the shadow
1962
+ walk we push next, i.e. nested shadow roots are discovered
1963
+ before this one is sanitised. */
1964
+ stack.push({
1965
+ node: null,
1966
+ shadow: sr
1967
+ }, {
1968
+ node: sr,
1969
+ shadow: null
1970
+ });
1971
+ }
1972
+ }
1973
+ }
1974
+ };
1229
1975
  // eslint-disable-next-line complexity
1230
1976
  DOMPurify.sanitize = function (dirty) {
1231
1977
  let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
@@ -1242,13 +1988,9 @@
1242
1988
  }
1243
1989
  /* Stringify, in case dirty is an object */
1244
1990
  if (typeof dirty !== 'string' && !_isNode(dirty)) {
1245
- if (typeof dirty.toString === 'function') {
1246
- dirty = dirty.toString();
1247
- if (typeof dirty !== 'string') {
1248
- throw typeErrorCreate('dirty is not a string, aborting');
1249
- }
1250
- } else {
1251
- throw typeErrorCreate('toString is not a function');
1991
+ dirty = stringifyValue(dirty);
1992
+ if (typeof dirty !== 'string') {
1993
+ throw typeErrorCreate('dirty is not a string, aborting');
1252
1994
  }
1253
1995
  }
1254
1996
  /* Return dirty HTML if DOMPurify cannot run */
@@ -1256,24 +1998,78 @@
1256
1998
  return dirty;
1257
1999
  }
1258
2000
  /* Assign config vars */
1259
- if (!SET_CONFIG) {
2001
+ if (SET_CONFIG) {
2002
+ /* Persistent setConfig() path: _parseConfig is skipped, so the sets are
2003
+ * not re-derived per call. Restore them from the pristine bindings
2004
+ * captured at setConfig() time so a previous call's hook clone (mutated
2005
+ * below) does not carry over. */
2006
+ ALLOWED_TAGS = SET_CONFIG_ALLOWED_TAGS;
2007
+ ALLOWED_ATTR = SET_CONFIG_ALLOWED_ATTR;
2008
+ } else {
1260
2009
  _parseConfig(cfg);
1261
2010
  }
2011
+ /* Clone the hook-mutable allowlists before the walk whenever an
2012
+ * uponSanitize* hook is registered. The hook event exposes ALLOWED_TAGS
2013
+ * and ALLOWED_ATTR by reference (as allowedTags / allowedAttributes), so
2014
+ * a hook that widens them would otherwise mutate the shared set
2015
+ * permanently: across later calls and across every element. Cloning per
2016
+ * walk keeps documented in-call widening working while scoping it to the
2017
+ * call. A single guard for both config paths - the per-call path rebinds
2018
+ * the sets in _parseConfig each call, the persistent path restores them
2019
+ * from the captured bindings just above - so the two cannot diverge. */
2020
+ if (hooks.uponSanitizeElement.length > 0 || hooks.uponSanitizeAttribute.length > 0) {
2021
+ ALLOWED_TAGS = clone(ALLOWED_TAGS);
2022
+ }
2023
+ if (hooks.uponSanitizeAttribute.length > 0) {
2024
+ ALLOWED_ATTR = clone(ALLOWED_ATTR);
2025
+ }
1262
2026
  /* Clean up removed elements */
1263
2027
  DOMPurify.removed = [];
1264
- /* Check if dirty is correctly typed for IN_PLACE */
1265
- if (typeof dirty === 'string') {
1266
- IN_PLACE = false;
1267
- }
1268
- if (IN_PLACE) {
1269
- /* Do some early pre-sanitization to avoid unsafe root nodes */
1270
- if (dirty.nodeName) {
1271
- const tagName = transformCaseFunc(dirty.nodeName);
2028
+ /* Resolve IN_PLACE for this call without mutating persistent config.
2029
+ Writing the IN_PLACE closure variable here leaks under setConfig(),
2030
+ where _parseConfig is skipped on later calls: a single string call would
2031
+ disable in-place mode for every subsequent node call, returning a
2032
+ sanitized copy while leaving the caller's node — which in-place callers
2033
+ keep using and whose return value they ignore unsanitized. REPORT-2. */
2034
+ const inPlace = IN_PLACE && typeof dirty !== 'string' && _isNode(dirty);
2035
+ if (inPlace) {
2036
+ /* Do some early pre-sanitization to avoid unsafe root nodes.
2037
+ Read nodeName through the cached prototype getter — a clobbering
2038
+ child named "nodeName" on the form root would otherwise shadow
2039
+ the property and let this check skip the root-allowlist
2040
+ validation entirely. */
2041
+ const nn = getNodeName ? getNodeName(dirty) : dirty.nodeName;
2042
+ if (typeof nn === 'string') {
2043
+ const tagName = transformCaseFunc(nn);
1272
2044
  if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
1273
2045
  throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
1274
2046
  }
1275
2047
  }
1276
- } else if (dirty instanceof Node) {
2048
+ /* Pre-flight the root through _isClobbered. The iterator-driven
2049
+ removal path can not detach a parent-less root: _forceRemove
2050
+ falls through to Element.prototype.remove(), which per spec
2051
+ is a no-op on a node with no parent. A clobbered root would
2052
+ then survive the main loop with its attributes uninspected,
2053
+ because _sanitizeAttributes early-returns on _isClobbered. The
2054
+ result would be an attacker-controlled form, complete with any
2055
+ event-handler attributes the caller passed in, handed back to
2056
+ the application unsanitized. Refuse to sanitize such a root
2057
+ the same way we refuse a forbidden tag. GHSA-r47g-fvhr-h676. */
2058
+ if (_isClobbered(dirty)) {
2059
+ throw typeErrorCreate('root node is clobbered and cannot be sanitized in-place');
2060
+ }
2061
+ /* Sanitize attached shadow roots before the main iterator runs.
2062
+ The iterator does not descend into shadow trees. Same fail-closed
2063
+ barrier as the main walk (campaign-3 F2): a custom-element reaction
2064
+ inside a shadow root could abort this pre-pass before the walk runs,
2065
+ which would otherwise leave the entire live tree unsanitized. */
2066
+ try {
2067
+ _sanitizeAttachedShadowRoots(dirty);
2068
+ } catch (error) {
2069
+ _neutralizeRoot(dirty);
2070
+ throw error;
2071
+ }
2072
+ } else if (_isNode(dirty)) {
1277
2073
  /* If dirty is a DOM element, append to an empty document to avoid
1278
2074
  elements being stripped by the parser */
1279
2075
  body = _initDocument('<!---->');
@@ -1287,12 +2083,18 @@
1287
2083
  // eslint-disable-next-line unicorn/prefer-dom-node-append
1288
2084
  body.appendChild(importedNode);
1289
2085
  }
2086
+ /* Clonable shadow roots are deep-cloned by importNode(); sanitize
2087
+ them before the main iterator runs, since the iterator does not
2088
+ descend into shadow trees. The walk routes every read through a
2089
+ cached prototype getter so clobbering descendants on a form root
2090
+ cannot hide a shadow host from this pass. */
2091
+ _sanitizeAttachedShadowRoots(importedNode);
1290
2092
  } else {
1291
2093
  /* Exit directly if we have nothing to do */
1292
2094
  if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
1293
2095
  // eslint-disable-next-line unicorn/prefer-includes
1294
2096
  dirty.indexOf('<') === -1) {
1295
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
2097
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(dirty) : dirty;
1296
2098
  }
1297
2099
  /* Initialize the document to work on */
1298
2100
  body = _initDocument(dirty);
@@ -1306,31 +2108,59 @@
1306
2108
  _forceRemove(body.firstChild);
1307
2109
  }
1308
2110
  /* Get node iterator */
1309
- const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);
1310
- /* Now start iterating over the created document */
1311
- while (currentNode = nodeIterator.nextNode()) {
1312
- /* Sanitize tags and elements */
1313
- _sanitizeElements(currentNode);
1314
- /* Check attributes next */
1315
- _sanitizeAttributes(currentNode);
1316
- /* Shadow DOM detected, sanitize it */
1317
- if (currentNode.content instanceof DocumentFragment) {
1318
- _sanitizeShadowDOM2(currentNode.content);
2111
+ const nodeIterator = _createNodeIterator(inPlace ? dirty : body);
2112
+ /* Now start iterating over the created document.
2113
+ The walk runs inside an exception barrier (campaign-3 F2): a re-entrant
2114
+ engine/custom-element mutation can detach a node mid-walk so
2115
+ `_forceRemove`'s parentless guard throws, aborting the loop. Without the
2116
+ barrier the caller's in-place tree would be left half-sanitized with the
2117
+ unvisited tail still armed. On any throw we fail closed — strip the
2118
+ in-place root bare then rethrow so the existing throw contract is
2119
+ preserved. (String/DOM-copy paths never return the partial body, so the
2120
+ propagating throw is already fail-closed there.) */
2121
+ try {
2122
+ while (currentNode = nodeIterator.nextNode()) {
2123
+ /* Sanitize tags and elements */
2124
+ _sanitizeElements(currentNode);
2125
+ /* Check attributes next */
2126
+ _sanitizeAttributes(currentNode);
2127
+ /* Shadow DOM detected, sanitize it.
2128
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
2129
+ instead of instanceof, so foreign-realm <template>.content is
2130
+ walked correctly. */
2131
+ if (_isDocumentFragment(currentNode.content)) {
2132
+ _sanitizeShadowDOM2(currentNode.content);
2133
+ }
2134
+ }
2135
+ } catch (error) {
2136
+ if (inPlace) {
2137
+ _neutralizeRoot(dirty);
1319
2138
  }
2139
+ throw error;
1320
2140
  }
1321
2141
  /* If we sanitized `dirty` in-place, return it. */
1322
- if (IN_PLACE) {
2142
+ if (inPlace) {
2143
+ /* Fail-closed completion of the audit-5 F1 fix: every node removed from
2144
+ the caller's live tree is detached but may still hold a queued
2145
+ resource-event handler that fires in page scope after we return. The
2146
+ move-hoist covers only disallowed-tag KEEP_CONTENT removals; strip the
2147
+ non-allow-listed attributes off every other removed subtree (clobber,
2148
+ mXSS, namespace, comments, KEEP_CONTENT:false, …) so those handlers are
2149
+ cancelled before any event can fire. Runs synchronously, pre-return. */
2150
+ arrayForEach(DOMPurify.removed, entry => {
2151
+ if (entry.element) {
2152
+ _neutralizeSubtree(entry.element);
2153
+ }
2154
+ });
2155
+ if (SAFE_FOR_TEMPLATES) {
2156
+ _scrubTemplateExpressions2(dirty);
2157
+ }
1323
2158
  return dirty;
1324
2159
  }
1325
2160
  /* Return sanitized string or DOM */
1326
2161
  if (RETURN_DOM) {
1327
2162
  if (SAFE_FOR_TEMPLATES) {
1328
- body.normalize();
1329
- let html = body.innerHTML;
1330
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1331
- html = stringReplace(html, expr, ' ');
1332
- });
1333
- body.innerHTML = html;
2163
+ _scrubTemplateExpressions2(body);
1334
2164
  }
1335
2165
  if (RETURN_DOM_FRAGMENT) {
1336
2166
  returnNode = createDocumentFragment.call(body.ownerDocument);
@@ -1360,20 +2190,28 @@
1360
2190
  }
1361
2191
  /* Sanitize final string template-safe */
1362
2192
  if (SAFE_FOR_TEMPLATES) {
1363
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1364
- serializedHTML = stringReplace(serializedHTML, expr, ' ');
1365
- });
2193
+ serializedHTML = _stripTemplateExpressions(serializedHTML);
1366
2194
  }
1367
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
2195
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(serializedHTML) : serializedHTML;
1368
2196
  };
1369
2197
  DOMPurify.setConfig = function () {
1370
2198
  let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1371
2199
  _parseConfig(cfg);
1372
2200
  SET_CONFIG = true;
2201
+ SET_CONFIG_ALLOWED_TAGS = ALLOWED_TAGS;
2202
+ SET_CONFIG_ALLOWED_ATTR = ALLOWED_ATTR;
1373
2203
  };
1374
2204
  DOMPurify.clearConfig = function () {
1375
2205
  CONFIG = null;
1376
2206
  SET_CONFIG = false;
2207
+ SET_CONFIG_ALLOWED_TAGS = null;
2208
+ SET_CONFIG_ALLOWED_ATTR = null;
2209
+ // Drop any caller-supplied Trusted Types policy so it cannot poison later
2210
+ // `RETURN_TRUSTED_TYPE` output. The internal default policy (cached, and
2211
+ // never recreated — Trusted Types throws on duplicate names) is restored by
2212
+ // the next `_parseConfig`. See GHSA-vxr8-fq34-vvx9.
2213
+ trustedTypesPolicy = defaultTrustedTypesPolicy;
2214
+ emptyHTML = '';
1377
2215
  };
1378
2216
  DOMPurify.isValidAttribute = function (tag, attr, value) {
1379
2217
  /* Initialize shared config vars if necessary. */
@@ -1388,9 +2226,19 @@
1388
2226
  if (typeof hookFunction !== 'function') {
1389
2227
  return;
1390
2228
  }
2229
+ /* Reject unknown entry points. Without this, a non-hook key (e.g.
2230
+ * '__proto__') indexes off the prototype chain rather than a real
2231
+ * hook array, and arrayPush then writes to Object.prototype. Guard
2232
+ * with an own-property check against the known hook names. */
2233
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
2234
+ return;
2235
+ }
1391
2236
  arrayPush(hooks[entryPoint], hookFunction);
1392
2237
  };
1393
2238
  DOMPurify.removeHook = function (entryPoint, hookFunction) {
2239
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
2240
+ return undefined;
2241
+ }
1394
2242
  if (hookFunction !== undefined) {
1395
2243
  const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);
1396
2244
  return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];
@@ -1398,6 +2246,9 @@
1398
2246
  return arrayPop(hooks[entryPoint]);
1399
2247
  };
1400
2248
  DOMPurify.removeHooks = function (entryPoint) {
2249
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
2250
+ return;
2251
+ }
1401
2252
  hooks[entryPoint] = [];
1402
2253
  };
1403
2254
  DOMPurify.removeAllHooks = function () {