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