@vaadin/bundles 25.2.0-rc1 → 25.2.0-rc2

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