@touchvue/chat 1.0.0-beta.56 → 1.0.0-beta.57

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.
Files changed (121) hide show
  1. package/es/index.mjs.map +1 -1
  2. package/es/node_modules/.pnpm/{dompurify@3.4.3 → dompurify@3.4.11}/node_modules/dompurify/dist/purify.es.mjs +939 -226
  3. package/es/node_modules/.pnpm/dompurify@3.4.11/node_modules/dompurify/dist/purify.es.mjs.map +1 -0
  4. package/es/node_modules/.pnpm/{linkify-it@5.0.0 → linkify-it@5.0.2}/node_modules/linkify-it/index.mjs +109 -105
  5. package/es/node_modules/.pnpm/linkify-it@5.0.2/node_modules/linkify-it/index.mjs.map +1 -0
  6. package/es/node_modules/.pnpm/{linkify-it@5.0.0 → linkify-it@5.0.2}/node_modules/linkify-it/lib/re.mjs +34 -30
  7. package/es/node_modules/.pnpm/linkify-it@5.0.2/node_modules/linkify-it/lib/re.mjs.map +1 -0
  8. package/es/node_modules/.pnpm/{markdown-it-deflist@3.0.0 → markdown-it-deflist@3.0.1}/node_modules/markdown-it-deflist/index.mjs +2 -1
  9. package/es/node_modules/.pnpm/markdown-it-deflist@3.0.1/node_modules/markdown-it-deflist/index.mjs.map +1 -0
  10. package/es/node_modules/.pnpm/markdown-it@14.1.0/node_modules/markdown-it/lib/index.mjs +1 -1
  11. package/es/package.json.mjs +1 -1
  12. package/es/packages/components/touchchat/component/AiRobot/face.vue2.mjs.map +1 -1
  13. package/es/packages/components/touchchat/component/AiRobot/letter.vue2.mjs +1 -1
  14. package/es/packages/components/touchchat/component/AiRobot/letter.vue2.mjs.map +1 -1
  15. package/es/packages/components/touchchat/component/AiRobot/meterialPrepare.vue2.mjs.map +1 -1
  16. package/es/packages/components/touchchat/component/AiRobot/start.vue2.mjs.map +1 -1
  17. package/es/packages/components/touchchat/component/CardView.vue2.mjs.map +1 -1
  18. package/es/packages/components/touchchat/component/ImageFile.vue2.mjs.map +1 -1
  19. package/es/packages/components/touchchat/component/ImageView.vue2.mjs.map +1 -1
  20. package/es/packages/components/touchchat/component/LinkView.vue2.mjs.map +1 -1
  21. package/es/packages/components/touchchat/component/MarkLayer.vue2.mjs.map +1 -1
  22. package/es/packages/components/touchchat/component/ModuleSelect.vue2.mjs.map +1 -1
  23. package/es/packages/components/touchchat/component/Screenshot.vue2.mjs.map +1 -1
  24. package/es/packages/components/touchchat/component/ThoughtChain.vue2.mjs.map +1 -1
  25. package/es/packages/components/touchchat/component/UploadView.vue2.mjs.map +1 -1
  26. package/es/packages/components/touchchat/component/UploadView_api.vue2.mjs.map +1 -1
  27. package/es/packages/components/touchchat/index.mjs.map +1 -1
  28. package/es/packages/components/touchchat/src/AiChat/Chat/TouchChat.mjs.map +1 -1
  29. package/es/packages/components/touchchat/src/AiChat/Chat/useChat.mjs +7 -2
  30. package/es/packages/components/touchchat/src/AiChat/Chat/useChat.mjs.map +1 -1
  31. package/es/packages/components/touchchat/src/AiChat/Chat/useMessageRender.mjs +1 -1
  32. package/es/packages/components/touchchat/src/AiChat/Chat/useSSE.mjs +10 -7
  33. package/es/packages/components/touchchat/src/AiChat/Chat/useSSE.mjs.map +1 -1
  34. package/es/packages/components/touchchat/src/AiChat/Chat/useScroll.mjs.map +1 -1
  35. package/es/packages/components/touchchat/src/AiChat/ChatInput.vue2.mjs +6 -2
  36. package/es/packages/components/touchchat/src/AiChat/ChatInput.vue2.mjs.map +1 -1
  37. package/es/packages/components/touchchat/src/AiChat/HistoryList.vue2.mjs.map +1 -1
  38. package/es/packages/components/touchchat/src/AiChat/HistorySidebar.vue2.mjs.map +1 -1
  39. package/es/packages/components/touchchat/src/AiChat/SiderBarView.vue2.mjs.map +1 -1
  40. package/es/packages/components/touchchat/src/AiChat/TouchAgent.vue2.mjs +136 -120
  41. package/es/packages/components/touchchat/src/AiChat/TouchAgent.vue2.mjs.map +1 -1
  42. package/es/packages/components/touchchat/src/index.vue2.mjs +6 -1
  43. package/es/packages/components/touchchat/src/index.vue2.mjs.map +1 -1
  44. package/es/packages/components/touchchat/src/types/a2a.mjs.map +1 -1
  45. package/es/packages/components/touchchat/utils/a2aService.mjs +189 -132
  46. package/es/packages/components/touchchat/utils/a2aService.mjs.map +1 -1
  47. package/es/packages/components/touchchat/utils/chatRobot.mjs.map +1 -1
  48. package/es/packages/components/touchchat/utils/deepCloneDom.mjs.map +1 -1
  49. package/es/packages/components/touchchat/utils/hight-it.mjs.map +1 -1
  50. package/es/packages/components/touchchat/utils/markdown.mjs +2 -2
  51. package/es/packages/components/touchchat/utils/markdown.mjs.map +1 -1
  52. package/es/packages/components/touchchat/utils/socket.mjs.map +1 -1
  53. package/es/packages/components/touchchat/utils/tools.mjs.map +1 -1
  54. package/es/packages/components/touchchat/utils/uuid.mjs.map +1 -1
  55. package/es/packages/utils/config.mjs.map +1 -1
  56. package/es/packages/utils/types.mjs.map +1 -1
  57. package/lib/index.js.map +1 -1
  58. package/lib/node_modules/.pnpm/{dompurify@3.4.3 → dompurify@3.4.11}/node_modules/dompurify/dist/purify.es.js +939 -226
  59. package/lib/node_modules/.pnpm/dompurify@3.4.11/node_modules/dompurify/dist/purify.es.js.map +1 -0
  60. package/lib/node_modules/.pnpm/{linkify-it@5.0.0 → linkify-it@5.0.2}/node_modules/linkify-it/index.js +109 -105
  61. package/lib/node_modules/.pnpm/linkify-it@5.0.2/node_modules/linkify-it/index.js.map +1 -0
  62. package/lib/node_modules/.pnpm/{linkify-it@5.0.0 → linkify-it@5.0.2}/node_modules/linkify-it/lib/re.js +34 -30
  63. package/lib/node_modules/.pnpm/linkify-it@5.0.2/node_modules/linkify-it/lib/re.js.map +1 -0
  64. package/lib/node_modules/.pnpm/{markdown-it-deflist@3.0.0 → markdown-it-deflist@3.0.1}/node_modules/markdown-it-deflist/index.js +2 -1
  65. package/lib/node_modules/.pnpm/markdown-it-deflist@3.0.1/node_modules/markdown-it-deflist/index.js.map +1 -0
  66. package/lib/node_modules/.pnpm/markdown-it@14.1.0/node_modules/markdown-it/lib/index.js +1 -1
  67. package/lib/package.json.js +1 -1
  68. package/lib/packages/components/touchchat/component/AiRobot/face.vue2.js.map +1 -1
  69. package/lib/packages/components/touchchat/component/AiRobot/letter.vue2.js +1 -1
  70. package/lib/packages/components/touchchat/component/AiRobot/letter.vue2.js.map +1 -1
  71. package/lib/packages/components/touchchat/component/AiRobot/meterialPrepare.vue2.js.map +1 -1
  72. package/lib/packages/components/touchchat/component/AiRobot/start.vue2.js.map +1 -1
  73. package/lib/packages/components/touchchat/component/CardView.vue2.js.map +1 -1
  74. package/lib/packages/components/touchchat/component/ImageFile.vue2.js.map +1 -1
  75. package/lib/packages/components/touchchat/component/ImageView.vue2.js.map +1 -1
  76. package/lib/packages/components/touchchat/component/LinkView.vue2.js.map +1 -1
  77. package/lib/packages/components/touchchat/component/MarkLayer.vue2.js.map +1 -1
  78. package/lib/packages/components/touchchat/component/ModuleSelect.vue2.js.map +1 -1
  79. package/lib/packages/components/touchchat/component/Screenshot.vue2.js.map +1 -1
  80. package/lib/packages/components/touchchat/component/ThoughtChain.vue2.js.map +1 -1
  81. package/lib/packages/components/touchchat/component/UploadView.vue2.js.map +1 -1
  82. package/lib/packages/components/touchchat/component/UploadView_api.vue2.js.map +1 -1
  83. package/lib/packages/components/touchchat/index.js.map +1 -1
  84. package/lib/packages/components/touchchat/src/AiChat/Chat/TouchChat.js.map +1 -1
  85. package/lib/packages/components/touchchat/src/AiChat/Chat/useChat.js +6 -1
  86. package/lib/packages/components/touchchat/src/AiChat/Chat/useChat.js.map +1 -1
  87. package/lib/packages/components/touchchat/src/AiChat/Chat/useMessageRender.js +1 -1
  88. package/lib/packages/components/touchchat/src/AiChat/Chat/useSSE.js +10 -7
  89. package/lib/packages/components/touchchat/src/AiChat/Chat/useSSE.js.map +1 -1
  90. package/lib/packages/components/touchchat/src/AiChat/Chat/useScroll.js.map +1 -1
  91. package/lib/packages/components/touchchat/src/AiChat/ChatInput.vue2.js +5 -1
  92. package/lib/packages/components/touchchat/src/AiChat/ChatInput.vue2.js.map +1 -1
  93. package/lib/packages/components/touchchat/src/AiChat/HistoryList.vue2.js.map +1 -1
  94. package/lib/packages/components/touchchat/src/AiChat/HistorySidebar.vue2.js.map +1 -1
  95. package/lib/packages/components/touchchat/src/AiChat/SiderBarView.vue2.js.map +1 -1
  96. package/lib/packages/components/touchchat/src/AiChat/TouchAgent.vue2.js +136 -120
  97. package/lib/packages/components/touchchat/src/AiChat/TouchAgent.vue2.js.map +1 -1
  98. package/lib/packages/components/touchchat/src/index.vue2.js +6 -1
  99. package/lib/packages/components/touchchat/src/index.vue2.js.map +1 -1
  100. package/lib/packages/components/touchchat/src/types/a2a.js.map +1 -1
  101. package/lib/packages/components/touchchat/utils/a2aService.js +189 -132
  102. package/lib/packages/components/touchchat/utils/a2aService.js.map +1 -1
  103. package/lib/packages/components/touchchat/utils/chatRobot.js.map +1 -1
  104. package/lib/packages/components/touchchat/utils/deepCloneDom.js.map +1 -1
  105. package/lib/packages/components/touchchat/utils/hight-it.js.map +1 -1
  106. package/lib/packages/components/touchchat/utils/markdown.js +2 -2
  107. package/lib/packages/components/touchchat/utils/markdown.js.map +1 -1
  108. package/lib/packages/components/touchchat/utils/socket.js.map +1 -1
  109. package/lib/packages/components/touchchat/utils/tools.js.map +1 -1
  110. package/lib/packages/components/touchchat/utils/uuid.js.map +1 -1
  111. package/lib/packages/utils/config.js.map +1 -1
  112. package/lib/packages/utils/types.js.map +1 -1
  113. package/package.json +83 -83
  114. package/es/node_modules/.pnpm/dompurify@3.4.3/node_modules/dompurify/dist/purify.es.mjs.map +0 -1
  115. package/es/node_modules/.pnpm/linkify-it@5.0.0/node_modules/linkify-it/index.mjs.map +0 -1
  116. package/es/node_modules/.pnpm/linkify-it@5.0.0/node_modules/linkify-it/lib/re.mjs.map +0 -1
  117. package/es/node_modules/.pnpm/markdown-it-deflist@3.0.0/node_modules/markdown-it-deflist/index.mjs.map +0 -1
  118. package/lib/node_modules/.pnpm/dompurify@3.4.3/node_modules/dompurify/dist/purify.es.js.map +0 -1
  119. package/lib/node_modules/.pnpm/linkify-it@5.0.0/node_modules/linkify-it/index.js.map +0 -1
  120. package/lib/node_modules/.pnpm/linkify-it@5.0.0/node_modules/linkify-it/lib/re.js.map +0 -1
  121. package/lib/node_modules/.pnpm/markdown-it-deflist@3.0.0/node_modules/markdown-it-deflist/index.js.map +0 -1
@@ -2,7 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- /*! @license DOMPurify 3.4.3 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.3/LICENSE */
5
+ /*! @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 */
6
6
 
7
7
  function _arrayLikeToArray(r, a) {
8
8
  (null == a || a > r.length) && (a = r.length);
@@ -314,7 +314,7 @@ const mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mgly
314
314
  const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
315
315
  const text = freeze(['#text']);
316
316
 
317
- 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']);
317
+ 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']);
318
318
  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']);
319
319
  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']);
320
320
  const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
@@ -331,16 +331,31 @@ const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205
331
331
  );
332
332
  const DOCTYPE_NAME = seal(/^html$/i);
333
333
  const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);
334
+ // Markup-significant character probes used by _sanitizeElements.
335
+ // Shared module-level instances are safe despite the sticky /g flags:
336
+ // unapply() resets lastIndex for RegExp receivers before every call.
337
+ const ELEMENT_MARKUP_PROBE = seal(/<[/\w!]/g);
338
+ const COMMENT_MARKUP_PROBE = seal(/<[/\w]/g);
339
+ const FALLBACK_TAG_CLOSE = seal(/<\/no(script|embed|frames)/i);
340
+ const SELF_CLOSING_TAG = seal(/\/>/i);
334
341
 
335
- /* eslint-disable @typescript-eslint/indent */
336
342
  // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
337
343
  const NODE_TYPE = {
338
344
  element: 1,
345
+ attribute: 2,
339
346
  text: 3,
347
+ cdataSection: 4,
348
+ entityReference: 5,
340
349
  // Deprecated
341
- progressingInstruction: 7,
350
+ entityNode: 6,
351
+ // Deprecated
352
+ processingInstruction: 7,
342
353
  comment: 8,
343
- document: 9};
354
+ document: 9,
355
+ documentType: 10,
356
+ documentFragment: 11,
357
+ notation: 12 // Deprecated
358
+ };
344
359
  const getGlobal = function getGlobal() {
345
360
  return typeof window === 'undefined' ? null : window;
346
361
  };
@@ -395,10 +410,25 @@ const _createHooksMap = function _createHooksMap() {
395
410
  uponSanitizeShadowNode: []
396
411
  };
397
412
  };
413
+ /**
414
+ * Resolve a set-valued configuration option: a fresh set built from
415
+ * cfg[key] when it is an own array property (seeded with a clone of
416
+ * options.base when given, case-normalized via options.transform),
417
+ * the fallback set otherwise.
418
+ *
419
+ * @param cfg the cloned, prototype-free configuration object
420
+ * @param key the configuration property to read
421
+ * @param fallback the set to use when the option is absent or not an array
422
+ * @param options transform and optional base set to merge into
423
+ * @returns the resolved set
424
+ */
425
+ const _resolveSetOption = function _resolveSetOption(cfg, key, fallback, options) {
426
+ return objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key]) ? addToSet(options.base ? clone(options.base) : {}, cfg[key], options.transform) : fallback;
427
+ };
398
428
  function createDOMPurify() {
399
429
  let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
400
430
  const DOMPurify = root => createDOMPurify(root);
401
- DOMPurify.version = '3.4.3';
431
+ DOMPurify.version = '3.4.11';
402
432
  DOMPurify.removed = [];
403
433
  if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {
404
434
  // Not running in a browser, provide a factory function
@@ -409,15 +439,15 @@ function createDOMPurify() {
409
439
  let document = window.document;
410
440
  const originalDocument = document;
411
441
  const currentScript = originalDocument.currentScript;
412
- const DocumentFragment = window.DocumentFragment,
413
- HTMLTemplateElement = window.HTMLTemplateElement,
442
+ window.DocumentFragment;
443
+ const HTMLTemplateElement = window.HTMLTemplateElement,
414
444
  Node = window.Node,
415
445
  Element = window.Element,
416
446
  NodeFilter = window.NodeFilter,
417
- _window$NamedNodeMap = window.NamedNodeMap,
418
- NamedNodeMap = _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap,
419
- HTMLFormElement = window.HTMLFormElement,
420
- DOMParser = window.DOMParser,
447
+ _window$NamedNodeMap = window.NamedNodeMap;
448
+ _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap;
449
+ window.HTMLFormElement;
450
+ const DOMParser = window.DOMParser,
421
451
  trustedTypes = window.trustedTypes;
422
452
  const ElementPrototype = Element.prototype;
423
453
  const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
@@ -425,6 +455,10 @@ function createDOMPurify() {
425
455
  const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
426
456
  const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
427
457
  const getParentNode = lookupGetter(ElementPrototype, 'parentNode');
458
+ const getShadowRoot = lookupGetter(ElementPrototype, 'shadowRoot');
459
+ const getAttributes = lookupGetter(ElementPrototype, 'attributes');
460
+ const getNodeType = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeType') : null;
461
+ const getNodeName = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeName') : null;
428
462
  // As per issue #47, the web-components registry is inherited by a
429
463
  // new document created via createHTMLDocument. As per the spec
430
464
  // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
@@ -439,6 +473,54 @@ function createDOMPurify() {
439
473
  }
440
474
  let trustedTypesPolicy;
441
475
  let emptyHTML = '';
476
+ // The instance's own internal Trusted Types policy. Unlike a caller-supplied
477
+ // `TRUSTED_TYPES_POLICY`, this is created at most once — Trusted Types throws
478
+ // on duplicate policy names — and is the only policy allowed to persist
479
+ // across configurations and survive `clearConfig()`.
480
+ let defaultTrustedTypesPolicy;
481
+ let defaultTrustedTypesPolicyResolved = false;
482
+ // Tracks whether we are already inside a call to the configured Trusted Types
483
+ // policy (`createHTML` or `createScriptURL`). If a supplied policy callback
484
+ // itself calls `DOMPurify.sanitize` (the cause of #1422), `sanitize` would
485
+ // re-enter the policy and recurse until the stack overflows. We detect that
486
+ // re-entry and throw a clear, actionable error instead. The guard is shared
487
+ // across both callbacks, because either one re-entering `sanitize` triggers
488
+ // the same unbounded recursion.
489
+ let IN_TRUSTED_TYPES_POLICY = 0;
490
+ const _assertNotInTrustedTypesPolicy = function _assertNotInTrustedTypesPolicy() {
491
+ if (IN_TRUSTED_TYPES_POLICY > 0) {
492
+ 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.');
493
+ }
494
+ };
495
+ const _createTrustedHTML = function _createTrustedHTML(html) {
496
+ _assertNotInTrustedTypesPolicy();
497
+ IN_TRUSTED_TYPES_POLICY++;
498
+ try {
499
+ return trustedTypesPolicy.createHTML(html);
500
+ } finally {
501
+ IN_TRUSTED_TYPES_POLICY--;
502
+ }
503
+ };
504
+ const _createTrustedScriptURL = function _createTrustedScriptURL(scriptUrl) {
505
+ _assertNotInTrustedTypesPolicy();
506
+ IN_TRUSTED_TYPES_POLICY++;
507
+ try {
508
+ return trustedTypesPolicy.createScriptURL(scriptUrl);
509
+ } finally {
510
+ IN_TRUSTED_TYPES_POLICY--;
511
+ }
512
+ };
513
+ // Lazily resolve (and cache) the instance's internal default policy.
514
+ // Resolution is attempted at most once: a successful `createPolicy` cannot be
515
+ // repeated (Trusted Types throws on duplicate names), and a failed or
516
+ // unsupported attempt must not be retried on every parse.
517
+ const _getDefaultTrustedTypesPolicy = function _getDefaultTrustedTypesPolicy() {
518
+ if (!defaultTrustedTypesPolicyResolved) {
519
+ defaultTrustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
520
+ defaultTrustedTypesPolicyResolved = true;
521
+ }
522
+ return defaultTrustedTypesPolicy;
523
+ };
442
524
  const _document = document,
443
525
  implementation = _document.implementation,
444
526
  createNodeIterator = _document.createNodeIterator,
@@ -535,6 +617,13 @@ function createDOMPurify() {
535
617
  let WHOLE_DOCUMENT = false;
536
618
  /* Track whether config is already set on this instance of DOMPurify. */
537
619
  let SET_CONFIG = false;
620
+ /* Pristine allowlist bindings captured at setConfig() time. On the
621
+ * persistent-config path sanitize() restores the sets from these before
622
+ * the per-walk hook clone-guard, so a hook's in-call widening cannot
623
+ * carry across calls. Null until setConfig() is called; reset by
624
+ * clearConfig(). */
625
+ let SET_CONFIG_ALLOWED_TAGS = null;
626
+ let SET_CONFIG_ALLOWED_ATTR = null;
538
627
  /* Decide if all elements (e.g. style, script) must be children of
539
628
  * document.body. By default, browsers might move them to document.head */
540
629
  let FORCE_BODY = false;
@@ -577,7 +666,17 @@ function createDOMPurify() {
577
666
  let USE_PROFILES = {};
578
667
  /* Tags to ignore content of when KEEP_CONTENT is true */
579
668
  let FORBID_CONTENTS = null;
580
- 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']);
669
+ const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script',
670
+ // <selectedcontent> mirrors the selected <option>'s subtree, cloned by
671
+ // the UA (customizable <select>) — including any on* handlers — and the
672
+ // engine re-mirrors synchronously whenever a removal changes which
673
+ // option/selectedcontent is current, even inside DOMPurify's inert
674
+ // DOMParser document. Hoisting its children on removal re-inserts a fresh
675
+ // mirror target ahead of the walk, which the engine refills, looping
676
+ // forever (DoS) and amplifying output. Dropping its content on removal
677
+ // (rather than hoisting) breaks that cascade; the content is a duplicate
678
+ // of the option, which is sanitized on its own. See campaign-3 F1/F6.
679
+ 'selectedcontent', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
581
680
  /* Tags that are safe for data: URIs */
582
681
  let DATA_URI_TAGS = null;
583
682
  const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
@@ -593,8 +692,10 @@ function createDOMPurify() {
593
692
  /* Allowed XHTML+XML namespaces */
594
693
  let ALLOWED_NAMESPACES = null;
595
694
  const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
596
- let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
597
- let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);
695
+ const DEFAULT_MATHML_TEXT_INTEGRATION_POINTS = freeze(['mi', 'mo', 'mn', 'ms', 'mtext']);
696
+ let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS);
697
+ const DEFAULT_HTML_INTEGRATION_POINTS = freeze(['annotation-xml']);
698
+ let HTML_INTEGRATION_POINTS = addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS);
598
699
  // Certain elements are allowed in both SVG and HTML
599
700
  // namespace. We need to specify them explicitly
600
701
  // so that they don't get erroneously deleted from
@@ -636,14 +737,32 @@ function createDOMPurify() {
636
737
  // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
637
738
  transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
638
739
  /* Set configuration parameters */
639
- ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') && arrayIsArray(cfg.ALLOWED_TAGS) ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
640
- ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') && arrayIsArray(cfg.ALLOWED_ATTR) ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
641
- ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') && arrayIsArray(cfg.ALLOWED_NAMESPACES) ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
642
- URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR) ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES;
643
- DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') && arrayIsArray(cfg.ADD_DATA_URI_TAGS) ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS;
644
- FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS) ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
645
- FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') && arrayIsArray(cfg.FORBID_TAGS) ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({});
646
- FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') && arrayIsArray(cfg.FORBID_ATTR) ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({});
740
+ ALLOWED_TAGS = _resolveSetOption(cfg, 'ALLOWED_TAGS', DEFAULT_ALLOWED_TAGS, {
741
+ transform: transformCaseFunc
742
+ });
743
+ ALLOWED_ATTR = _resolveSetOption(cfg, 'ALLOWED_ATTR', DEFAULT_ALLOWED_ATTR, {
744
+ transform: transformCaseFunc
745
+ });
746
+ ALLOWED_NAMESPACES = _resolveSetOption(cfg, 'ALLOWED_NAMESPACES', DEFAULT_ALLOWED_NAMESPACES, {
747
+ transform: stringToString
748
+ });
749
+ URI_SAFE_ATTRIBUTES = _resolveSetOption(cfg, 'ADD_URI_SAFE_ATTR', DEFAULT_URI_SAFE_ATTRIBUTES, {
750
+ transform: transformCaseFunc,
751
+ base: DEFAULT_URI_SAFE_ATTRIBUTES
752
+ });
753
+ DATA_URI_TAGS = _resolveSetOption(cfg, 'ADD_DATA_URI_TAGS', DEFAULT_DATA_URI_TAGS, {
754
+ transform: transformCaseFunc,
755
+ base: DEFAULT_DATA_URI_TAGS
756
+ });
757
+ FORBID_CONTENTS = _resolveSetOption(cfg, 'FORBID_CONTENTS', DEFAULT_FORBID_CONTENTS, {
758
+ transform: transformCaseFunc
759
+ });
760
+ FORBID_TAGS = _resolveSetOption(cfg, 'FORBID_TAGS', clone({}), {
761
+ transform: transformCaseFunc
762
+ });
763
+ FORBID_ATTR = _resolveSetOption(cfg, 'FORBID_ATTR', clone({}), {
764
+ transform: transformCaseFunc
765
+ });
647
766
  USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;
648
767
  ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
649
768
  ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
@@ -662,8 +781,8 @@ function createDOMPurify() {
662
781
  IN_PLACE = cfg.IN_PLACE || false; // Default false
663
782
  IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp
664
783
  NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace
665
- MATHML_TEXT_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'MATHML_TEXT_INTEGRATION_POINTS') && cfg.MATHML_TEXT_INTEGRATION_POINTS && typeof cfg.MATHML_TEXT_INTEGRATION_POINTS === 'object' ? clone(cfg.MATHML_TEXT_INTEGRATION_POINTS) : addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']); // Default built-in map
666
- HTML_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'HTML_INTEGRATION_POINTS') && cfg.HTML_INTEGRATION_POINTS && typeof cfg.HTML_INTEGRATION_POINTS === 'object' ? clone(cfg.HTML_INTEGRATION_POINTS) : addToSet({}, ['annotation-xml']); // Default built-in map
784
+ 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
785
+ 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
667
786
  const customElementHandling = objectHasOwnProperty(cfg, 'CUSTOM_ELEMENT_HANDLING') && cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING === 'object' ? clone(cfg.CUSTOM_ELEMENT_HANDLING) : create(null);
668
787
  CUSTOM_ELEMENT_HANDLING = create(null);
669
788
  if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) {
@@ -675,6 +794,7 @@ function createDOMPurify() {
675
794
  if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') {
676
795
  CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined
677
796
  }
797
+ seal(CUSTOM_ELEMENT_HANDLING);
678
798
  if (SAFE_FOR_TEMPLATES) {
679
799
  ALLOW_DATA_ATTR = false;
680
800
  }
@@ -758,6 +878,13 @@ function createDOMPurify() {
758
878
  addToSet(ALLOWED_TAGS, ['tbody']);
759
879
  delete FORBID_TAGS.tbody;
760
880
  }
881
+ // Re-derive the active Trusted Types policy from this configuration on
882
+ // every parse. The active policy must never be sticky closure state that
883
+ // outlives the config that set it: a caller-supplied policy left in place
884
+ // after `clearConfig()` — or after a later call that supplied none, or
885
+ // `TRUSTED_TYPES_POLICY: null` — could sign a subsequent "default"
886
+ // `RETURN_TRUSTED_TYPE` result with a foreign, possibly unsafe policy.
887
+ // See GHSA-vxr8-fq34-vvx9.
761
888
  if (cfg.TRUSTED_TYPES_POLICY) {
762
889
  if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
763
890
  throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
@@ -765,18 +892,45 @@ function createDOMPurify() {
765
892
  if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
766
893
  throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
767
894
  }
768
- // Overwrite existing TrustedTypes policy.
895
+ // A caller-supplied policy applies to this configuration only.
896
+ const previousTrustedTypesPolicy = trustedTypesPolicy;
769
897
  trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
770
- // Sign local variables required by `sanitize`.
771
- emptyHTML = trustedTypesPolicy.createHTML('');
898
+ // Sign local variables required by `sanitize`. If the supplied policy's
899
+ // `createHTML` is circular (i.e. it calls `DOMPurify.sanitize`), this
900
+ // throws via the re-entrancy guard. Restore the previous policy first so
901
+ // the instance is not left in a poisoned state. See #1422.
902
+ try {
903
+ emptyHTML = _createTrustedHTML('');
904
+ } catch (error) {
905
+ trustedTypesPolicy = previousTrustedTypesPolicy;
906
+ throw error;
907
+ }
908
+ } else if (cfg.TRUSTED_TYPES_POLICY === null) {
909
+ // Explicit opt-out for this call: perform no Trusted Types signing and
910
+ // create nothing (so a strict `trusted-types` CSP that disallows a
911
+ // `dompurify` policy can still call `sanitize` from inside its own
912
+ // policy — see #1422). Resetting to `undefined` rather than a sticky
913
+ // `null` also drops any previously retained caller policy, so it cannot
914
+ // resurface on a later call, while still allowing the next config-less
915
+ // call to restore the internal default policy. See GHSA-vxr8-fq34-vvx9.
916
+ trustedTypesPolicy = undefined;
917
+ emptyHTML = '';
772
918
  } else {
773
- // Uninitialized policy, attempt to initialize the internal dompurify policy.
919
+ // No policy supplied: keep the currently active policy if one is set — a
920
+ // previously supplied policy is intentionally sticky across config-less
921
+ // calls — otherwise fall back to the instance's own internal policy,
922
+ // created at most once. (A policy supplied for a *single* call still
923
+ // lingers by design; what must not linger is a policy whose configuration
924
+ // has been torn down via `clearConfig()`, which restores the default.)
774
925
  if (trustedTypesPolicy === undefined) {
775
- trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
926
+ trustedTypesPolicy = _getDefaultTrustedTypesPolicy();
776
927
  }
777
- // If creating the internal policy succeeded sign internal variables.
778
- if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {
779
- emptyHTML = trustedTypesPolicy.createHTML('');
928
+ // Sign internal variables only when a policy is active. A falsy policy
929
+ // (Trusted Types unsupported, creation failed, or an explicit opt-out)
930
+ // leaves `emptyHTML` as a plain string, so we never call `.createHTML` on
931
+ // a non-policy and throw. See #1422.
932
+ if (trustedTypesPolicy && typeof emptyHTML === 'string') {
933
+ emptyHTML = _createTrustedHTML('');
780
934
  }
781
935
  }
782
936
  // Prevent further manipulation of configuration.
@@ -791,6 +945,77 @@ function createDOMPurify() {
791
945
  * correctly. */
792
946
  const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
793
947
  const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
948
+ /**
949
+ * Namespace rules for an element in the SVG namespace.
950
+ *
951
+ * @param tagName the element's lowercase tag name
952
+ * @param parent the (possibly simulated) parent node
953
+ * @param parentTagName the parent's lowercase tag name
954
+ * @returns true if a spec-compliant parser could produce this element
955
+ */
956
+ const _checkSvgNamespace = function _checkSvgNamespace(tagName, parent, parentTagName) {
957
+ // The only way to switch from HTML namespace to SVG
958
+ // is via <svg>. If it happens via any other tag, then
959
+ // it should be killed.
960
+ if (parent.namespaceURI === HTML_NAMESPACE) {
961
+ return tagName === 'svg';
962
+ }
963
+ // The only way to switch from MathML to SVG is via <svg>
964
+ // if the parent is either <annotation-xml> or a MathML
965
+ // text integration point.
966
+ if (parent.namespaceURI === MATHML_NAMESPACE) {
967
+ return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
968
+ }
969
+ // We only allow elements that are defined in SVG
970
+ // spec. All others are disallowed in SVG namespace.
971
+ return Boolean(ALL_SVG_TAGS[tagName]);
972
+ };
973
+ /**
974
+ * Namespace rules for an element in the MathML namespace.
975
+ *
976
+ * @param tagName the element's lowercase tag name
977
+ * @param parent the (possibly simulated) parent node
978
+ * @param parentTagName the parent's lowercase tag name
979
+ * @returns true if a spec-compliant parser could produce this element
980
+ */
981
+ const _checkMathMlNamespace = function _checkMathMlNamespace(tagName, parent, parentTagName) {
982
+ // The only way to switch from HTML namespace to MathML
983
+ // is via <math>. If it happens via any other tag, then
984
+ // it should be killed.
985
+ if (parent.namespaceURI === HTML_NAMESPACE) {
986
+ return tagName === 'math';
987
+ }
988
+ // The only way to switch from SVG to MathML is via
989
+ // <math> and HTML integration points
990
+ if (parent.namespaceURI === SVG_NAMESPACE) {
991
+ return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
992
+ }
993
+ // We only allow elements that are defined in MathML
994
+ // spec. All others are disallowed in MathML namespace.
995
+ return Boolean(ALL_MATHML_TAGS[tagName]);
996
+ };
997
+ /**
998
+ * Namespace rules for an element in the HTML namespace.
999
+ *
1000
+ * @param tagName the element's lowercase tag name
1001
+ * @param parent the (possibly simulated) parent node
1002
+ * @param parentTagName the parent's lowercase tag name
1003
+ * @returns true if a spec-compliant parser could produce this element
1004
+ */
1005
+ const _checkHtmlNamespace = function _checkHtmlNamespace(tagName, parent, parentTagName) {
1006
+ // The only way to switch from SVG to HTML is via
1007
+ // HTML integration points, and from MathML to HTML
1008
+ // is via MathML text integration points
1009
+ if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
1010
+ return false;
1011
+ }
1012
+ if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
1013
+ return false;
1014
+ }
1015
+ // We disallow tags that are specific for MathML
1016
+ // or SVG and should never appear in HTML namespace
1017
+ return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
1018
+ };
794
1019
  /**
795
1020
  * @param element a DOM element whose namespace is being checked
796
1021
  * @returns Return false if the element has a
@@ -813,51 +1038,13 @@ function createDOMPurify() {
813
1038
  return false;
814
1039
  }
815
1040
  if (element.namespaceURI === SVG_NAMESPACE) {
816
- // The only way to switch from HTML namespace to SVG
817
- // is via <svg>. If it happens via any other tag, then
818
- // it should be killed.
819
- if (parent.namespaceURI === HTML_NAMESPACE) {
820
- return tagName === 'svg';
821
- }
822
- // The only way to switch from MathML to SVG is via`
823
- // svg if parent is either <annotation-xml> or MathML
824
- // text integration points.
825
- if (parent.namespaceURI === MATHML_NAMESPACE) {
826
- return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
827
- }
828
- // We only allow elements that are defined in SVG
829
- // spec. All others are disallowed in SVG namespace.
830
- return Boolean(ALL_SVG_TAGS[tagName]);
1041
+ return _checkSvgNamespace(tagName, parent, parentTagName);
831
1042
  }
832
1043
  if (element.namespaceURI === MATHML_NAMESPACE) {
833
- // The only way to switch from HTML namespace to MathML
834
- // is via <math>. If it happens via any other tag, then
835
- // it should be killed.
836
- if (parent.namespaceURI === HTML_NAMESPACE) {
837
- return tagName === 'math';
838
- }
839
- // The only way to switch from SVG to MathML is via
840
- // <math> and HTML integration points
841
- if (parent.namespaceURI === SVG_NAMESPACE) {
842
- return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
843
- }
844
- // We only allow elements that are defined in MathML
845
- // spec. All others are disallowed in MathML namespace.
846
- return Boolean(ALL_MATHML_TAGS[tagName]);
1044
+ return _checkMathMlNamespace(tagName, parent, parentTagName);
847
1045
  }
848
1046
  if (element.namespaceURI === HTML_NAMESPACE) {
849
- // The only way to switch from SVG to HTML is via
850
- // HTML integration points, and from MathML to HTML
851
- // is via MathML text integration points
852
- if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
853
- return false;
854
- }
855
- if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
856
- return false;
857
- }
858
- // We disallow tags that are specific for MathML
859
- // or SVG and should never appear in HTML namespace
860
- return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
1047
+ return _checkHtmlNamespace(tagName, parent, parentTagName);
861
1048
  }
862
1049
  // For XHTML and XML documents that support custom namespaces
863
1050
  if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
@@ -882,7 +1069,74 @@ function createDOMPurify() {
882
1069
  // eslint-disable-next-line unicorn/prefer-dom-node-remove
883
1070
  getParentNode(node).removeChild(node);
884
1071
  } catch (_) {
1072
+ /* The normal detach failed — this is reached for a parentless node
1073
+ (getParentNode() is null, so .removeChild throws). Element.prototype
1074
+ .remove() is itself a spec no-op on a parentless node, so a recorded
1075
+ "removal" would otherwise hand the caller back an intact,
1076
+ payload-bearing node (e.g. a detached IN_PLACE root the mXSS canary or
1077
+ the style-with-element-child rule decided to kill). Fail closed by
1078
+ throwing — exactly as a clobbered root does at the IN_PLACE entry —
1079
+ rather than trying to "neutralize" the node via its own methods.
1080
+ Neutralizing would mean calling getAttributeNames()/removeAttribute()
1081
+ on the node, both of which a <form> root can clobber via a named child
1082
+ (and _isClobbered does not even probe getAttributeNames), so the
1083
+ neutralize step could itself be silently defeated, leaving the payload
1084
+ intact. A throw touches only the cached, clobber-safe remove() and
1085
+ getParentNode(). Generalizes GHSA-r47g-fvhr-h676 (clobbered-form root)
1086
+ to every root-kill reason. REPORT-3.
1087
+ This lives inside the catch, so it never fires for a normally-removed
1088
+ in-tree node: those have a parent, removeChild() succeeds, and the
1089
+ catch is not entered. Only a kept (parentless) root reaches here. */
885
1090
  remove(node);
1091
+ if (!getParentNode(node)) {
1092
+ throw typeErrorCreate('a node selected for removal could not be detached from its tree ' + 'and cannot be safely returned; refusing to sanitize in place');
1093
+ }
1094
+ }
1095
+ };
1096
+ /**
1097
+ * _neutralizeRoot
1098
+ *
1099
+ * Fail-closed teardown of an in-place root after the sanitize walk aborts
1100
+ * (campaign-3 F2). An internal throw mid-walk — e.g. a page-registered
1101
+ * custom element's reaction detaches a node so `_forceRemove`'s deliberate
1102
+ * parentless guard throws, or any other re-entrant engine mutation — would
1103
+ * otherwise leave the caller's *live* tree half-sanitized, with everything
1104
+ * after the abort point still carrying its handlers. There is no safe way
1105
+ * to resume the walk (the tree mutated under us), so we strip the root bare:
1106
+ * remove every child and every attribute, then let the caller's catch see
1107
+ * the original error. Clobber-safe (cached `remove`/`childNodes`/`attributes`
1108
+ * getters; the root was already clobber-pre-flighted at the IN_PLACE entry).
1109
+ *
1110
+ * @param root the in-place root to empty
1111
+ */
1112
+ const _neutralizeRoot = function _neutralizeRoot(root) {
1113
+ const childNodes = getChildNodes(root);
1114
+ if (childNodes) {
1115
+ const snapshot = [];
1116
+ arrayForEach(childNodes, child => {
1117
+ arrayPush(snapshot, child);
1118
+ });
1119
+ arrayForEach(snapshot, child => {
1120
+ try {
1121
+ remove(child);
1122
+ } catch (_) {
1123
+ /* Best-effort teardown; a still-attached child is handled below */
1124
+ }
1125
+ });
1126
+ }
1127
+ const attributes = getAttributes(root);
1128
+ if (attributes) {
1129
+ for (let i = attributes.length - 1; i >= 0; --i) {
1130
+ const attribute = attributes[i];
1131
+ const name = attribute && attribute.name;
1132
+ if (typeof name === 'string') {
1133
+ try {
1134
+ root.removeAttribute(name);
1135
+ } catch (_) {
1136
+ /* Clobbered removeAttribute — ignore (fail-closed best effort) */
1137
+ }
1138
+ }
1139
+ }
886
1140
  }
887
1141
  };
888
1142
  /**
@@ -917,6 +1171,72 @@ function createDOMPurify() {
917
1171
  }
918
1172
  }
919
1173
  };
1174
+ /**
1175
+ * _stripDisallowedAttributes
1176
+ *
1177
+ * Removes every attribute the active configuration does not allow from a
1178
+ * single element, using the same allowlist as the main attribute pass (so
1179
+ * `on*` handlers go, but no `/^on/` blocklist is introduced). Used only to
1180
+ * neutralise nodes that are being discarded from an in-place tree.
1181
+ *
1182
+ * @param element the element to strip
1183
+ */
1184
+ const _stripDisallowedAttributes = function _stripDisallowedAttributes(element) {
1185
+ const attributes = getAttributes(element);
1186
+ if (!attributes) {
1187
+ return;
1188
+ }
1189
+ for (let i = attributes.length - 1; i >= 0; --i) {
1190
+ const attribute = attributes[i];
1191
+ const name = attribute && attribute.name;
1192
+ if (typeof name !== 'string' || ALLOWED_ATTR[transformCaseFunc(name)]) {
1193
+ continue;
1194
+ }
1195
+ try {
1196
+ element.removeAttribute(name);
1197
+ } catch (_) {
1198
+ /* Clobbered removeAttribute on a doomed node — ignore */
1199
+ }
1200
+ }
1201
+ };
1202
+ /**
1203
+ * _neutralizeSubtree
1204
+ *
1205
+ * Completes the audit-5 F1 fix across every removal path. The KEEP_CONTENT
1206
+ * move-hoist neutralises only disallowed-tag removals; clobber, mXSS-canary,
1207
+ * namespace, comment, processing-instruction and KEEP_CONTENT:false removals
1208
+ * all drop their subtree wholesale via `_forceRemove`. On the IN_PLACE path
1209
+ * those dropped nodes are detached from the caller's LIVE tree but a
1210
+ * handler-bearing original among them (an `<img onerror>`/`<video>` that was
1211
+ * loading) keeps its queued resource event, which fires in page scope after
1212
+ * sanitize returns. This walks a removed subtree and strips every attribute
1213
+ * the active configuration does not allow — so `on*` handlers are cancelled
1214
+ * through the SAME allowlist that governs kept nodes, not a separate `/^on/`
1215
+ * blocklist. Run synchronously before sanitize returns, i.e. before any
1216
+ * queued event can fire. Hook-free by design: these nodes leave the output,
1217
+ * so firing attribute hooks for them would be surprising. Clobber-safe reads;
1218
+ * a doomed clobbered node may shadow `removeAttribute` (its own attributes are
1219
+ * irrelevant — it is discarded — while its non-clobbered descendants, e.g.
1220
+ * the `<img>`, are reached and scrubbed).
1221
+ *
1222
+ * @param root the root of a removed subtree to neutralise
1223
+ */
1224
+ const _neutralizeSubtree = function _neutralizeSubtree(root) {
1225
+ const stack = [root];
1226
+ while (stack.length > 0) {
1227
+ const node = stack.pop();
1228
+ const nodeType = getNodeType ? getNodeType(node) : node.nodeType;
1229
+ if (nodeType === NODE_TYPE.element) {
1230
+ _stripDisallowedAttributes(node);
1231
+ }
1232
+ const childNodes = getChildNodes(node);
1233
+ if (childNodes) {
1234
+ for (let i = childNodes.length - 1; i >= 0; --i) {
1235
+ stack.push(childNodes[i]);
1236
+ }
1237
+ }
1238
+ }
1239
+ };
920
1240
  /**
921
1241
  * _initDocument
922
1242
  *
@@ -938,7 +1258,7 @@ function createDOMPurify() {
938
1258
  // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
939
1259
  dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
940
1260
  }
941
- const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
1261
+ const dirtyPayload = trustedTypesPolicy ? _createTrustedHTML(dirty) : dirty;
942
1262
  /*
943
1263
  * Use the DOMParser API by default, fallback later if needs be
944
1264
  * DOMParser not work for svg when has multiple root element.
@@ -978,29 +1298,254 @@ function createDOMPurify() {
978
1298
  // eslint-disable-next-line no-bitwise
979
1299
  NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
980
1300
  };
1301
+ /**
1302
+ * Replace template expression syntax (mustache, ERB, template
1303
+ * literal) with a space; shared by all SAFE_FOR_TEMPLATES scrub
1304
+ * sites. Order matters: mustache, then ERB, then template literal.
1305
+ *
1306
+ * @param value the string to scrub
1307
+ * @returns the scrubbed string
1308
+ */
1309
+ const _stripTemplateExpressions = function _stripTemplateExpressions(value) {
1310
+ value = stringReplace(value, MUSTACHE_EXPR$1, ' ');
1311
+ value = stringReplace(value, ERB_EXPR$1, ' ');
1312
+ value = stringReplace(value, TMPLIT_EXPR$1, ' ');
1313
+ return value;
1314
+ };
1315
+ /**
1316
+ * Strip template-engine expressions ({{...}}, ${...}, <%...%>) from the
1317
+ * character data of an element subtree. Used as the final safety net for
1318
+ * SAFE_FOR_TEMPLATES on every DOM-returning code path so that expressions
1319
+ * which only form after text-node normalization (e.g. fragments split across
1320
+ * stripped elements) cannot survive into a template-evaluating framework.
1321
+ *
1322
+ * Walks text/comment/CDATA/processing-instruction nodes and mutates `.data`
1323
+ * in place rather than round-tripping through innerHTML. This preserves
1324
+ * descendant node references (important for IN_PLACE callers), avoids a
1325
+ * serialize/reparse cycle, and reads literal character data — which means
1326
+ * `<%...%>` in text content matches the ERB regex against its real bytes
1327
+ * instead of the HTML-entity-escaped form innerHTML would produce.
1328
+ *
1329
+ * Attribute values are not visited here; SAFE_FOR_TEMPLATES handling for
1330
+ * attributes is performed during the per-node `_sanitizeAttributes` pass.
1331
+ *
1332
+ * @param node The root element whose character data should be scrubbed.
1333
+ */
1334
+ const _scrubTemplateExpressions2 = function _scrubTemplateExpressions(node) {
1335
+ var _node$querySelectorAl;
1336
+ node.normalize();
1337
+ const walker = createNodeIterator.call(node.ownerDocument || node, node,
1338
+ // eslint-disable-next-line no-bitwise
1339
+ NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_CDATA_SECTION | NodeFilter.SHOW_PROCESSING_INSTRUCTION, null);
1340
+ let currentNode = walker.nextNode();
1341
+ while (currentNode) {
1342
+ currentNode.data = _stripTemplateExpressions(currentNode.data);
1343
+ currentNode = walker.nextNode();
1344
+ }
1345
+ // NodeIterator does not descend into <template>.content per the DOM spec,
1346
+ // so we must explicitly recurse into each template's content fragment,
1347
+ // mirroring the approach used by _sanitizeShadowDOM.
1348
+ const templates = (_node$querySelectorAl = node.querySelectorAll) === null || _node$querySelectorAl === void 0 ? void 0 : _node$querySelectorAl.call(node, 'template');
1349
+ if (templates) {
1350
+ arrayForEach(templates, tmpl => {
1351
+ if (_isDocumentFragment(tmpl.content)) {
1352
+ _scrubTemplateExpressions2(tmpl.content);
1353
+ }
1354
+ });
1355
+ }
1356
+ };
981
1357
  /**
982
1358
  * _isClobbered
983
1359
  *
1360
+ * Detect DOM-clobbering on HTMLFormElement nodes. Form is the only HTML
1361
+ * interface with [LegacyOverrideBuiltIns]; a descendant element with a
1362
+ * `name` attribute matching a prototype property shadows that property
1363
+ * on direct reads. We use this check at the IN_PLACE entry-point and
1364
+ * during attribute sanitization to refuse clobbered forms.
1365
+ *
984
1366
  * @param element element to check for clobbering attacks
985
1367
  * @return true if clobbered, false if safe
986
1368
  */
987
1369
  const _isClobbered = function _isClobbered(element) {
988
- 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');
1370
+ // Realm-independent tag-name probe. If we can't determine the tag
1371
+ // name at all, we can't reason about clobbering — return false
1372
+ // (the caller's other defences still apply).
1373
+ const realTagName = getNodeName ? getNodeName(element) : null;
1374
+ if (typeof realTagName !== 'string') {
1375
+ return false;
1376
+ }
1377
+ if (transformCaseFunc(realTagName) !== 'form') {
1378
+ return false;
1379
+ }
1380
+ return typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' ||
1381
+ // Realm-safe NamedNodeMap detection: equality against the cached
1382
+ // prototype getter. Clobbered .attributes (e.g. <input name="attributes">)
1383
+ // makes the direct read diverge from the cached read; a clean form
1384
+ // (same-realm OR foreign-realm) has both reads pointing at the same
1385
+ // canonical NamedNodeMap.
1386
+ element.attributes !== getAttributes(element) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function' ||
1387
+ // NodeType clobbering probe. Cached Node.prototype.nodeType getter
1388
+ // returns the integer 1 for any Element regardless of realm; direct
1389
+ // read on a clobbered form (e.g. <input name="nodeType">) returns
1390
+ // the named child element. Cheap addition — nodeType is read from
1391
+ // an internal slot, no serialization cost — and removes a residual
1392
+ // clobbering surface used by several mXSS / PI / comment branches
1393
+ // in _sanitizeElements that compare currentNode.nodeType directly.
1394
+ element.nodeType !== getNodeType(element) ||
1395
+ // HTMLFormElement has [LegacyOverrideBuiltIns]: a descendant named
1396
+ // "childNodes" shadows the prototype getter. Direct reads of
1397
+ // form.childNodes from a clobbered form return the named child
1398
+ // instead of the real NodeList, so any walk that reads it directly
1399
+ // skips the form's real children. Compare the direct read to the
1400
+ // cached Node.prototype getter — when the form's named-property
1401
+ // getter intercepts the read, the two values differ and we flag
1402
+ // the form. This catches every clobbering child type (input,
1403
+ // select, etc.) regardless of whether the named child happens to
1404
+ // carry a numeric .length, which a typeof-based probe would miss
1405
+ // (e.g. HTMLSelectElement.length is a defined unsigned-long).
1406
+ element.childNodes !== getChildNodes(element);
1407
+ };
1408
+ /**
1409
+ * Checks whether the given value is a DocumentFragment from any realm.
1410
+ *
1411
+ * The realm-independent replacement reads `nodeType` through the cached
1412
+ * Node.prototype getter and compares to the DOCUMENT_FRAGMENT_NODE
1413
+ * constant (11). nodeType is a numeric value resolved from the node's
1414
+ * internal slot, identical across realms for the same kind of node.
1415
+ *
1416
+ * @param value object to check
1417
+ * @return true if value is a DocumentFragment-shaped node from any realm
1418
+ */
1419
+ const _isDocumentFragment = function _isDocumentFragment(value) {
1420
+ if (!getNodeType || typeof value !== 'object' || value === null) {
1421
+ return false;
1422
+ }
1423
+ try {
1424
+ return getNodeType(value) === NODE_TYPE.documentFragment;
1425
+ } catch (_) {
1426
+ return false;
1427
+ }
989
1428
  };
990
1429
  /**
991
- * Checks whether the given object is a DOM node.
1430
+ * Checks whether the given object is a DOM node, including nodes that
1431
+ * originate from a different window/realm (e.g. an iframe's
1432
+ * contentDocument). The previous `value instanceof Node` check was
1433
+ * realm-bound: nodes from a different window failed it, causing
1434
+ * sanitize() to silently stringify them and reset IN_PLACE to false,
1435
+ * returning the original node unsanitized. See GHSA-4w3q-35jp-p934.
992
1436
  *
993
1437
  * @param value object to check whether it's a DOM node
994
- * @return true is object is a DOM node
1438
+ * @return true if value is a DOM node from any realm
995
1439
  */
996
1440
  const _isNode = function _isNode(value) {
997
- return typeof Node === 'function' && value instanceof Node;
1441
+ if (!getNodeType || typeof value !== 'object' || value === null) {
1442
+ return false;
1443
+ }
1444
+ try {
1445
+ return typeof getNodeType(value) === 'number';
1446
+ } catch (_) {
1447
+ return false;
1448
+ }
998
1449
  };
999
1450
  function _executeHooks(hooks, currentNode, data) {
1451
+ if (hooks.length === 0) {
1452
+ return;
1453
+ }
1000
1454
  arrayForEach(hooks, hook => {
1001
1455
  hook.call(DOMPurify, currentNode, data, CONFIG);
1002
1456
  });
1003
1457
  }
1458
+ /**
1459
+ * Structural-threat checks that condemn a node regardless of the
1460
+ * allowlists: mXSS via namespace confusion, risky CSS construction,
1461
+ * processing instructions, markup-bearing comments. Pure predicate;
1462
+ * the caller removes. Check order is load-bearing.
1463
+ *
1464
+ * @param currentNode the node to inspect
1465
+ * @param tagName the node's transformCaseFunc'd tag name
1466
+ * @return true if the node must be removed
1467
+ */
1468
+ const _isUnsafeNode = function _isUnsafeNode(currentNode, tagName) {
1469
+ /* Detect mXSS attempts abusing namespace confusion */
1470
+ if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.textContent) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.innerHTML)) {
1471
+ return true;
1472
+ }
1473
+ /* Remove risky CSS construction leading to mXSS */
1474
+ if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {
1475
+ return true;
1476
+ }
1477
+ /* Remove any occurrence of processing instructions */
1478
+ if (currentNode.nodeType === NODE_TYPE.processingInstruction) {
1479
+ return true;
1480
+ }
1481
+ /* Remove any kind of possibly harmful comments */
1482
+ if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, currentNode.data)) {
1483
+ return true;
1484
+ }
1485
+ return false;
1486
+ };
1487
+ /**
1488
+ * Handle a node whose tag is forbidden or not allowlisted: keep
1489
+ * allowed custom elements (false return exits _sanitizeElements
1490
+ * early - namespace/fallback checks and the afterSanitizeElements
1491
+ * hook are intentionally skipped for kept custom elements), else
1492
+ * hoist content per KEEP_CONTENT and remove.
1493
+ *
1494
+ * @param currentNode the disallowed node
1495
+ * @param tagName the node's transformCaseFunc'd tag name
1496
+ * @return true if the node was removed, false if kept
1497
+ */
1498
+ const _sanitizeDisallowedNode = function _sanitizeDisallowedNode(currentNode, tagName) {
1499
+ /* Check if we have a custom element to handle */
1500
+ if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
1501
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
1502
+ return false;
1503
+ }
1504
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
1505
+ return false;
1506
+ }
1507
+ }
1508
+ /* Keep content except for bad-listed elements.
1509
+ Use the cached prototype getters exclusively — the previous code
1510
+ had `|| currentNode.parentNode` / `|| currentNode.childNodes`
1511
+ fallbacks, but the cached getters always return the canonical
1512
+ value (or null for a real parent-less node), so the fallback
1513
+ path was dead in safe cases and a clobbering surface in unsafe
1514
+ ones. Falsy cached results stay falsy; the `if (childNodes &&
1515
+ parentNode)` check already gates correctly. */
1516
+ if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
1517
+ const parentNode = getParentNode(currentNode);
1518
+ const childNodes = getChildNodes(currentNode);
1519
+ if (childNodes && parentNode) {
1520
+ const childCount = childNodes.length;
1521
+ /* In-place: hoist the *original* children so the iterator visits
1522
+ and sanitises them through the same allowlist pass as every other
1523
+ node. The caller built the tree in the live document, so the
1524
+ originals carry already-queued resource events (`<img onerror>`,
1525
+ `<video>`/`<audio>` error, lazy/`onload`, …); cloning would leave
1526
+ those originals detached but still armed, firing in page scope
1527
+ while the returned tree looked clean. Moving is safe in-place: the
1528
+ root is pre-validated as an allowed tag and so is never the node
1529
+ being removed, which keeps `parentNode` inside the iterator root
1530
+ and the relocated child inside the serialised tree.
1531
+ Otherwise (string / DOM-copy paths): clone. The iterator is rooted
1532
+ at — and the result serialised from — `body`, so a restrictive
1533
+ ALLOWED_TAGS that removes `body` itself must leave its content in
1534
+ place, which only cloning does; and those paths parse into an
1535
+ inert document, so their discarded originals never had a queued
1536
+ event to neutralise.
1537
+ `childNodes` is live; a tail-to-head walk keeps `childNodes[i]`
1538
+ valid whether we move (drops the trailing entry) or clone (leaves
1539
+ the list intact). */
1540
+ for (let i = childCount - 1; i >= 0; --i) {
1541
+ const hoisted = IN_PLACE ? childNodes[i] : cloneNode(childNodes[i], true);
1542
+ parentNode.insertBefore(hoisted, getNextSibling(currentNode));
1543
+ }
1544
+ }
1545
+ }
1546
+ _forceRemove(currentNode);
1547
+ return true;
1548
+ };
1004
1549
  /**
1005
1550
  * _sanitizeElements
1006
1551
  *
@@ -1011,7 +1556,6 @@ function createDOMPurify() {
1011
1556
  * @return true if node was killed, false if left alive
1012
1557
  */
1013
1558
  const _sanitizeElements = function _sanitizeElements(currentNode) {
1014
- let content = null;
1015
1559
  /* Execute a hook if present */
1016
1560
  _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
1017
1561
  /* Check if element is clobbered or can clobber */
@@ -1020,75 +1564,41 @@ function createDOMPurify() {
1020
1564
  return true;
1021
1565
  }
1022
1566
  /* Now let's check the element's type and name */
1023
- const tagName = transformCaseFunc(currentNode.nodeName);
1567
+ const tagName = transformCaseFunc(getNodeName ? getNodeName(currentNode) : currentNode.nodeName);
1024
1568
  /* Execute a hook if present */
1025
1569
  _executeHooks(hooks.uponSanitizeElement, currentNode, {
1026
1570
  tagName,
1027
1571
  allowedTags: ALLOWED_TAGS
1028
1572
  });
1029
- /* Detect mXSS attempts abusing namespace confusion */
1030
- if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) {
1031
- _forceRemove(currentNode);
1032
- return true;
1033
- }
1034
- /* Remove risky CSS construction leading to mXSS */
1035
- if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {
1036
- _forceRemove(currentNode);
1037
- return true;
1038
- }
1039
- /* Remove any occurrence of processing instructions */
1040
- if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {
1041
- _forceRemove(currentNode);
1042
- return true;
1043
- }
1044
- /* Remove any kind of possibly harmful comments */
1045
- if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) {
1573
+ /* Remove mXSS vectors, processing instructions and risky comments */
1574
+ if (_isUnsafeNode(currentNode, tagName)) {
1046
1575
  _forceRemove(currentNode);
1047
1576
  return true;
1048
1577
  }
1049
1578
  /* Remove element if anything forbids its presence */
1050
1579
  if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) {
1051
- /* Check if we have a custom element to handle */
1052
- if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
1053
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
1054
- return false;
1055
- }
1056
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
1057
- return false;
1058
- }
1059
- }
1060
- /* Keep content except for bad-listed elements */
1061
- if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
1062
- const parentNode = getParentNode(currentNode) || currentNode.parentNode;
1063
- const childNodes = getChildNodes(currentNode) || currentNode.childNodes;
1064
- if (childNodes && parentNode) {
1065
- const childCount = childNodes.length;
1066
- for (let i = childCount - 1; i >= 0; --i) {
1067
- const childClone = cloneNode(childNodes[i], true);
1068
- parentNode.insertBefore(childClone, getNextSibling(currentNode));
1069
- }
1070
- }
1071
- }
1072
- _forceRemove(currentNode);
1073
- return true;
1074
- }
1075
- /* Check whether element has a valid namespace */
1076
- if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
1580
+ return _sanitizeDisallowedNode(currentNode, tagName);
1581
+ }
1582
+ /* Check whether element has a valid namespace.
1583
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): use the cached Node.prototype
1584
+ nodeType getter rather than `instanceof Element`, which is realm-
1585
+ bound and short-circuits to false for any node minted in a different
1586
+ realm — letting a foreign-realm element with a forbidden namespace
1587
+ slip past the namespace check entirely. */
1588
+ const nt = getNodeType ? getNodeType(currentNode) : currentNode.nodeType;
1589
+ if (nt === NODE_TYPE.element && !_checkValidNamespace(currentNode)) {
1077
1590
  _forceRemove(currentNode);
1078
1591
  return true;
1079
1592
  }
1080
1593
  /* Make sure that older browsers don't get fallback-tag mXSS */
1081
- if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {
1594
+ if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(FALLBACK_TAG_CLOSE, currentNode.innerHTML)) {
1082
1595
  _forceRemove(currentNode);
1083
1596
  return true;
1084
1597
  }
1085
1598
  /* Sanitize element content to be template-safe */
1086
1599
  if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
1087
1600
  /* Get the element's text content */
1088
- content = currentNode.textContent;
1089
- arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => {
1090
- content = stringReplace(content, expr, ' ');
1091
- });
1601
+ const content = _stripTemplateExpressions(currentNode.textContent);
1092
1602
  if (currentNode.textContent !== content) {
1093
1603
  arrayPush(DOMPurify.removed, {
1094
1604
  element: currentNode.cloneNode()
@@ -1123,7 +1633,7 @@ function createDOMPurify() {
1123
1633
  (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
1124
1634
  XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
1125
1635
  We don't need to check the value; it's always URI safe. */
1126
- if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) ; else if (!nameIsPermitted || FORBID_ATTR[lcName]) {
1636
+ if (ALLOW_DATA_ATTR && regExpTest(DATA_ATTR$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) ; else if (!nameIsPermitted) {
1127
1637
  if (
1128
1638
  // First condition does a very basic check if a) it's basically a valid custom element tagname AND
1129
1639
  // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
@@ -1155,6 +1665,63 @@ function createDOMPurify() {
1155
1665
  const _isBasicCustomElement = function _isBasicCustomElement(tagName) {
1156
1666
  return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT$1, tagName);
1157
1667
  };
1668
+ /**
1669
+ * Wrap an attribute value in the matching Trusted Types object when
1670
+ * the active policy requires it. Namespaced attributes pass through
1671
+ * unchanged (no TT support yet, see
1672
+ * https://bugs.chromium.org/p/chromium/issues/detail?id=1305293).
1673
+ *
1674
+ * @param lcTag lowercase tag name of the containing element
1675
+ * @param lcName lowercase attribute name
1676
+ * @param namespaceURI the attribute's namespace, if any
1677
+ * @param value the attribute value to wrap
1678
+ * @return the value, wrapped when Trusted Types demand it
1679
+ */
1680
+ const _applyTrustedTypesToAttribute = function _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value) {
1681
+ if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function' && !namespaceURI) {
1682
+ switch (trustedTypes.getAttributeType(lcTag, lcName)) {
1683
+ case 'TrustedHTML':
1684
+ {
1685
+ return _createTrustedHTML(value);
1686
+ }
1687
+ case 'TrustedScriptURL':
1688
+ {
1689
+ return _createTrustedScriptURL(value);
1690
+ }
1691
+ }
1692
+ }
1693
+ return value;
1694
+ };
1695
+ /**
1696
+ * Write a modified attribute value back onto the element. On
1697
+ * success, re-probe for clobbering introduced by the new value and
1698
+ * remove the element when found; otherwise pop the removal entry
1699
+ * recorded by the earlier _removeAttribute (long-standing pairing
1700
+ * with the SANITIZE_NAMED_PROPS path - do not "fix" casually). On
1701
+ * failure, remove the attribute instead.
1702
+ *
1703
+ * @param currentNode the element carrying the attribute
1704
+ * @param name the attribute name as present on the element
1705
+ * @param namespaceURI the attribute's namespace, if any
1706
+ * @param value the new attribute value
1707
+ */
1708
+ const _setAttributeValue = function _setAttributeValue(currentNode, name, namespaceURI, value) {
1709
+ try {
1710
+ if (namespaceURI) {
1711
+ currentNode.setAttributeNS(namespaceURI, name, value);
1712
+ } else {
1713
+ /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
1714
+ currentNode.setAttribute(name, value);
1715
+ }
1716
+ if (_isClobbered(currentNode)) {
1717
+ _forceRemove(currentNode);
1718
+ } else {
1719
+ arrayPop(DOMPurify.removed);
1720
+ }
1721
+ } catch (_) {
1722
+ _removeAttribute(name, currentNode);
1723
+ }
1724
+ };
1158
1725
  /**
1159
1726
  * _sanitizeAttributes
1160
1727
  *
@@ -1181,6 +1748,7 @@ function createDOMPurify() {
1181
1748
  forceKeepAttr: undefined
1182
1749
  };
1183
1750
  let l = attributes.length;
1751
+ const lcTag = transformCaseFunc(currentNode.nodeName);
1184
1752
  /* Go backwards over all attributes; safely remove bad ones */
1185
1753
  while (l--) {
1186
1754
  const attr = attributes[l];
@@ -1218,7 +1786,7 @@ function createDOMPurify() {
1218
1786
  _removeAttribute(name, currentNode);
1219
1787
  continue;
1220
1788
  }
1221
- /* Did the hooks approve of the attribute? */
1789
+ /* Did the hooks force-keep the attribute? */
1222
1790
  if (hookEvent.forceKeepAttr) {
1223
1791
  continue;
1224
1792
  }
@@ -1228,56 +1796,24 @@ function createDOMPurify() {
1228
1796
  continue;
1229
1797
  }
1230
1798
  /* Work around a security issue in jQuery 3.0 */
1231
- if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
1799
+ if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(SELF_CLOSING_TAG, value)) {
1232
1800
  _removeAttribute(name, currentNode);
1233
1801
  continue;
1234
1802
  }
1235
1803
  /* Sanitize attribute content to be template-safe */
1236
1804
  if (SAFE_FOR_TEMPLATES) {
1237
- arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => {
1238
- value = stringReplace(value, expr, ' ');
1239
- });
1805
+ value = _stripTemplateExpressions(value);
1240
1806
  }
1241
1807
  /* Is `value` valid for this attribute? */
1242
- const lcTag = transformCaseFunc(currentNode.nodeName);
1243
1808
  if (!_isValidAttribute(lcTag, lcName, value)) {
1244
1809
  _removeAttribute(name, currentNode);
1245
1810
  continue;
1246
1811
  }
1247
1812
  /* Handle attributes that require Trusted Types */
1248
- if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {
1249
- if (namespaceURI) ; else {
1250
- switch (trustedTypes.getAttributeType(lcTag, lcName)) {
1251
- case 'TrustedHTML':
1252
- {
1253
- value = trustedTypesPolicy.createHTML(value);
1254
- break;
1255
- }
1256
- case 'TrustedScriptURL':
1257
- {
1258
- value = trustedTypesPolicy.createScriptURL(value);
1259
- break;
1260
- }
1261
- }
1262
- }
1263
- }
1813
+ value = _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value);
1264
1814
  /* Handle invalid data-* attribute set by try-catching it */
1265
1815
  if (value !== initValue) {
1266
- try {
1267
- if (namespaceURI) {
1268
- currentNode.setAttributeNS(namespaceURI, name, value);
1269
- } else {
1270
- /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
1271
- currentNode.setAttribute(name, value);
1272
- }
1273
- if (_isClobbered(currentNode)) {
1274
- _forceRemove(currentNode);
1275
- } else {
1276
- arrayPop(DOMPurify.removed);
1277
- }
1278
- } catch (_) {
1279
- _removeAttribute(name, currentNode);
1280
- }
1816
+ _setAttributeValue(currentNode, name, namespaceURI, value);
1281
1817
  }
1282
1818
  }
1283
1819
  /* Execute a hook if present */
@@ -1300,10 +1836,31 @@ function createDOMPurify() {
1300
1836
  _sanitizeElements(shadowNode);
1301
1837
  /* Check attributes next */
1302
1838
  _sanitizeAttributes(shadowNode);
1303
- /* Deep shadow DOM detected */
1304
- if (shadowNode.content instanceof DocumentFragment) {
1839
+ /* Deep shadow DOM detected.
1840
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): use nodeType against the
1841
+ DOCUMENT_FRAGMENT_NODE constant rather than instanceof, so we
1842
+ recurse into <template>.content from foreign realms too. */
1843
+ if (_isDocumentFragment(shadowNode.content)) {
1305
1844
  _sanitizeShadowDOM2(shadowNode.content);
1306
1845
  }
1846
+ /* An element iterated here may itself host an attached
1847
+ shadow root. The default NodeIterator does not enter shadow
1848
+ trees, so a shadow root nested inside template.content was
1849
+ previously reached by no walk at all (the pre-pass at
1850
+ _sanitizeAttachedShadowRoots descends via childNodes, which
1851
+ doesn't enter template.content; the template-content recursion
1852
+ above iterates the content but never inspected shadowRoot).
1853
+ Walk it explicitly. The nodeType guard avoids reading
1854
+ shadowRoot off text / comment / CDATA / PI nodes that the
1855
+ iterator also surfaces. */
1856
+ const shadowNodeType = getNodeType ? getNodeType(shadowNode) : shadowNode.nodeType;
1857
+ if (shadowNodeType === NODE_TYPE.element) {
1858
+ const innerSr = getShadowRoot(shadowNode);
1859
+ if (_isDocumentFragment(innerSr)) {
1860
+ _sanitizeAttachedShadowRoots(innerSr);
1861
+ _sanitizeShadowDOM2(innerSr);
1862
+ }
1863
+ }
1307
1864
  }
1308
1865
  /* Execute a hook if present */
1309
1866
  _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
@@ -1327,28 +1884,83 @@ function createDOMPurify() {
1327
1884
  *
1328
1885
  * @param root the subtree root to walk for attached shadow roots
1329
1886
  */
1330
- const _sanitizeAttachedShadowRoots2 = function _sanitizeAttachedShadowRoots(root) {
1331
- if (root.nodeType === NODE_TYPE.element && root.shadowRoot instanceof DocumentFragment) {
1332
- const sr = root.shadowRoot;
1333
- // Recurse first so that nested shadow roots are reached even if
1334
- // _sanitizeShadowDOM removes hosts at this level.
1335
- _sanitizeAttachedShadowRoots2(sr);
1336
- _sanitizeShadowDOM2(sr);
1337
- }
1338
- // Snapshot children before recursing. Sanitization of one subtree
1339
- // (e.g. via an uponSanitizeShadowNode hook) may detach siblings,
1340
- // and naive nextSibling traversal would silently skip the rest of
1341
- // the list once a node is detached.
1342
- const childNodes = root.childNodes;
1343
- if (!childNodes) {
1344
- return;
1345
- }
1346
- const snapshot = [];
1347
- arrayForEach(childNodes, child => {
1348
- arrayPush(snapshot, child);
1349
- });
1350
- for (const child of snapshot) {
1351
- _sanitizeAttachedShadowRoots2(child);
1887
+ const _sanitizeAttachedShadowRoots = function _sanitizeAttachedShadowRoots(root) {
1888
+ /* Iterative (explicit stack) rather than per-child recursion. DOM APIs
1889
+ impose no depth cap, so an attacker-shaped tree (JSON/CRDT/editor data
1890
+ built straight into the DOM the IN_PLACE surface) deeper than the JS
1891
+ call-stack budget would otherwise overflow native recursion here and
1892
+ throw at the IN_PLACE entry pre-pass, before a single node is
1893
+ sanitized, leaving the caller's live tree untouched (fail-open). See
1894
+ campaign-3 F4. A heap stack keeps depth off the call stack.
1895
+ Each work item is either a node to descend into, or a deferred
1896
+ `_sanitizeShadowDOM` for an already-walked shadow root. The deferred
1897
+ form preserves the original post-order discipline: a shadow root's
1898
+ nested shadow roots are discovered before the outer shadow is
1899
+ sanitized (which may remove hosts). Pushes are in reverse of the
1900
+ desired processing order (LIFO): template content, then children, then
1901
+ the shadow-sanitize, then the shadow walk — so the order matches the
1902
+ previous recursion exactly. */
1903
+ const stack = [{
1904
+ node: root,
1905
+ shadow: null
1906
+ }];
1907
+ while (stack.length > 0) {
1908
+ const item = stack.pop();
1909
+ /* Deferred shadow-DOM sanitisation: runs after its subtree was walked. */
1910
+ if (item.shadow) {
1911
+ _sanitizeShadowDOM2(item.shadow);
1912
+ continue;
1913
+ }
1914
+ const node = item.node;
1915
+ const nodeType = getNodeType ? getNodeType(node) : node.nodeType;
1916
+ const isElement = nodeType === NODE_TYPE.element;
1917
+ /* (pushed last → processed first) Children, snapshotted in reverse so
1918
+ the first child is processed first. Snapshotting matters because a
1919
+ hook may detach siblings mid-walk. */
1920
+ const childNodes = getChildNodes(node);
1921
+ if (childNodes) {
1922
+ for (let i = childNodes.length - 1; i >= 0; --i) {
1923
+ stack.push({
1924
+ node: childNodes[i],
1925
+ shadow: null
1926
+ });
1927
+ }
1928
+ }
1929
+ /* (pushed before children → processed after them, matching the old
1930
+ "template content last" order) When the node is a <template>,
1931
+ descend into its content. */
1932
+ if (isElement) {
1933
+ const rootName = getNodeName ? getNodeName(node) : null;
1934
+ if (typeof rootName === 'string' && transformCaseFunc(rootName) === 'template') {
1935
+ const content = node.content;
1936
+ if (_isDocumentFragment(content)) {
1937
+ stack.push({
1938
+ node: content,
1939
+ shadow: null
1940
+ });
1941
+ }
1942
+ }
1943
+ }
1944
+ /* Shadow root (processed first): walk its subtree, then sanitise it.
1945
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
1946
+ rather than `instanceof DocumentFragment`, which is realm-bound and
1947
+ silently skipped foreign-realm shadow roots (e.g.
1948
+ iframe.contentDocument attachShadow). */
1949
+ if (isElement) {
1950
+ const sr = getShadowRoot(node);
1951
+ if (_isDocumentFragment(sr)) {
1952
+ /* Push the deferred sanitise first so it pops after the shadow
1953
+ walk we push next, i.e. nested shadow roots are discovered
1954
+ before this one is sanitised. */
1955
+ stack.push({
1956
+ node: null,
1957
+ shadow: sr
1958
+ }, {
1959
+ node: sr,
1960
+ shadow: null
1961
+ });
1962
+ }
1963
+ }
1352
1964
  }
1353
1965
  };
1354
1966
  // eslint-disable-next-line complexity
@@ -1377,28 +1989,78 @@ function createDOMPurify() {
1377
1989
  return dirty;
1378
1990
  }
1379
1991
  /* Assign config vars */
1380
- if (!SET_CONFIG) {
1992
+ if (SET_CONFIG) {
1993
+ /* Persistent setConfig() path: _parseConfig is skipped, so the sets are
1994
+ * not re-derived per call. Restore them from the pristine bindings
1995
+ * captured at setConfig() time so a previous call's hook clone (mutated
1996
+ * below) does not carry over. */
1997
+ ALLOWED_TAGS = SET_CONFIG_ALLOWED_TAGS;
1998
+ ALLOWED_ATTR = SET_CONFIG_ALLOWED_ATTR;
1999
+ } else {
1381
2000
  _parseConfig(cfg);
1382
2001
  }
2002
+ /* Clone the hook-mutable allowlists before the walk whenever an
2003
+ * uponSanitize* hook is registered. The hook event exposes ALLOWED_TAGS
2004
+ * and ALLOWED_ATTR by reference (as allowedTags / allowedAttributes), so
2005
+ * a hook that widens them would otherwise mutate the shared set
2006
+ * permanently: across later calls and across every element. Cloning per
2007
+ * walk keeps documented in-call widening working while scoping it to the
2008
+ * call. A single guard for both config paths - the per-call path rebinds
2009
+ * the sets in _parseConfig each call, the persistent path restores them
2010
+ * from the captured bindings just above - so the two cannot diverge. */
2011
+ if (hooks.uponSanitizeElement.length > 0 || hooks.uponSanitizeAttribute.length > 0) {
2012
+ ALLOWED_TAGS = clone(ALLOWED_TAGS);
2013
+ }
2014
+ if (hooks.uponSanitizeAttribute.length > 0) {
2015
+ ALLOWED_ATTR = clone(ALLOWED_ATTR);
2016
+ }
1383
2017
  /* Clean up removed elements */
1384
2018
  DOMPurify.removed = [];
1385
- /* Check if dirty is correctly typed for IN_PLACE */
1386
- if (typeof dirty === 'string') {
1387
- IN_PLACE = false;
1388
- }
1389
- if (IN_PLACE) {
1390
- /* Do some early pre-sanitization to avoid unsafe root nodes */
1391
- const nn = dirty.nodeName;
2019
+ /* Resolve IN_PLACE for this call without mutating persistent config.
2020
+ Writing the IN_PLACE closure variable here leaks under setConfig(),
2021
+ where _parseConfig is skipped on later calls: a single string call would
2022
+ disable in-place mode for every subsequent node call, returning a
2023
+ sanitized copy while leaving the caller's node — which in-place callers
2024
+ keep using and whose return value they ignore unsanitized. REPORT-2. */
2025
+ const inPlace = IN_PLACE && typeof dirty !== 'string' && _isNode(dirty);
2026
+ if (inPlace) {
2027
+ /* Do some early pre-sanitization to avoid unsafe root nodes.
2028
+ Read nodeName through the cached prototype getter — a clobbering
2029
+ child named "nodeName" on the form root would otherwise shadow
2030
+ the property and let this check skip the root-allowlist
2031
+ validation entirely. */
2032
+ const nn = getNodeName ? getNodeName(dirty) : dirty.nodeName;
1392
2033
  if (typeof nn === 'string') {
1393
2034
  const tagName = transformCaseFunc(nn);
1394
2035
  if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
1395
2036
  throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
1396
2037
  }
1397
2038
  }
2039
+ /* Pre-flight the root through _isClobbered. The iterator-driven
2040
+ removal path can not detach a parent-less root: _forceRemove
2041
+ falls through to Element.prototype.remove(), which per spec
2042
+ is a no-op on a node with no parent. A clobbered root would
2043
+ then survive the main loop with its attributes uninspected,
2044
+ because _sanitizeAttributes early-returns on _isClobbered. The
2045
+ result would be an attacker-controlled form, complete with any
2046
+ event-handler attributes the caller passed in, handed back to
2047
+ the application unsanitized. Refuse to sanitize such a root
2048
+ the same way we refuse a forbidden tag. GHSA-r47g-fvhr-h676. */
2049
+ if (_isClobbered(dirty)) {
2050
+ throw typeErrorCreate('root node is clobbered and cannot be sanitized in-place');
2051
+ }
1398
2052
  /* Sanitize attached shadow roots before the main iterator runs.
1399
- The iterator does not descend into shadow trees. */
1400
- _sanitizeAttachedShadowRoots2(dirty);
1401
- } else if (dirty instanceof Node) {
2053
+ The iterator does not descend into shadow trees. Same fail-closed
2054
+ barrier as the main walk (campaign-3 F2): a custom-element reaction
2055
+ inside a shadow root could abort this pre-pass before the walk runs,
2056
+ which would otherwise leave the entire live tree unsanitized. */
2057
+ try {
2058
+ _sanitizeAttachedShadowRoots(dirty);
2059
+ } catch (error) {
2060
+ _neutralizeRoot(dirty);
2061
+ throw error;
2062
+ }
2063
+ } else if (_isNode(dirty)) {
1402
2064
  /* If dirty is a DOM element, append to an empty document to avoid
1403
2065
  elements being stripped by the parser */
1404
2066
  body = _initDocument('<!---->');
@@ -1414,14 +2076,16 @@ function createDOMPurify() {
1414
2076
  }
1415
2077
  /* Clonable shadow roots are deep-cloned by importNode(); sanitize
1416
2078
  them before the main iterator runs, since the iterator does not
1417
- descend into shadow trees. */
1418
- _sanitizeAttachedShadowRoots2(importedNode);
2079
+ descend into shadow trees. The walk routes every read through a
2080
+ cached prototype getter so clobbering descendants on a form root
2081
+ cannot hide a shadow host from this pass. */
2082
+ _sanitizeAttachedShadowRoots(importedNode);
1419
2083
  } else {
1420
2084
  /* Exit directly if we have nothing to do */
1421
2085
  if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
1422
2086
  // eslint-disable-next-line unicorn/prefer-includes
1423
2087
  dirty.indexOf('<') === -1) {
1424
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
2088
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(dirty) : dirty;
1425
2089
  }
1426
2090
  /* Initialize the document to work on */
1427
2091
  body = _initDocument(dirty);
@@ -1435,31 +2099,59 @@ function createDOMPurify() {
1435
2099
  _forceRemove(body.firstChild);
1436
2100
  }
1437
2101
  /* Get node iterator */
1438
- const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);
1439
- /* Now start iterating over the created document */
1440
- while (currentNode = nodeIterator.nextNode()) {
1441
- /* Sanitize tags and elements */
1442
- _sanitizeElements(currentNode);
1443
- /* Check attributes next */
1444
- _sanitizeAttributes(currentNode);
1445
- /* Shadow DOM detected, sanitize it */
1446
- if (currentNode.content instanceof DocumentFragment) {
1447
- _sanitizeShadowDOM2(currentNode.content);
2102
+ const nodeIterator = _createNodeIterator(inPlace ? dirty : body);
2103
+ /* Now start iterating over the created document.
2104
+ The walk runs inside an exception barrier (campaign-3 F2): a re-entrant
2105
+ engine/custom-element mutation can detach a node mid-walk so
2106
+ `_forceRemove`'s parentless guard throws, aborting the loop. Without the
2107
+ barrier the caller's in-place tree would be left half-sanitized with the
2108
+ unvisited tail still armed. On any throw we fail closed — strip the
2109
+ in-place root bare then rethrow so the existing throw contract is
2110
+ preserved. (String/DOM-copy paths never return the partial body, so the
2111
+ propagating throw is already fail-closed there.) */
2112
+ try {
2113
+ while (currentNode = nodeIterator.nextNode()) {
2114
+ /* Sanitize tags and elements */
2115
+ _sanitizeElements(currentNode);
2116
+ /* Check attributes next */
2117
+ _sanitizeAttributes(currentNode);
2118
+ /* Shadow DOM detected, sanitize it.
2119
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
2120
+ instead of instanceof, so foreign-realm <template>.content is
2121
+ walked correctly. */
2122
+ if (_isDocumentFragment(currentNode.content)) {
2123
+ _sanitizeShadowDOM2(currentNode.content);
2124
+ }
2125
+ }
2126
+ } catch (error) {
2127
+ if (inPlace) {
2128
+ _neutralizeRoot(dirty);
1448
2129
  }
2130
+ throw error;
1449
2131
  }
1450
2132
  /* If we sanitized `dirty` in-place, return it. */
1451
- if (IN_PLACE) {
2133
+ if (inPlace) {
2134
+ /* Fail-closed completion of the audit-5 F1 fix: every node removed from
2135
+ the caller's live tree is detached but may still hold a queued
2136
+ resource-event handler that fires in page scope after we return. The
2137
+ move-hoist covers only disallowed-tag KEEP_CONTENT removals; strip the
2138
+ non-allow-listed attributes off every other removed subtree (clobber,
2139
+ mXSS, namespace, comments, KEEP_CONTENT:false, …) so those handlers are
2140
+ cancelled before any event can fire. Runs synchronously, pre-return. */
2141
+ arrayForEach(DOMPurify.removed, entry => {
2142
+ if (entry.element) {
2143
+ _neutralizeSubtree(entry.element);
2144
+ }
2145
+ });
2146
+ if (SAFE_FOR_TEMPLATES) {
2147
+ _scrubTemplateExpressions2(dirty);
2148
+ }
1452
2149
  return dirty;
1453
2150
  }
1454
2151
  /* Return sanitized string or DOM */
1455
2152
  if (RETURN_DOM) {
1456
2153
  if (SAFE_FOR_TEMPLATES) {
1457
- body.normalize();
1458
- let html = body.innerHTML;
1459
- arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => {
1460
- html = stringReplace(html, expr, ' ');
1461
- });
1462
- body.innerHTML = html;
2154
+ _scrubTemplateExpressions2(body);
1463
2155
  }
1464
2156
  if (RETURN_DOM_FRAGMENT) {
1465
2157
  returnNode = createDocumentFragment.call(body.ownerDocument);
@@ -1489,20 +2181,28 @@ function createDOMPurify() {
1489
2181
  }
1490
2182
  /* Sanitize final string template-safe */
1491
2183
  if (SAFE_FOR_TEMPLATES) {
1492
- arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => {
1493
- serializedHTML = stringReplace(serializedHTML, expr, ' ');
1494
- });
2184
+ serializedHTML = _stripTemplateExpressions(serializedHTML);
1495
2185
  }
1496
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
2186
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(serializedHTML) : serializedHTML;
1497
2187
  };
1498
2188
  DOMPurify.setConfig = function () {
1499
2189
  let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1500
2190
  _parseConfig(cfg);
1501
2191
  SET_CONFIG = true;
2192
+ SET_CONFIG_ALLOWED_TAGS = ALLOWED_TAGS;
2193
+ SET_CONFIG_ALLOWED_ATTR = ALLOWED_ATTR;
1502
2194
  };
1503
2195
  DOMPurify.clearConfig = function () {
1504
2196
  CONFIG = null;
1505
2197
  SET_CONFIG = false;
2198
+ SET_CONFIG_ALLOWED_TAGS = null;
2199
+ SET_CONFIG_ALLOWED_ATTR = null;
2200
+ // Drop any caller-supplied Trusted Types policy so it cannot poison later
2201
+ // `RETURN_TRUSTED_TYPE` output. The internal default policy (cached, and
2202
+ // never recreated — Trusted Types throws on duplicate names) is restored by
2203
+ // the next `_parseConfig`. See GHSA-vxr8-fq34-vvx9.
2204
+ trustedTypesPolicy = defaultTrustedTypesPolicy;
2205
+ emptyHTML = '';
1506
2206
  };
1507
2207
  DOMPurify.isValidAttribute = function (tag, attr, value) {
1508
2208
  /* Initialize shared config vars if necessary. */
@@ -1517,9 +2217,19 @@ function createDOMPurify() {
1517
2217
  if (typeof hookFunction !== 'function') {
1518
2218
  return;
1519
2219
  }
2220
+ /* Reject unknown entry points. Without this, a non-hook key (e.g.
2221
+ * '__proto__') indexes off the prototype chain rather than a real
2222
+ * hook array, and arrayPush then writes to Object.prototype. Guard
2223
+ * with an own-property check against the known hook names. */
2224
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
2225
+ return;
2226
+ }
1520
2227
  arrayPush(hooks[entryPoint], hookFunction);
1521
2228
  };
1522
2229
  DOMPurify.removeHook = function (entryPoint, hookFunction) {
2230
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
2231
+ return undefined;
2232
+ }
1523
2233
  if (hookFunction !== undefined) {
1524
2234
  const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);
1525
2235
  return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];
@@ -1527,6 +2237,9 @@ function createDOMPurify() {
1527
2237
  return arrayPop(hooks[entryPoint]);
1528
2238
  };
1529
2239
  DOMPurify.removeHooks = function (entryPoint) {
2240
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
2241
+ return;
2242
+ }
1530
2243
  hooks[entryPoint] = [];
1531
2244
  };
1532
2245
  DOMPurify.removeAllHooks = function () {