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