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