dompurify 3.4.8 → 3.4.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/purify.js CHANGED
@@ -1,4 +1,4 @@
1
- /*! @license DOMPurify 3.4.8 | (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.8/LICENSE */
1
+ /*! @license DOMPurify 3.4.10 | (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.10/LICENSE */
2
2
 
3
3
  (function (global, factory) {
4
4
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
@@ -333,6 +333,13 @@
333
333
  );
334
334
  const DOCTYPE_NAME = seal(/^html$/i);
335
335
  const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);
336
+ // Markup-significant character probes used by _sanitizeElements.
337
+ // Shared module-level instances are safe despite the sticky /g flags:
338
+ // unapply() resets lastIndex for RegExp receivers before every call.
339
+ const ELEMENT_MARKUP_PROBE = seal(/<[/\w!]/g);
340
+ const COMMENT_MARKUP_PROBE = seal(/<[/\w]/g);
341
+ const FALLBACK_TAG_CLOSE = seal(/<\/no(script|embed|frames)/i);
342
+ const SELF_CLOSING_TAG = seal(/\/>/i);
336
343
 
337
344
  /* eslint-disable @typescript-eslint/indent */
338
345
  // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
@@ -345,7 +352,7 @@
345
352
  // Deprecated
346
353
  entityNode: 6,
347
354
  // Deprecated
348
- progressingInstruction: 7,
355
+ processingInstruction: 7,
349
356
  comment: 8,
350
357
  document: 9,
351
358
  documentType: 10,
@@ -406,10 +413,25 @@
406
413
  uponSanitizeShadowNode: []
407
414
  };
408
415
  };
416
+ /**
417
+ * Resolve a set-valued configuration option: a fresh set built from
418
+ * cfg[key] when it is an own array property (seeded with a clone of
419
+ * options.base when given, case-normalized via options.transform),
420
+ * the fallback set otherwise.
421
+ *
422
+ * @param cfg the cloned, prototype-free configuration object
423
+ * @param key the configuration property to read
424
+ * @param fallback the set to use when the option is absent or not an array
425
+ * @param options transform and optional base set to merge into
426
+ * @returns the resolved set
427
+ */
428
+ const _resolveSetOption = function _resolveSetOption(cfg, key, fallback, options) {
429
+ return objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key]) ? addToSet(options.base ? clone(options.base) : {}, cfg[key], options.transform) : fallback;
430
+ };
409
431
  function createDOMPurify() {
410
432
  let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
411
433
  const DOMPurify = root => createDOMPurify(root);
412
- DOMPurify.version = '3.4.8';
434
+ DOMPurify.version = '3.4.10';
413
435
  DOMPurify.removed = [];
414
436
  if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {
415
437
  // Not running in a browser, provide a factory function
@@ -454,23 +476,54 @@
454
476
  }
455
477
  let trustedTypesPolicy;
456
478
  let emptyHTML = '';
479
+ // The instance's own internal Trusted Types policy. Unlike a caller-supplied
480
+ // `TRUSTED_TYPES_POLICY`, this is created at most once — Trusted Types throws
481
+ // on duplicate policy names — and is the only policy allowed to persist
482
+ // across configurations and survive `clearConfig()`.
483
+ let defaultTrustedTypesPolicy;
484
+ let defaultTrustedTypesPolicyResolved = false;
457
485
  // Tracks whether we are already inside a call to the configured Trusted Types
458
- // policy's `createHTML`. If the supplied `TRUSTED_TYPES_POLICY.createHTML`
486
+ // policy (`createHTML` or `createScriptURL`). If a supplied policy callback
459
487
  // itself calls `DOMPurify.sanitize` (the cause of #1422), `sanitize` would
460
488
  // re-enter the policy and recurse until the stack overflows. We detect that
461
- // re-entry and throw a clear, actionable error instead.
462
- let IN_POLICY_CREATE_HTML = 0;
463
- const _createTrustedHTML = function _createTrustedHTML(html) {
464
- if (IN_POLICY_CREATE_HTML > 0) {
465
- throw typeErrorCreate('The configured TRUSTED_TYPES_POLICY.createHTML must not call ' + 'DOMPurify.sanitize, as that causes infinite recursion. Do not pass ' + 'a policy whose createHTML wraps DOMPurify as TRUSTED_TYPES_POLICY; ' + 'see the "DOMPurify and Trusted Types" section of the README.');
489
+ // re-entry and throw a clear, actionable error instead. The guard is shared
490
+ // across both callbacks, because either one re-entering `sanitize` triggers
491
+ // the same unbounded recursion.
492
+ let IN_TRUSTED_TYPES_POLICY = 0;
493
+ const _assertNotInTrustedTypesPolicy = function _assertNotInTrustedTypesPolicy() {
494
+ if (IN_TRUSTED_TYPES_POLICY > 0) {
495
+ 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.');
466
496
  }
467
- IN_POLICY_CREATE_HTML++;
497
+ };
498
+ const _createTrustedHTML = function _createTrustedHTML(html) {
499
+ _assertNotInTrustedTypesPolicy();
500
+ IN_TRUSTED_TYPES_POLICY++;
468
501
  try {
469
502
  return trustedTypesPolicy.createHTML(html);
470
503
  } finally {
471
- IN_POLICY_CREATE_HTML--;
504
+ IN_TRUSTED_TYPES_POLICY--;
472
505
  }
473
506
  };
507
+ const _createTrustedScriptURL = function _createTrustedScriptURL(scriptUrl) {
508
+ _assertNotInTrustedTypesPolicy();
509
+ IN_TRUSTED_TYPES_POLICY++;
510
+ try {
511
+ return trustedTypesPolicy.createScriptURL(scriptUrl);
512
+ } finally {
513
+ IN_TRUSTED_TYPES_POLICY--;
514
+ }
515
+ };
516
+ // Lazily resolve (and cache) the instance's internal default policy.
517
+ // Resolution is attempted at most once: a successful `createPolicy` cannot be
518
+ // repeated (Trusted Types throws on duplicate names), and a failed or
519
+ // unsupported attempt must not be retried on every parse.
520
+ const _getDefaultTrustedTypesPolicy = function _getDefaultTrustedTypesPolicy() {
521
+ if (!defaultTrustedTypesPolicyResolved) {
522
+ defaultTrustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
523
+ defaultTrustedTypesPolicyResolved = true;
524
+ }
525
+ return defaultTrustedTypesPolicy;
526
+ };
474
527
  const _document = document,
475
528
  implementation = _document.implementation,
476
529
  createNodeIterator = _document.createNodeIterator,
@@ -609,7 +662,17 @@
609
662
  let USE_PROFILES = {};
610
663
  /* Tags to ignore content of when KEEP_CONTENT is true */
611
664
  let FORBID_CONTENTS = null;
612
- 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']);
665
+ const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script',
666
+ // <selectedcontent> mirrors the selected <option>'s subtree, cloned by
667
+ // the UA (customizable <select>) — including any on* handlers — and the
668
+ // engine re-mirrors synchronously whenever a removal changes which
669
+ // option/selectedcontent is current, even inside DOMPurify's inert
670
+ // DOMParser document. Hoisting its children on removal re-inserts a fresh
671
+ // mirror target ahead of the walk, which the engine refills, looping
672
+ // forever (DoS) and amplifying output. Dropping its content on removal
673
+ // (rather than hoisting) breaks that cascade; the content is a duplicate
674
+ // of the option, which is sanitized on its own. See campaign-3 F1/F6.
675
+ 'selectedcontent', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
613
676
  /* Tags that are safe for data: URIs */
614
677
  let DATA_URI_TAGS = null;
615
678
  const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
@@ -625,8 +688,10 @@
625
688
  /* Allowed XHTML+XML namespaces */
626
689
  let ALLOWED_NAMESPACES = null;
627
690
  const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
628
- let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
629
- let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);
691
+ const DEFAULT_MATHML_TEXT_INTEGRATION_POINTS = freeze(['mi', 'mo', 'mn', 'ms', 'mtext']);
692
+ let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS);
693
+ const DEFAULT_HTML_INTEGRATION_POINTS = freeze(['annotation-xml']);
694
+ let HTML_INTEGRATION_POINTS = addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS);
630
695
  // Certain elements are allowed in both SVG and HTML
631
696
  // namespace. We need to specify them explicitly
632
697
  // so that they don't get erroneously deleted from
@@ -668,14 +733,32 @@
668
733
  // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
669
734
  transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
670
735
  /* Set configuration parameters */
671
- ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') && arrayIsArray(cfg.ALLOWED_TAGS) ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
672
- ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') && arrayIsArray(cfg.ALLOWED_ATTR) ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
673
- ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') && arrayIsArray(cfg.ALLOWED_NAMESPACES) ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
674
- 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;
675
- 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;
676
- FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS) ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
677
- FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') && arrayIsArray(cfg.FORBID_TAGS) ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({});
678
- FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') && arrayIsArray(cfg.FORBID_ATTR) ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({});
736
+ ALLOWED_TAGS = _resolveSetOption(cfg, 'ALLOWED_TAGS', DEFAULT_ALLOWED_TAGS, {
737
+ transform: transformCaseFunc
738
+ });
739
+ ALLOWED_ATTR = _resolveSetOption(cfg, 'ALLOWED_ATTR', DEFAULT_ALLOWED_ATTR, {
740
+ transform: transformCaseFunc
741
+ });
742
+ ALLOWED_NAMESPACES = _resolveSetOption(cfg, 'ALLOWED_NAMESPACES', DEFAULT_ALLOWED_NAMESPACES, {
743
+ transform: stringToString
744
+ });
745
+ URI_SAFE_ATTRIBUTES = _resolveSetOption(cfg, 'ADD_URI_SAFE_ATTR', DEFAULT_URI_SAFE_ATTRIBUTES, {
746
+ transform: transformCaseFunc,
747
+ base: DEFAULT_URI_SAFE_ATTRIBUTES
748
+ });
749
+ DATA_URI_TAGS = _resolveSetOption(cfg, 'ADD_DATA_URI_TAGS', DEFAULT_DATA_URI_TAGS, {
750
+ transform: transformCaseFunc,
751
+ base: DEFAULT_DATA_URI_TAGS
752
+ });
753
+ FORBID_CONTENTS = _resolveSetOption(cfg, 'FORBID_CONTENTS', DEFAULT_FORBID_CONTENTS, {
754
+ transform: transformCaseFunc
755
+ });
756
+ FORBID_TAGS = _resolveSetOption(cfg, 'FORBID_TAGS', clone({}), {
757
+ transform: transformCaseFunc
758
+ });
759
+ FORBID_ATTR = _resolveSetOption(cfg, 'FORBID_ATTR', clone({}), {
760
+ transform: transformCaseFunc
761
+ });
679
762
  USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;
680
763
  ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
681
764
  ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
@@ -694,8 +777,8 @@
694
777
  IN_PLACE = cfg.IN_PLACE || false; // Default false
695
778
  IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp
696
779
  NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace
697
- 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
698
- 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
780
+ 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
781
+ 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
699
782
  const customElementHandling = objectHasOwnProperty(cfg, 'CUSTOM_ELEMENT_HANDLING') && cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING === 'object' ? clone(cfg.CUSTOM_ELEMENT_HANDLING) : create(null);
700
783
  CUSTOM_ELEMENT_HANDLING = create(null);
701
784
  if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) {
@@ -707,6 +790,7 @@
707
790
  if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') {
708
791
  CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined
709
792
  }
793
+ seal(CUSTOM_ELEMENT_HANDLING);
710
794
  if (SAFE_FOR_TEMPLATES) {
711
795
  ALLOW_DATA_ATTR = false;
712
796
  }
@@ -790,6 +874,13 @@
790
874
  addToSet(ALLOWED_TAGS, ['tbody']);
791
875
  delete FORBID_TAGS.tbody;
792
876
  }
877
+ // Re-derive the active Trusted Types policy from this configuration on
878
+ // every parse. The active policy must never be sticky closure state that
879
+ // outlives the config that set it: a caller-supplied policy left in place
880
+ // after `clearConfig()` — or after a later call that supplied none, or
881
+ // `TRUSTED_TYPES_POLICY: null` — could sign a subsequent "default"
882
+ // `RETURN_TRUSTED_TYPE` result with a foreign, possibly unsafe policy.
883
+ // See GHSA-vxr8-fq34-vvx9.
793
884
  if (cfg.TRUSTED_TYPES_POLICY) {
794
885
  if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
795
886
  throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
@@ -797,7 +888,7 @@
797
888
  if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
798
889
  throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
799
890
  }
800
- // Overwrite existing TrustedTypes policy.
891
+ // A caller-supplied policy applies to this configuration only.
801
892
  const previousTrustedTypesPolicy = trustedTypesPolicy;
802
893
  trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
803
894
  // Sign local variables required by `sanitize`. If the supplied policy's
@@ -810,16 +901,30 @@
810
901
  trustedTypesPolicy = previousTrustedTypesPolicy;
811
902
  throw error;
812
903
  }
904
+ } else if (cfg.TRUSTED_TYPES_POLICY === null) {
905
+ // Explicit opt-out for this call: perform no Trusted Types signing and
906
+ // create nothing (so a strict `trusted-types` CSP that disallows a
907
+ // `dompurify` policy can still call `sanitize` from inside its own
908
+ // policy — see #1422). Resetting to `undefined` rather than a sticky
909
+ // `null` also drops any previously retained caller policy, so it cannot
910
+ // resurface on a later call, while still allowing the next config-less
911
+ // call to restore the internal default policy. See GHSA-vxr8-fq34-vvx9.
912
+ trustedTypesPolicy = undefined;
913
+ emptyHTML = '';
813
914
  } else {
814
- // Uninitialized policy, attempt to initialize the internal dompurify policy.
815
- if (trustedTypesPolicy === undefined && cfg.TRUSTED_TYPES_POLICY !== null) {
816
- trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
817
- }
818
- // If creating the internal policy succeeded sign internal variables.
819
- // Note: a falsy `trustedTypesPolicy` (null when policy creation failed or
820
- // was skipped via `TRUSTED_TYPES_POLICY: null`, or undefined when no
821
- // policy has been initialized yet) must be excluded here, otherwise we
822
- // would call `.createHTML` on a non-policy and throw. See #1422.
915
+ // No policy supplied: keep the currently active policy if one is set — a
916
+ // previously supplied policy is intentionally sticky across config-less
917
+ // calls — otherwise fall back to the instance's own internal policy,
918
+ // created at most once. (A policy supplied for a *single* call still
919
+ // lingers by design; what must not linger is a policy whose configuration
920
+ // has been torn down via `clearConfig()`, which restores the default.)
921
+ if (trustedTypesPolicy === undefined) {
922
+ trustedTypesPolicy = _getDefaultTrustedTypesPolicy();
923
+ }
924
+ // Sign internal variables only when a policy is active. A falsy policy
925
+ // (Trusted Types unsupported, creation failed, or an explicit opt-out)
926
+ // leaves `emptyHTML` as a plain string, so we never call `.createHTML` on
927
+ // a non-policy and throw. See #1422.
823
928
  if (trustedTypesPolicy && typeof emptyHTML === 'string') {
824
929
  emptyHTML = _createTrustedHTML('');
825
930
  }
@@ -851,6 +956,77 @@
851
956
  * correctly. */
852
957
  const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
853
958
  const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
959
+ /**
960
+ * Namespace rules for an element in the SVG namespace.
961
+ *
962
+ * @param tagName the element's lowercase tag name
963
+ * @param parent the (possibly simulated) parent node
964
+ * @param parentTagName the parent's lowercase tag name
965
+ * @returns true if a spec-compliant parser could produce this element
966
+ */
967
+ const _checkSvgNamespace = function _checkSvgNamespace(tagName, parent, parentTagName) {
968
+ // The only way to switch from HTML namespace to SVG
969
+ // is via <svg>. If it happens via any other tag, then
970
+ // it should be killed.
971
+ if (parent.namespaceURI === HTML_NAMESPACE) {
972
+ return tagName === 'svg';
973
+ }
974
+ // The only way to switch from MathML to SVG is via <svg>
975
+ // if the parent is either <annotation-xml> or a MathML
976
+ // text integration point.
977
+ if (parent.namespaceURI === MATHML_NAMESPACE) {
978
+ return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
979
+ }
980
+ // We only allow elements that are defined in SVG
981
+ // spec. All others are disallowed in SVG namespace.
982
+ return Boolean(ALL_SVG_TAGS[tagName]);
983
+ };
984
+ /**
985
+ * Namespace rules for an element in the MathML namespace.
986
+ *
987
+ * @param tagName the element's lowercase tag name
988
+ * @param parent the (possibly simulated) parent node
989
+ * @param parentTagName the parent's lowercase tag name
990
+ * @returns true if a spec-compliant parser could produce this element
991
+ */
992
+ const _checkMathMlNamespace = function _checkMathMlNamespace(tagName, parent, parentTagName) {
993
+ // The only way to switch from HTML namespace to MathML
994
+ // is via <math>. If it happens via any other tag, then
995
+ // it should be killed.
996
+ if (parent.namespaceURI === HTML_NAMESPACE) {
997
+ return tagName === 'math';
998
+ }
999
+ // The only way to switch from SVG to MathML is via
1000
+ // <math> and HTML integration points
1001
+ if (parent.namespaceURI === SVG_NAMESPACE) {
1002
+ return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
1003
+ }
1004
+ // We only allow elements that are defined in MathML
1005
+ // spec. All others are disallowed in MathML namespace.
1006
+ return Boolean(ALL_MATHML_TAGS[tagName]);
1007
+ };
1008
+ /**
1009
+ * Namespace rules for an element in the HTML namespace.
1010
+ *
1011
+ * @param tagName the element's lowercase tag name
1012
+ * @param parent the (possibly simulated) parent node
1013
+ * @param parentTagName the parent's lowercase tag name
1014
+ * @returns true if a spec-compliant parser could produce this element
1015
+ */
1016
+ const _checkHtmlNamespace = function _checkHtmlNamespace(tagName, parent, parentTagName) {
1017
+ // The only way to switch from SVG to HTML is via
1018
+ // HTML integration points, and from MathML to HTML
1019
+ // is via MathML text integration points
1020
+ if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
1021
+ return false;
1022
+ }
1023
+ if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
1024
+ return false;
1025
+ }
1026
+ // We disallow tags that are specific for MathML
1027
+ // or SVG and should never appear in HTML namespace
1028
+ return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
1029
+ };
854
1030
  /**
855
1031
  * @param element a DOM element whose namespace is being checked
856
1032
  * @returns Return false if the element has a
@@ -873,51 +1049,13 @@
873
1049
  return false;
874
1050
  }
875
1051
  if (element.namespaceURI === SVG_NAMESPACE) {
876
- // The only way to switch from HTML namespace to SVG
877
- // is via <svg>. If it happens via any other tag, then
878
- // it should be killed.
879
- if (parent.namespaceURI === HTML_NAMESPACE) {
880
- return tagName === 'svg';
881
- }
882
- // The only way to switch from MathML to SVG is via`
883
- // svg if parent is either <annotation-xml> or MathML
884
- // text integration points.
885
- if (parent.namespaceURI === MATHML_NAMESPACE) {
886
- return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
887
- }
888
- // We only allow elements that are defined in SVG
889
- // spec. All others are disallowed in SVG namespace.
890
- return Boolean(ALL_SVG_TAGS[tagName]);
1052
+ return _checkSvgNamespace(tagName, parent, parentTagName);
891
1053
  }
892
1054
  if (element.namespaceURI === MATHML_NAMESPACE) {
893
- // The only way to switch from HTML namespace to MathML
894
- // is via <math>. If it happens via any other tag, then
895
- // it should be killed.
896
- if (parent.namespaceURI === HTML_NAMESPACE) {
897
- return tagName === 'math';
898
- }
899
- // The only way to switch from SVG to MathML is via
900
- // <math> and HTML integration points
901
- if (parent.namespaceURI === SVG_NAMESPACE) {
902
- return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
903
- }
904
- // We only allow elements that are defined in MathML
905
- // spec. All others are disallowed in MathML namespace.
906
- return Boolean(ALL_MATHML_TAGS[tagName]);
1055
+ return _checkMathMlNamespace(tagName, parent, parentTagName);
907
1056
  }
908
1057
  if (element.namespaceURI === HTML_NAMESPACE) {
909
- // The only way to switch from SVG to HTML is via
910
- // HTML integration points, and from MathML to HTML
911
- // is via MathML text integration points
912
- if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
913
- return false;
914
- }
915
- if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
916
- return false;
917
- }
918
- // We disallow tags that are specific for MathML
919
- // or SVG and should never appear in HTML namespace
920
- return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
1058
+ return _checkHtmlNamespace(tagName, parent, parentTagName);
921
1059
  }
922
1060
  // For XHTML and XML documents that support custom namespaces
923
1061
  if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
@@ -942,7 +1080,74 @@
942
1080
  // eslint-disable-next-line unicorn/prefer-dom-node-remove
943
1081
  getParentNode(node).removeChild(node);
944
1082
  } catch (_) {
1083
+ /* The normal detach failed — this is reached for a parentless node
1084
+ (getParentNode() is null, so .removeChild throws). Element.prototype
1085
+ .remove() is itself a spec no-op on a parentless node, so a recorded
1086
+ "removal" would otherwise hand the caller back an intact,
1087
+ payload-bearing node (e.g. a detached IN_PLACE root the mXSS canary or
1088
+ the style-with-element-child rule decided to kill). Fail closed by
1089
+ throwing — exactly as a clobbered root does at the IN_PLACE entry —
1090
+ rather than trying to "neutralize" the node via its own methods.
1091
+ Neutralizing would mean calling getAttributeNames()/removeAttribute()
1092
+ on the node, both of which a <form> root can clobber via a named child
1093
+ (and _isClobbered does not even probe getAttributeNames), so the
1094
+ neutralize step could itself be silently defeated, leaving the payload
1095
+ intact. A throw touches only the cached, clobber-safe remove() and
1096
+ getParentNode(). Generalizes GHSA-r47g-fvhr-h676 (clobbered-form root)
1097
+ to every root-kill reason. REPORT-3.
1098
+ This lives inside the catch, so it never fires for a normally-removed
1099
+ in-tree node: those have a parent, removeChild() succeeds, and the
1100
+ catch is not entered. Only a kept (parentless) root reaches here. */
945
1101
  remove(node);
1102
+ if (!getParentNode(node)) {
1103
+ throw typeErrorCreate('a node selected for removal could not be detached from its tree ' + 'and cannot be safely returned; refusing to sanitize in place');
1104
+ }
1105
+ }
1106
+ };
1107
+ /**
1108
+ * _neutralizeRoot
1109
+ *
1110
+ * Fail-closed teardown of an in-place root after the sanitize walk aborts
1111
+ * (campaign-3 F2). An internal throw mid-walk — e.g. a page-registered
1112
+ * custom element's reaction detaches a node so `_forceRemove`'s deliberate
1113
+ * parentless guard throws, or any other re-entrant engine mutation — would
1114
+ * otherwise leave the caller's *live* tree half-sanitized, with everything
1115
+ * after the abort point still carrying its handlers. There is no safe way
1116
+ * to resume the walk (the tree mutated under us), so we strip the root bare:
1117
+ * remove every child and every attribute, then let the caller's catch see
1118
+ * the original error. Clobber-safe (cached `remove`/`childNodes`/`attributes`
1119
+ * getters; the root was already clobber-pre-flighted at the IN_PLACE entry).
1120
+ *
1121
+ * @param root the in-place root to empty
1122
+ */
1123
+ const _neutralizeRoot = function _neutralizeRoot(root) {
1124
+ const childNodes = getChildNodes(root);
1125
+ if (childNodes) {
1126
+ const snapshot = [];
1127
+ arrayForEach(childNodes, child => {
1128
+ arrayPush(snapshot, child);
1129
+ });
1130
+ arrayForEach(snapshot, child => {
1131
+ try {
1132
+ remove(child);
1133
+ } catch (_) {
1134
+ /* Best-effort teardown; a still-attached child is handled below */
1135
+ }
1136
+ });
1137
+ }
1138
+ const attributes = getAttributes(root);
1139
+ if (attributes) {
1140
+ for (let i = attributes.length - 1; i >= 0; --i) {
1141
+ const attribute = attributes[i];
1142
+ const name = attribute && attribute.name;
1143
+ if (typeof name === 'string') {
1144
+ try {
1145
+ root.removeAttribute(name);
1146
+ } catch (_) {
1147
+ /* Clobbered removeAttribute — ignore (fail-closed best effort) */
1148
+ }
1149
+ }
1150
+ }
946
1151
  }
947
1152
  };
948
1153
  /**
@@ -977,6 +1182,72 @@
977
1182
  }
978
1183
  }
979
1184
  };
1185
+ /**
1186
+ * _stripDisallowedAttributes
1187
+ *
1188
+ * Removes every attribute the active configuration does not allow from a
1189
+ * single element, using the same allowlist as the main attribute pass (so
1190
+ * `on*` handlers go, but no `/^on/` blocklist is introduced). Used only to
1191
+ * neutralise nodes that are being discarded from an in-place tree.
1192
+ *
1193
+ * @param element the element to strip
1194
+ */
1195
+ const _stripDisallowedAttributes = function _stripDisallowedAttributes(element) {
1196
+ const attributes = getAttributes(element);
1197
+ if (!attributes) {
1198
+ return;
1199
+ }
1200
+ for (let i = attributes.length - 1; i >= 0; --i) {
1201
+ const attribute = attributes[i];
1202
+ const name = attribute && attribute.name;
1203
+ if (typeof name !== 'string' || ALLOWED_ATTR[transformCaseFunc(name)]) {
1204
+ continue;
1205
+ }
1206
+ try {
1207
+ element.removeAttribute(name);
1208
+ } catch (_) {
1209
+ /* Clobbered removeAttribute on a doomed node — ignore */
1210
+ }
1211
+ }
1212
+ };
1213
+ /**
1214
+ * _neutralizeSubtree
1215
+ *
1216
+ * Completes the audit-5 F1 fix across every removal path. The KEEP_CONTENT
1217
+ * move-hoist neutralises only disallowed-tag removals; clobber, mXSS-canary,
1218
+ * namespace, comment, processing-instruction and KEEP_CONTENT:false removals
1219
+ * all drop their subtree wholesale via `_forceRemove`. On the IN_PLACE path
1220
+ * those dropped nodes are detached from the caller's LIVE tree but a
1221
+ * handler-bearing original among them (an `<img onerror>`/`<video>` that was
1222
+ * loading) keeps its queued resource event, which fires in page scope after
1223
+ * sanitize returns. This walks a removed subtree and strips every attribute
1224
+ * the active configuration does not allow — so `on*` handlers are cancelled
1225
+ * through the SAME allowlist that governs kept nodes, not a separate `/^on/`
1226
+ * blocklist. Run synchronously before sanitize returns, i.e. before any
1227
+ * queued event can fire. Hook-free by design: these nodes leave the output,
1228
+ * so firing attribute hooks for them would be surprising. Clobber-safe reads;
1229
+ * a doomed clobbered node may shadow `removeAttribute` (its own attributes are
1230
+ * irrelevant — it is discarded — while its non-clobbered descendants, e.g.
1231
+ * the `<img>`, are reached and scrubbed).
1232
+ *
1233
+ * @param root the root of a removed subtree to neutralise
1234
+ */
1235
+ const _neutralizeSubtree = function _neutralizeSubtree(root) {
1236
+ const stack = [root];
1237
+ while (stack.length > 0) {
1238
+ const node = stack.pop();
1239
+ const nodeType = getNodeType ? getNodeType(node) : node.nodeType;
1240
+ if (nodeType === NODE_TYPE.element) {
1241
+ _stripDisallowedAttributes(node);
1242
+ }
1243
+ const childNodes = getChildNodes(node);
1244
+ if (childNodes) {
1245
+ for (let i = childNodes.length - 1; i >= 0; --i) {
1246
+ stack.push(childNodes[i]);
1247
+ }
1248
+ }
1249
+ }
1250
+ };
980
1251
  /**
981
1252
  * _initDocument
982
1253
  *
@@ -1038,6 +1309,20 @@
1038
1309
  // eslint-disable-next-line no-bitwise
1039
1310
  NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
1040
1311
  };
1312
+ /**
1313
+ * Replace template expression syntax (mustache, ERB, template
1314
+ * literal) with a space; shared by all SAFE_FOR_TEMPLATES scrub
1315
+ * sites. Order matters: mustache, then ERB, then template literal.
1316
+ *
1317
+ * @param value the string to scrub
1318
+ * @returns the scrubbed string
1319
+ */
1320
+ const _stripTemplateExpressions = function _stripTemplateExpressions(value) {
1321
+ value = stringReplace(value, MUSTACHE_EXPR$1, ' ');
1322
+ value = stringReplace(value, ERB_EXPR$1, ' ');
1323
+ value = stringReplace(value, TMPLIT_EXPR$1, ' ');
1324
+ return value;
1325
+ };
1041
1326
  /**
1042
1327
  * Strip template-engine expressions ({{...}}, ${...}, <%...%>) from the
1043
1328
  * character data of an element subtree. Used as the final safety net for
@@ -1058,29 +1343,27 @@
1058
1343
  * @param node The root element whose character data should be scrubbed.
1059
1344
  */
1060
1345
  const _scrubTemplateExpressions2 = function _scrubTemplateExpressions(node) {
1061
- var _node$querySelectorAl, _node$querySelectorAl2;
1346
+ var _node$querySelectorAl;
1062
1347
  node.normalize();
1063
1348
  const walker = createNodeIterator.call(node.ownerDocument || node, node,
1064
1349
  // eslint-disable-next-line no-bitwise
1065
1350
  NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_CDATA_SECTION | NodeFilter.SHOW_PROCESSING_INSTRUCTION, null);
1066
1351
  let currentNode = walker.nextNode();
1067
1352
  while (currentNode) {
1068
- let data = currentNode.data;
1069
- arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => {
1070
- data = stringReplace(data, expr, ' ');
1071
- });
1072
- currentNode.data = data;
1353
+ currentNode.data = _stripTemplateExpressions(currentNode.data);
1073
1354
  currentNode = walker.nextNode();
1074
1355
  }
1075
1356
  // NodeIterator does not descend into <template>.content per the DOM spec,
1076
1357
  // so we must explicitly recurse into each template's content fragment,
1077
1358
  // mirroring the approach used by _sanitizeShadowDOM.
1078
- const templates = (_node$querySelectorAl = (_node$querySelectorAl2 = node.querySelectorAll) === null || _node$querySelectorAl2 === void 0 ? void 0 : _node$querySelectorAl2.call(node, 'template')) !== null && _node$querySelectorAl !== void 0 ? _node$querySelectorAl : [];
1079
- arrayForEach(Array.from(templates), tmpl => {
1080
- if (_isDocumentFragment(tmpl.content)) {
1081
- _scrubTemplateExpressions2(tmpl.content);
1082
- }
1083
- });
1359
+ const templates = (_node$querySelectorAl = node.querySelectorAll) === null || _node$querySelectorAl === void 0 ? void 0 : _node$querySelectorAl.call(node, 'template');
1360
+ if (templates) {
1361
+ arrayForEach(templates, tmpl => {
1362
+ if (_isDocumentFragment(tmpl.content)) {
1363
+ _scrubTemplateExpressions2(tmpl.content);
1364
+ }
1365
+ });
1366
+ }
1084
1367
  };
1085
1368
  /**
1086
1369
  * _isClobbered
@@ -1176,10 +1459,104 @@
1176
1459
  }
1177
1460
  };
1178
1461
  function _executeHooks(hooks, currentNode, data) {
1462
+ if (hooks.length === 0) {
1463
+ return;
1464
+ }
1179
1465
  arrayForEach(hooks, hook => {
1180
1466
  hook.call(DOMPurify, currentNode, data, CONFIG);
1181
1467
  });
1182
1468
  }
1469
+ /**
1470
+ * Structural-threat checks that condemn a node regardless of the
1471
+ * allowlists: mXSS via namespace confusion, risky CSS construction,
1472
+ * processing instructions, markup-bearing comments. Pure predicate;
1473
+ * the caller removes. Check order is load-bearing.
1474
+ *
1475
+ * @param currentNode the node to inspect
1476
+ * @param tagName the node's transformCaseFunc'd tag name
1477
+ * @return true if the node must be removed
1478
+ */
1479
+ const _isUnsafeNode = function _isUnsafeNode(currentNode, tagName) {
1480
+ /* Detect mXSS attempts abusing namespace confusion */
1481
+ if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.textContent) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.innerHTML)) {
1482
+ return true;
1483
+ }
1484
+ /* Remove risky CSS construction leading to mXSS */
1485
+ if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {
1486
+ return true;
1487
+ }
1488
+ /* Remove any occurrence of processing instructions */
1489
+ if (currentNode.nodeType === NODE_TYPE.processingInstruction) {
1490
+ return true;
1491
+ }
1492
+ /* Remove any kind of possibly harmful comments */
1493
+ if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, currentNode.data)) {
1494
+ return true;
1495
+ }
1496
+ return false;
1497
+ };
1498
+ /**
1499
+ * Handle a node whose tag is forbidden or not allowlisted: keep
1500
+ * allowed custom elements (false return exits _sanitizeElements
1501
+ * early - namespace/fallback checks and the afterSanitizeElements
1502
+ * hook are intentionally skipped for kept custom elements), else
1503
+ * hoist content per KEEP_CONTENT and remove.
1504
+ *
1505
+ * @param currentNode the disallowed node
1506
+ * @param tagName the node's transformCaseFunc'd tag name
1507
+ * @return true if the node was removed, false if kept
1508
+ */
1509
+ const _sanitizeDisallowedNode = function _sanitizeDisallowedNode(currentNode, tagName) {
1510
+ /* Check if we have a custom element to handle */
1511
+ if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
1512
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
1513
+ return false;
1514
+ }
1515
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
1516
+ return false;
1517
+ }
1518
+ }
1519
+ /* Keep content except for bad-listed elements.
1520
+ Use the cached prototype getters exclusively — the previous code
1521
+ had `|| currentNode.parentNode` / `|| currentNode.childNodes`
1522
+ fallbacks, but the cached getters always return the canonical
1523
+ value (or null for a real parent-less node), so the fallback
1524
+ path was dead in safe cases and a clobbering surface in unsafe
1525
+ ones. Falsy cached results stay falsy; the `if (childNodes &&
1526
+ parentNode)` check already gates correctly. */
1527
+ if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
1528
+ const parentNode = getParentNode(currentNode);
1529
+ const childNodes = getChildNodes(currentNode);
1530
+ if (childNodes && parentNode) {
1531
+ const childCount = childNodes.length;
1532
+ /* In-place: hoist the *original* children so the iterator visits
1533
+ and sanitises them through the same allowlist pass as every other
1534
+ node. The caller built the tree in the live document, so the
1535
+ originals carry already-queued resource events (`<img onerror>`,
1536
+ `<video>`/`<audio>` error, lazy/`onload`, …); cloning would leave
1537
+ those originals detached but still armed, firing in page scope
1538
+ while the returned tree looked clean. Moving is safe in-place: the
1539
+ root is pre-validated as an allowed tag and so is never the node
1540
+ being removed, which keeps `parentNode` inside the iterator root
1541
+ and the relocated child inside the serialised tree.
1542
+ Otherwise (string / DOM-copy paths): clone. The iterator is rooted
1543
+ at — and the result serialised from — `body`, so a restrictive
1544
+ ALLOWED_TAGS that removes `body` itself must leave its content in
1545
+ place, which only cloning does; and those paths parse into an
1546
+ inert document, so their discarded originals never had a queued
1547
+ event to neutralise.
1548
+ `childNodes` is live; a tail-to-head walk keeps `childNodes[i]`
1549
+ valid whether we move (drops the trailing entry) or clone (leaves
1550
+ the list intact). */
1551
+ for (let i = childCount - 1; i >= 0; --i) {
1552
+ const hoisted = IN_PLACE ? childNodes[i] : cloneNode(childNodes[i], true);
1553
+ parentNode.insertBefore(hoisted, getNextSibling(currentNode));
1554
+ }
1555
+ }
1556
+ }
1557
+ _forceRemove(currentNode);
1558
+ return true;
1559
+ };
1183
1560
  /**
1184
1561
  * _sanitizeElements
1185
1562
  *
@@ -1190,7 +1567,6 @@
1190
1567
  * @return true if node was killed, false if left alive
1191
1568
  */
1192
1569
  const _sanitizeElements = function _sanitizeElements(currentNode) {
1193
- let content = null;
1194
1570
  /* Execute a hook if present */
1195
1571
  _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
1196
1572
  /* Check if element is clobbered or can clobber */
@@ -1205,58 +1581,14 @@
1205
1581
  tagName,
1206
1582
  allowedTags: ALLOWED_TAGS
1207
1583
  });
1208
- /* Detect mXSS attempts abusing namespace confusion */
1209
- if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) {
1210
- _forceRemove(currentNode);
1211
- return true;
1212
- }
1213
- /* Remove risky CSS construction leading to mXSS */
1214
- if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {
1215
- _forceRemove(currentNode);
1216
- return true;
1217
- }
1218
- /* Remove any occurrence of processing instructions */
1219
- if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {
1220
- _forceRemove(currentNode);
1221
- return true;
1222
- }
1223
- /* Remove any kind of possibly harmful comments */
1224
- if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) {
1584
+ /* Remove mXSS vectors, processing instructions and risky comments */
1585
+ if (_isUnsafeNode(currentNode, tagName)) {
1225
1586
  _forceRemove(currentNode);
1226
1587
  return true;
1227
1588
  }
1228
1589
  /* Remove element if anything forbids its presence */
1229
1590
  if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) {
1230
- /* Check if we have a custom element to handle */
1231
- if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
1232
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
1233
- return false;
1234
- }
1235
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
1236
- return false;
1237
- }
1238
- }
1239
- /* Keep content except for bad-listed elements.
1240
- Use the cached prototype getters exclusively — the previous code
1241
- had `|| currentNode.parentNode` / `|| currentNode.childNodes`
1242
- fallbacks, but the cached getters always return the canonical
1243
- value (or null for a real parent-less node), so the fallback
1244
- path was dead in safe cases and a clobbering surface in unsafe
1245
- ones. Falsy cached results stay falsy; the `if (childNodes &&
1246
- parentNode)` check already gates correctly. */
1247
- if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
1248
- const parentNode = getParentNode(currentNode);
1249
- const childNodes = getChildNodes(currentNode);
1250
- if (childNodes && parentNode) {
1251
- const childCount = childNodes.length;
1252
- for (let i = childCount - 1; i >= 0; --i) {
1253
- const childClone = cloneNode(childNodes[i], true);
1254
- parentNode.insertBefore(childClone, getNextSibling(currentNode));
1255
- }
1256
- }
1257
- }
1258
- _forceRemove(currentNode);
1259
- return true;
1591
+ return _sanitizeDisallowedNode(currentNode, tagName);
1260
1592
  }
1261
1593
  /* Check whether element has a valid namespace.
1262
1594
  Realm-safe check (GHSA-hpcv-96wg-7vj8): use the cached Node.prototype
@@ -1270,17 +1602,14 @@
1270
1602
  return true;
1271
1603
  }
1272
1604
  /* Make sure that older browsers don't get fallback-tag mXSS */
1273
- if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {
1605
+ if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(FALLBACK_TAG_CLOSE, currentNode.innerHTML)) {
1274
1606
  _forceRemove(currentNode);
1275
1607
  return true;
1276
1608
  }
1277
1609
  /* Sanitize element content to be template-safe */
1278
1610
  if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
1279
1611
  /* Get the element's text content */
1280
- content = currentNode.textContent;
1281
- arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => {
1282
- content = stringReplace(content, expr, ' ');
1283
- });
1612
+ const content = _stripTemplateExpressions(currentNode.textContent);
1284
1613
  if (currentNode.textContent !== content) {
1285
1614
  arrayPush(DOMPurify.removed, {
1286
1615
  element: currentNode.cloneNode()
@@ -1315,7 +1644,7 @@
1315
1644
  (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
1316
1645
  XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
1317
1646
  We don't need to check the value; it's always URI safe. */
1318
- 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]) {
1647
+ if (ALLOW_DATA_ATTR && regExpTest(DATA_ATTR$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) ; else if (!nameIsPermitted) {
1319
1648
  if (
1320
1649
  // First condition does a very basic check if a) it's basically a valid custom element tagname AND
1321
1650
  // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
@@ -1347,6 +1676,63 @@
1347
1676
  const _isBasicCustomElement = function _isBasicCustomElement(tagName) {
1348
1677
  return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT$1, tagName);
1349
1678
  };
1679
+ /**
1680
+ * Wrap an attribute value in the matching Trusted Types object when
1681
+ * the active policy requires it. Namespaced attributes pass through
1682
+ * unchanged (no TT support yet, see
1683
+ * https://bugs.chromium.org/p/chromium/issues/detail?id=1305293).
1684
+ *
1685
+ * @param lcTag lowercase tag name of the containing element
1686
+ * @param lcName lowercase attribute name
1687
+ * @param namespaceURI the attribute's namespace, if any
1688
+ * @param value the attribute value to wrap
1689
+ * @return the value, wrapped when Trusted Types demand it
1690
+ */
1691
+ const _applyTrustedTypesToAttribute = function _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value) {
1692
+ if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function' && !namespaceURI) {
1693
+ switch (trustedTypes.getAttributeType(lcTag, lcName)) {
1694
+ case 'TrustedHTML':
1695
+ {
1696
+ return _createTrustedHTML(value);
1697
+ }
1698
+ case 'TrustedScriptURL':
1699
+ {
1700
+ return _createTrustedScriptURL(value);
1701
+ }
1702
+ }
1703
+ }
1704
+ return value;
1705
+ };
1706
+ /**
1707
+ * Write a modified attribute value back onto the element. On
1708
+ * success, re-probe for clobbering introduced by the new value and
1709
+ * remove the element when found; otherwise pop the removal entry
1710
+ * recorded by the earlier _removeAttribute (long-standing pairing
1711
+ * with the SANITIZE_NAMED_PROPS path - do not "fix" casually). On
1712
+ * failure, remove the attribute instead.
1713
+ *
1714
+ * @param currentNode the element carrying the attribute
1715
+ * @param name the attribute name as present on the element
1716
+ * @param namespaceURI the attribute's namespace, if any
1717
+ * @param value the new attribute value
1718
+ */
1719
+ const _setAttributeValue = function _setAttributeValue(currentNode, name, namespaceURI, value) {
1720
+ try {
1721
+ if (namespaceURI) {
1722
+ currentNode.setAttributeNS(namespaceURI, name, value);
1723
+ } else {
1724
+ /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
1725
+ currentNode.setAttribute(name, value);
1726
+ }
1727
+ if (_isClobbered(currentNode)) {
1728
+ _forceRemove(currentNode);
1729
+ } else {
1730
+ arrayPop(DOMPurify.removed);
1731
+ }
1732
+ } catch (_) {
1733
+ _removeAttribute(name, currentNode);
1734
+ }
1735
+ };
1350
1736
  /**
1351
1737
  * _sanitizeAttributes
1352
1738
  *
@@ -1373,6 +1759,7 @@
1373
1759
  forceKeepAttr: undefined
1374
1760
  };
1375
1761
  let l = attributes.length;
1762
+ const lcTag = transformCaseFunc(currentNode.nodeName);
1376
1763
  /* Go backwards over all attributes; safely remove bad ones */
1377
1764
  while (l--) {
1378
1765
  const attr = attributes[l];
@@ -1410,7 +1797,7 @@
1410
1797
  _removeAttribute(name, currentNode);
1411
1798
  continue;
1412
1799
  }
1413
- /* Did the hooks approve of the attribute? */
1800
+ /* Did the hooks force-keep the attribute? */
1414
1801
  if (hookEvent.forceKeepAttr) {
1415
1802
  continue;
1416
1803
  }
@@ -1420,56 +1807,24 @@
1420
1807
  continue;
1421
1808
  }
1422
1809
  /* Work around a security issue in jQuery 3.0 */
1423
- if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
1810
+ if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(SELF_CLOSING_TAG, value)) {
1424
1811
  _removeAttribute(name, currentNode);
1425
1812
  continue;
1426
1813
  }
1427
1814
  /* Sanitize attribute content to be template-safe */
1428
1815
  if (SAFE_FOR_TEMPLATES) {
1429
- arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => {
1430
- value = stringReplace(value, expr, ' ');
1431
- });
1816
+ value = _stripTemplateExpressions(value);
1432
1817
  }
1433
1818
  /* Is `value` valid for this attribute? */
1434
- const lcTag = transformCaseFunc(currentNode.nodeName);
1435
1819
  if (!_isValidAttribute(lcTag, lcName, value)) {
1436
1820
  _removeAttribute(name, currentNode);
1437
1821
  continue;
1438
1822
  }
1439
1823
  /* Handle attributes that require Trusted Types */
1440
- if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {
1441
- if (namespaceURI) ; else {
1442
- switch (trustedTypes.getAttributeType(lcTag, lcName)) {
1443
- case 'TrustedHTML':
1444
- {
1445
- value = _createTrustedHTML(value);
1446
- break;
1447
- }
1448
- case 'TrustedScriptURL':
1449
- {
1450
- value = trustedTypesPolicy.createScriptURL(value);
1451
- break;
1452
- }
1453
- }
1454
- }
1455
- }
1824
+ value = _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value);
1456
1825
  /* Handle invalid data-* attribute set by try-catching it */
1457
1826
  if (value !== initValue) {
1458
- try {
1459
- if (namespaceURI) {
1460
- currentNode.setAttributeNS(namespaceURI, name, value);
1461
- } else {
1462
- /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
1463
- currentNode.setAttribute(name, value);
1464
- }
1465
- if (_isClobbered(currentNode)) {
1466
- _forceRemove(currentNode);
1467
- } else {
1468
- arrayPop(DOMPurify.removed);
1469
- }
1470
- } catch (_) {
1471
- _removeAttribute(name, currentNode);
1472
- }
1827
+ _setAttributeValue(currentNode, name, namespaceURI, value);
1473
1828
  }
1474
1829
  }
1475
1830
  /* Execute a hook if present */
@@ -1511,9 +1866,9 @@
1511
1866
  iterator also surfaces. */
1512
1867
  const shadowNodeType = getNodeType ? getNodeType(shadowNode) : shadowNode.nodeType;
1513
1868
  if (shadowNodeType === NODE_TYPE.element) {
1514
- const innerSr = getShadowRoot ? getShadowRoot(shadowNode) : shadowNode.shadowRoot;
1869
+ const innerSr = getShadowRoot(shadowNode);
1515
1870
  if (_isDocumentFragment(innerSr)) {
1516
- _sanitizeAttachedShadowRoots2(innerSr);
1871
+ _sanitizeAttachedShadowRoots(innerSr);
1517
1872
  _sanitizeShadowDOM2(innerSr);
1518
1873
  }
1519
1874
  }
@@ -1540,46 +1895,81 @@
1540
1895
  *
1541
1896
  * @param root the subtree root to walk for attached shadow roots
1542
1897
  */
1543
- const _sanitizeAttachedShadowRoots2 = function _sanitizeAttachedShadowRoots(root) {
1544
- const nodeType = getNodeType ? getNodeType(root) : root.nodeType;
1545
- if (nodeType === NODE_TYPE.element) {
1546
- const sr = getShadowRoot ? getShadowRoot(root) : root.shadowRoot;
1547
- // Realm-safe check (GHSA-hpcv-96wg-7vj8): use nodeType-based
1548
- // detection rather than `instanceof DocumentFragment`, which is
1549
- // realm-bound and silently skipped shadow roots whose host element
1550
- // belonged to a foreign realm (e.g. iframe.contentDocument
1551
- // attachShadow). A foreign-realm ShadowRoot extends the foreign
1552
- // realm's DocumentFragment, not ours, so the old instanceof check
1553
- // returned false and the shadow subtree was never walked.
1554
- if (_isDocumentFragment(sr)) {
1555
- // Recurse first so that nested shadow roots are reached even if
1556
- // _sanitizeShadowDOM removes hosts at this level.
1557
- _sanitizeAttachedShadowRoots2(sr);
1558
- _sanitizeShadowDOM2(sr);
1559
- }
1560
- }
1561
- // Snapshot children before recursing. Sanitization of one subtree
1562
- // (e.g. via an uponSanitizeShadowNode hook) may detach siblings,
1563
- // and naive nextSibling traversal would silently skip the rest of
1564
- // the list once a node is detached.
1565
- const childNodes = getChildNodes ? getChildNodes(root) : root.childNodes;
1566
- if (!childNodes) {
1567
- return;
1568
- }
1569
- const snapshot = [];
1570
- arrayForEach(childNodes, child => {
1571
- arrayPush(snapshot, child);
1572
- });
1573
- for (const child of snapshot) {
1574
- _sanitizeAttachedShadowRoots2(child);
1575
- }
1576
- /* When the root is a <template>, also descend into root.content */
1577
- if (nodeType === NODE_TYPE.element) {
1578
- const rootName = getNodeName ? getNodeName(root) : null;
1579
- if (typeof rootName === 'string' && transformCaseFunc(rootName) === 'template') {
1580
- const content = root.content;
1581
- if (_isDocumentFragment(content)) {
1582
- _sanitizeAttachedShadowRoots2(content);
1898
+ const _sanitizeAttachedShadowRoots = function _sanitizeAttachedShadowRoots(root) {
1899
+ /* Iterative (explicit stack) rather than per-child recursion. DOM APIs
1900
+ impose no depth cap, so an attacker-shaped tree (JSON/CRDT/editor data
1901
+ built straight into the DOM — the IN_PLACE surface) deeper than the JS
1902
+ call-stack budget would otherwise overflow native recursion here and
1903
+ throw at the IN_PLACE entry pre-pass, before a single node is
1904
+ sanitized, leaving the caller's live tree untouched (fail-open). See
1905
+ campaign-3 F4. A heap stack keeps depth off the call stack.
1906
+ Each work item is either a node to descend into, or a deferred
1907
+ `_sanitizeShadowDOM` for an already-walked shadow root. The deferred
1908
+ form preserves the original post-order discipline: a shadow root's
1909
+ nested shadow roots are discovered before the outer shadow is
1910
+ sanitized (which may remove hosts). Pushes are in reverse of the
1911
+ desired processing order (LIFO): template content, then children, then
1912
+ the shadow-sanitize, then the shadow walk — so the order matches the
1913
+ previous recursion exactly. */
1914
+ const stack = [{
1915
+ node: root,
1916
+ shadow: null
1917
+ }];
1918
+ while (stack.length > 0) {
1919
+ const item = stack.pop();
1920
+ /* Deferred shadow-DOM sanitisation: runs after its subtree was walked. */
1921
+ if (item.shadow) {
1922
+ _sanitizeShadowDOM2(item.shadow);
1923
+ continue;
1924
+ }
1925
+ const node = item.node;
1926
+ const nodeType = getNodeType ? getNodeType(node) : node.nodeType;
1927
+ const isElement = nodeType === NODE_TYPE.element;
1928
+ /* (pushed last processed first) Children, snapshotted in reverse so
1929
+ the first child is processed first. Snapshotting matters because a
1930
+ hook may detach siblings mid-walk. */
1931
+ const childNodes = getChildNodes(node);
1932
+ if (childNodes) {
1933
+ for (let i = childNodes.length - 1; i >= 0; --i) {
1934
+ stack.push({
1935
+ node: childNodes[i],
1936
+ shadow: null
1937
+ });
1938
+ }
1939
+ }
1940
+ /* (pushed before children → processed after them, matching the old
1941
+ "template content last" order) When the node is a <template>,
1942
+ descend into its content. */
1943
+ if (isElement) {
1944
+ const rootName = getNodeName ? getNodeName(node) : null;
1945
+ if (typeof rootName === 'string' && transformCaseFunc(rootName) === 'template') {
1946
+ const content = node.content;
1947
+ if (_isDocumentFragment(content)) {
1948
+ stack.push({
1949
+ node: content,
1950
+ shadow: null
1951
+ });
1952
+ }
1953
+ }
1954
+ }
1955
+ /* Shadow root (processed first): walk its subtree, then sanitise it.
1956
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
1957
+ rather than `instanceof DocumentFragment`, which is realm-bound and
1958
+ silently skipped foreign-realm shadow roots (e.g.
1959
+ iframe.contentDocument attachShadow). */
1960
+ if (isElement) {
1961
+ const sr = getShadowRoot(node);
1962
+ if (_isDocumentFragment(sr)) {
1963
+ /* Push the deferred sanitise first so it pops after the shadow
1964
+ walk we push next, i.e. nested shadow roots are discovered
1965
+ before this one is sanitised. */
1966
+ stack.push({
1967
+ node: null,
1968
+ shadow: sr
1969
+ }, {
1970
+ node: sr,
1971
+ shadow: null
1972
+ });
1583
1973
  }
1584
1974
  }
1585
1975
  }
@@ -1615,11 +2005,14 @@
1615
2005
  }
1616
2006
  /* Clean up removed elements */
1617
2007
  DOMPurify.removed = [];
1618
- /* Check if dirty is correctly typed for IN_PLACE */
1619
- if (typeof dirty === 'string') {
1620
- IN_PLACE = false;
1621
- }
1622
- if (IN_PLACE) {
2008
+ /* Resolve IN_PLACE for this call without mutating persistent config.
2009
+ Writing the IN_PLACE closure variable here leaks under setConfig(),
2010
+ where _parseConfig is skipped on later calls: a single string call would
2011
+ disable in-place mode for every subsequent node call, returning a
2012
+ sanitized copy while leaving the caller's node — which in-place callers
2013
+ keep using and whose return value they ignore — unsanitized. REPORT-2. */
2014
+ const inPlace = IN_PLACE && typeof dirty !== 'string' && _isNode(dirty);
2015
+ if (inPlace) {
1623
2016
  /* Do some early pre-sanitization to avoid unsafe root nodes.
1624
2017
  Read nodeName through the cached prototype getter — a clobbering
1625
2018
  child named "nodeName" on the form root would otherwise shadow
@@ -1646,8 +2039,16 @@
1646
2039
  throw typeErrorCreate('root node is clobbered and cannot be sanitized in-place');
1647
2040
  }
1648
2041
  /* Sanitize attached shadow roots before the main iterator runs.
1649
- The iterator does not descend into shadow trees. */
1650
- _sanitizeAttachedShadowRoots2(dirty);
2042
+ The iterator does not descend into shadow trees. Same fail-closed
2043
+ barrier as the main walk (campaign-3 F2): a custom-element reaction
2044
+ inside a shadow root could abort this pre-pass before the walk runs,
2045
+ which would otherwise leave the entire live tree unsanitized. */
2046
+ try {
2047
+ _sanitizeAttachedShadowRoots(dirty);
2048
+ } catch (error) {
2049
+ _neutralizeRoot(dirty);
2050
+ throw error;
2051
+ }
1651
2052
  } else if (_isNode(dirty)) {
1652
2053
  /* If dirty is a DOM element, append to an empty document to avoid
1653
2054
  elements being stripped by the parser */
@@ -1667,7 +2068,7 @@
1667
2068
  descend into shadow trees. The walk routes every read through a
1668
2069
  cached prototype getter so clobbering descendants on a form root
1669
2070
  cannot hide a shadow host from this pass. */
1670
- _sanitizeAttachedShadowRoots2(importedNode);
2071
+ _sanitizeAttachedShadowRoots(importedNode);
1671
2072
  } else {
1672
2073
  /* Exit directly if we have nothing to do */
1673
2074
  if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
@@ -1687,23 +2088,50 @@
1687
2088
  _forceRemove(body.firstChild);
1688
2089
  }
1689
2090
  /* Get node iterator */
1690
- const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);
1691
- /* Now start iterating over the created document */
1692
- while (currentNode = nodeIterator.nextNode()) {
1693
- /* Sanitize tags and elements */
1694
- _sanitizeElements(currentNode);
1695
- /* Check attributes next */
1696
- _sanitizeAttributes(currentNode);
1697
- /* Shadow DOM detected, sanitize it.
1698
- Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
1699
- instead of instanceof, so foreign-realm <template>.content is
1700
- walked correctly. */
1701
- if (_isDocumentFragment(currentNode.content)) {
1702
- _sanitizeShadowDOM2(currentNode.content);
2091
+ const nodeIterator = _createNodeIterator(inPlace ? dirty : body);
2092
+ /* Now start iterating over the created document.
2093
+ The walk runs inside an exception barrier (campaign-3 F2): a re-entrant
2094
+ engine/custom-element mutation can detach a node mid-walk so
2095
+ `_forceRemove`'s parentless guard throws, aborting the loop. Without the
2096
+ barrier the caller's in-place tree would be left half-sanitized with the
2097
+ unvisited tail still armed. On any throw we fail closed — strip the
2098
+ in-place root bare then rethrow so the existing throw contract is
2099
+ preserved. (String/DOM-copy paths never return the partial body, so the
2100
+ propagating throw is already fail-closed there.) */
2101
+ try {
2102
+ while (currentNode = nodeIterator.nextNode()) {
2103
+ /* Sanitize tags and elements */
2104
+ _sanitizeElements(currentNode);
2105
+ /* Check attributes next */
2106
+ _sanitizeAttributes(currentNode);
2107
+ /* Shadow DOM detected, sanitize it.
2108
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
2109
+ instead of instanceof, so foreign-realm <template>.content is
2110
+ walked correctly. */
2111
+ if (_isDocumentFragment(currentNode.content)) {
2112
+ _sanitizeShadowDOM2(currentNode.content);
2113
+ }
2114
+ }
2115
+ } catch (error) {
2116
+ if (inPlace) {
2117
+ _neutralizeRoot(dirty);
1703
2118
  }
2119
+ throw error;
1704
2120
  }
1705
2121
  /* If we sanitized `dirty` in-place, return it. */
1706
- if (IN_PLACE) {
2122
+ if (inPlace) {
2123
+ /* Fail-closed completion of the audit-5 F1 fix: every node removed from
2124
+ the caller's live tree is detached but may still hold a queued
2125
+ resource-event handler that fires in page scope after we return. The
2126
+ move-hoist covers only disallowed-tag KEEP_CONTENT removals; strip the
2127
+ non-allow-listed attributes off every other removed subtree (clobber,
2128
+ mXSS, namespace, comments, KEEP_CONTENT:false, …) so those handlers are
2129
+ cancelled before any event can fire. Runs synchronously, pre-return. */
2130
+ arrayForEach(DOMPurify.removed, entry => {
2131
+ if (entry.element) {
2132
+ _neutralizeSubtree(entry.element);
2133
+ }
2134
+ });
1707
2135
  if (SAFE_FOR_TEMPLATES) {
1708
2136
  _scrubTemplateExpressions2(dirty);
1709
2137
  }
@@ -1742,9 +2170,7 @@
1742
2170
  }
1743
2171
  /* Sanitize final string template-safe */
1744
2172
  if (SAFE_FOR_TEMPLATES) {
1745
- arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => {
1746
- serializedHTML = stringReplace(serializedHTML, expr, ' ');
1747
- });
2173
+ serializedHTML = _stripTemplateExpressions(serializedHTML);
1748
2174
  }
1749
2175
  return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(serializedHTML) : serializedHTML;
1750
2176
  };
@@ -1756,6 +2182,12 @@
1756
2182
  DOMPurify.clearConfig = function () {
1757
2183
  CONFIG = null;
1758
2184
  SET_CONFIG = false;
2185
+ // Drop any caller-supplied Trusted Types policy so it cannot poison later
2186
+ // `RETURN_TRUSTED_TYPE` output. The internal default policy (cached, and
2187
+ // never recreated — Trusted Types throws on duplicate names) is restored by
2188
+ // the next `_parseConfig`. See GHSA-vxr8-fq34-vvx9.
2189
+ trustedTypesPolicy = defaultTrustedTypesPolicy;
2190
+ emptyHTML = '';
1759
2191
  };
1760
2192
  DOMPurify.isValidAttribute = function (tag, attr, value) {
1761
2193
  /* Initialize shared config vars if necessary. */