@vaadin/bundles 24.10.4 → 24.10.6

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.
@@ -6,7 +6,7 @@
6
6
  \***********************************************/
7
7
  /***/ (function(module) {
8
8
 
9
- /*! @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 */
9
+ /*! @license DOMPurify 3.4.11 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.11/LICENSE */
10
10
 
11
11
  (function (global, factory) {
12
12
  true ? module.exports = factory() :
@@ -340,8 +340,14 @@
340
340
  );
341
341
  const DOCTYPE_NAME = seal(/^html$/i);
342
342
  const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);
343
+ // Markup-significant character probes used by _sanitizeElements.
344
+ // Shared module-level instances are safe despite the sticky /g flags:
345
+ // unapply() resets lastIndex for RegExp receivers before every call.
346
+ const ELEMENT_MARKUP_PROBE = seal(/<[/\w!]/g);
347
+ const COMMENT_MARKUP_PROBE = seal(/<[/\w]/g);
348
+ const FALLBACK_TAG_CLOSE = seal(/<\/no(script|embed|frames)/i);
349
+ const SELF_CLOSING_TAG = seal(/\/>/i);
343
350
 
344
- /* eslint-disable @typescript-eslint/indent */
345
351
  // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
346
352
  const NODE_TYPE = {
347
353
  element: 1,
@@ -352,7 +358,7 @@
352
358
  // Deprecated
353
359
  entityNode: 6,
354
360
  // Deprecated
355
- progressingInstruction: 7,
361
+ processingInstruction: 7,
356
362
  comment: 8,
357
363
  document: 9,
358
364
  documentType: 10,
@@ -413,10 +419,25 @@
413
419
  uponSanitizeShadowNode: []
414
420
  };
415
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
+ };
416
437
  function createDOMPurify() {
417
438
  let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
418
439
  const DOMPurify = root => createDOMPurify(root);
419
- DOMPurify.version = '3.4.8';
440
+ DOMPurify.version = '3.4.11';
420
441
  DOMPurify.removed = [];
421
442
  if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {
422
443
  // Not running in a browser, provide a factory function
@@ -461,23 +482,54 @@
461
482
  }
462
483
  let trustedTypesPolicy;
463
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;
464
491
  // Tracks whether we are already inside a call to the configured Trusted Types
465
- // policy's `createHTML`. If the supplied `TRUSTED_TYPES_POLICY.createHTML`
492
+ // policy (`createHTML` or `createScriptURL`). If a supplied policy callback
466
493
  // itself calls `DOMPurify.sanitize` (the cause of #1422), `sanitize` would
467
494
  // re-enter the policy and recurse until the stack overflows. We detect that
468
- // re-entry and throw a clear, actionable error instead.
469
- let IN_POLICY_CREATE_HTML = 0;
470
- const _createTrustedHTML = function _createTrustedHTML(html) {
471
- if (IN_POLICY_CREATE_HTML > 0) {
472
- 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.');
473
502
  }
474
- IN_POLICY_CREATE_HTML++;
503
+ };
504
+ const _createTrustedHTML = function _createTrustedHTML(html) {
505
+ _assertNotInTrustedTypesPolicy();
506
+ IN_TRUSTED_TYPES_POLICY++;
475
507
  try {
476
508
  return trustedTypesPolicy.createHTML(html);
477
509
  } finally {
478
- IN_POLICY_CREATE_HTML--;
510
+ IN_TRUSTED_TYPES_POLICY--;
479
511
  }
480
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
+ };
481
533
  const _document = document,
482
534
  implementation = _document.implementation,
483
535
  createNodeIterator = _document.createNodeIterator,
@@ -574,6 +626,13 @@
574
626
  let WHOLE_DOCUMENT = false;
575
627
  /* Track whether config is already set on this instance of DOMPurify. */
576
628
  let SET_CONFIG = false;
629
+ /* Pristine allowlist bindings captured at setConfig() time. On the
630
+ * persistent-config path sanitize() restores the sets from these before
631
+ * the per-walk hook clone-guard, so a hook's in-call widening cannot
632
+ * carry across calls. Null until setConfig() is called; reset by
633
+ * clearConfig(). */
634
+ let SET_CONFIG_ALLOWED_TAGS = null;
635
+ let SET_CONFIG_ALLOWED_ATTR = null;
577
636
  /* Decide if all elements (e.g. style, script) must be children of
578
637
  * document.body. By default, browsers might move them to document.head */
579
638
  let FORCE_BODY = false;
@@ -616,7 +675,17 @@
616
675
  let USE_PROFILES = {};
617
676
  /* Tags to ignore content of when KEEP_CONTENT is true */
618
677
  let FORBID_CONTENTS = null;
619
- 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']);
678
+ const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script',
679
+ // <selectedcontent> mirrors the selected <option>'s subtree, cloned by
680
+ // the UA (customizable <select>) — including any on* handlers — and the
681
+ // engine re-mirrors synchronously whenever a removal changes which
682
+ // option/selectedcontent is current, even inside DOMPurify's inert
683
+ // DOMParser document. Hoisting its children on removal re-inserts a fresh
684
+ // mirror target ahead of the walk, which the engine refills, looping
685
+ // forever (DoS) and amplifying output. Dropping its content on removal
686
+ // (rather than hoisting) breaks that cascade; the content is a duplicate
687
+ // of the option, which is sanitized on its own. See campaign-3 F1/F6.
688
+ 'selectedcontent', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
620
689
  /* Tags that are safe for data: URIs */
621
690
  let DATA_URI_TAGS = null;
622
691
  const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
@@ -632,8 +701,10 @@
632
701
  /* Allowed XHTML+XML namespaces */
633
702
  let ALLOWED_NAMESPACES = null;
634
703
  const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
635
- let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
636
- let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);
704
+ const DEFAULT_MATHML_TEXT_INTEGRATION_POINTS = freeze(['mi', 'mo', 'mn', 'ms', 'mtext']);
705
+ let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS);
706
+ const DEFAULT_HTML_INTEGRATION_POINTS = freeze(['annotation-xml']);
707
+ let HTML_INTEGRATION_POINTS = addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS);
637
708
  // Certain elements are allowed in both SVG and HTML
638
709
  // namespace. We need to specify them explicitly
639
710
  // so that they don't get erroneously deleted from
@@ -675,14 +746,32 @@
675
746
  // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
676
747
  transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
677
748
  /* Set configuration parameters */
678
- ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') && arrayIsArray(cfg.ALLOWED_TAGS) ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
679
- ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') && arrayIsArray(cfg.ALLOWED_ATTR) ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
680
- ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') && arrayIsArray(cfg.ALLOWED_NAMESPACES) ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
681
- 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;
682
- 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;
683
- FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS) ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
684
- FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') && arrayIsArray(cfg.FORBID_TAGS) ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({});
685
- FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') && arrayIsArray(cfg.FORBID_ATTR) ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({});
749
+ ALLOWED_TAGS = _resolveSetOption(cfg, 'ALLOWED_TAGS', DEFAULT_ALLOWED_TAGS, {
750
+ transform: transformCaseFunc
751
+ });
752
+ ALLOWED_ATTR = _resolveSetOption(cfg, 'ALLOWED_ATTR', DEFAULT_ALLOWED_ATTR, {
753
+ transform: transformCaseFunc
754
+ });
755
+ ALLOWED_NAMESPACES = _resolveSetOption(cfg, 'ALLOWED_NAMESPACES', DEFAULT_ALLOWED_NAMESPACES, {
756
+ transform: stringToString
757
+ });
758
+ URI_SAFE_ATTRIBUTES = _resolveSetOption(cfg, 'ADD_URI_SAFE_ATTR', DEFAULT_URI_SAFE_ATTRIBUTES, {
759
+ transform: transformCaseFunc,
760
+ base: DEFAULT_URI_SAFE_ATTRIBUTES
761
+ });
762
+ DATA_URI_TAGS = _resolveSetOption(cfg, 'ADD_DATA_URI_TAGS', DEFAULT_DATA_URI_TAGS, {
763
+ transform: transformCaseFunc,
764
+ base: DEFAULT_DATA_URI_TAGS
765
+ });
766
+ FORBID_CONTENTS = _resolveSetOption(cfg, 'FORBID_CONTENTS', DEFAULT_FORBID_CONTENTS, {
767
+ transform: transformCaseFunc
768
+ });
769
+ FORBID_TAGS = _resolveSetOption(cfg, 'FORBID_TAGS', clone({}), {
770
+ transform: transformCaseFunc
771
+ });
772
+ FORBID_ATTR = _resolveSetOption(cfg, 'FORBID_ATTR', clone({}), {
773
+ transform: transformCaseFunc
774
+ });
686
775
  USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;
687
776
  ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
688
777
  ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
@@ -701,8 +790,8 @@
701
790
  IN_PLACE = cfg.IN_PLACE || false; // Default false
702
791
  IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp
703
792
  NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace
704
- 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
705
- 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
793
+ 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
794
+ 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
706
795
  const customElementHandling = objectHasOwnProperty(cfg, 'CUSTOM_ELEMENT_HANDLING') && cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING === 'object' ? clone(cfg.CUSTOM_ELEMENT_HANDLING) : create(null);
707
796
  CUSTOM_ELEMENT_HANDLING = create(null);
708
797
  if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) {
@@ -714,6 +803,7 @@
714
803
  if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') {
715
804
  CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined
716
805
  }
806
+ seal(CUSTOM_ELEMENT_HANDLING);
717
807
  if (SAFE_FOR_TEMPLATES) {
718
808
  ALLOW_DATA_ATTR = false;
719
809
  }
@@ -797,6 +887,13 @@
797
887
  addToSet(ALLOWED_TAGS, ['tbody']);
798
888
  delete FORBID_TAGS.tbody;
799
889
  }
890
+ // Re-derive the active Trusted Types policy from this configuration on
891
+ // every parse. The active policy must never be sticky closure state that
892
+ // outlives the config that set it: a caller-supplied policy left in place
893
+ // after `clearConfig()` — or after a later call that supplied none, or
894
+ // `TRUSTED_TYPES_POLICY: null` — could sign a subsequent "default"
895
+ // `RETURN_TRUSTED_TYPE` result with a foreign, possibly unsafe policy.
896
+ // See GHSA-vxr8-fq34-vvx9.
800
897
  if (cfg.TRUSTED_TYPES_POLICY) {
801
898
  if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
802
899
  throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
@@ -804,7 +901,7 @@
804
901
  if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
805
902
  throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
806
903
  }
807
- // Overwrite existing TrustedTypes policy.
904
+ // A caller-supplied policy applies to this configuration only.
808
905
  const previousTrustedTypesPolicy = trustedTypesPolicy;
809
906
  trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
810
907
  // Sign local variables required by `sanitize`. If the supplied policy's
@@ -817,35 +914,34 @@
817
914
  trustedTypesPolicy = previousTrustedTypesPolicy;
818
915
  throw error;
819
916
  }
917
+ } else if (cfg.TRUSTED_TYPES_POLICY === null) {
918
+ // Explicit opt-out for this call: perform no Trusted Types signing and
919
+ // create nothing (so a strict `trusted-types` CSP that disallows a
920
+ // `dompurify` policy can still call `sanitize` from inside its own
921
+ // policy — see #1422). Resetting to `undefined` rather than a sticky
922
+ // `null` also drops any previously retained caller policy, so it cannot
923
+ // resurface on a later call, while still allowing the next config-less
924
+ // call to restore the internal default policy. See GHSA-vxr8-fq34-vvx9.
925
+ trustedTypesPolicy = undefined;
926
+ emptyHTML = '';
820
927
  } else {
821
- // Uninitialized policy, attempt to initialize the internal dompurify policy.
822
- if (trustedTypesPolicy === undefined && cfg.TRUSTED_TYPES_POLICY !== null) {
823
- trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
824
- }
825
- // If creating the internal policy succeeded sign internal variables.
826
- // Note: a falsy `trustedTypesPolicy` (null when policy creation failed or
827
- // was skipped via `TRUSTED_TYPES_POLICY: null`, or undefined when no
828
- // policy has been initialized yet) must be excluded here, otherwise we
829
- // would call `.createHTML` on a non-policy and throw. See #1422.
928
+ // No policy supplied: keep the currently active policy if one is set — a
929
+ // previously supplied policy is intentionally sticky across config-less
930
+ // calls — otherwise fall back to the instance's own internal policy,
931
+ // created at most once. (A policy supplied for a *single* call still
932
+ // lingers by design; what must not linger is a policy whose configuration
933
+ // has been torn down via `clearConfig()`, which restores the default.)
934
+ if (trustedTypesPolicy === undefined) {
935
+ trustedTypesPolicy = _getDefaultTrustedTypesPolicy();
936
+ }
937
+ // Sign internal variables only when a policy is active. A falsy policy
938
+ // (Trusted Types unsupported, creation failed, or an explicit opt-out)
939
+ // leaves `emptyHTML` as a plain string, so we never call `.createHTML` on
940
+ // a non-policy and throw. See #1422.
830
941
  if (trustedTypesPolicy && typeof emptyHTML === 'string') {
831
942
  emptyHTML = _createTrustedHTML('');
832
943
  }
833
944
  }
834
- /*
835
- * Mirror the clone-before-mutate pattern already applied above for
836
- * cfg.ADD_TAGS / cfg.ADD_ATTR: if any uponSanitize* hook is
837
- * registered AND the set still points at the default constant,
838
- * clone it. The hook then mutates the clone (in-call widening
839
- * still works exactly as documented) and the next default-cfg
840
- * call rebinds to the untouched original via the reassignment at
841
- * the top of this function.
842
- */
843
- if ((hooks.uponSanitizeElement.length > 0 || hooks.uponSanitizeAttribute.length > 0) && ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
844
- ALLOWED_TAGS = clone(ALLOWED_TAGS);
845
- }
846
- if (hooks.uponSanitizeAttribute.length > 0 && ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
847
- ALLOWED_ATTR = clone(ALLOWED_ATTR);
848
- }
849
945
  // Prevent further manipulation of configuration.
850
946
  // Not available in IE8, Safari 5, etc.
851
947
  if (freeze) {
@@ -858,6 +954,77 @@
858
954
  * correctly. */
859
955
  const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
860
956
  const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
957
+ /**
958
+ * Namespace rules for an element in the SVG namespace.
959
+ *
960
+ * @param tagName the element's lowercase tag name
961
+ * @param parent the (possibly simulated) parent node
962
+ * @param parentTagName the parent's lowercase tag name
963
+ * @returns true if a spec-compliant parser could produce this element
964
+ */
965
+ const _checkSvgNamespace = function _checkSvgNamespace(tagName, parent, parentTagName) {
966
+ // The only way to switch from HTML namespace to SVG
967
+ // is via <svg>. If it happens via any other tag, then
968
+ // it should be killed.
969
+ if (parent.namespaceURI === HTML_NAMESPACE) {
970
+ return tagName === 'svg';
971
+ }
972
+ // The only way to switch from MathML to SVG is via <svg>
973
+ // if the parent is either <annotation-xml> or a MathML
974
+ // text integration point.
975
+ if (parent.namespaceURI === MATHML_NAMESPACE) {
976
+ return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
977
+ }
978
+ // We only allow elements that are defined in SVG
979
+ // spec. All others are disallowed in SVG namespace.
980
+ return Boolean(ALL_SVG_TAGS[tagName]);
981
+ };
982
+ /**
983
+ * Namespace rules for an element in the MathML namespace.
984
+ *
985
+ * @param tagName the element's lowercase tag name
986
+ * @param parent the (possibly simulated) parent node
987
+ * @param parentTagName the parent's lowercase tag name
988
+ * @returns true if a spec-compliant parser could produce this element
989
+ */
990
+ const _checkMathMlNamespace = function _checkMathMlNamespace(tagName, parent, parentTagName) {
991
+ // The only way to switch from HTML namespace to MathML
992
+ // is via <math>. If it happens via any other tag, then
993
+ // it should be killed.
994
+ if (parent.namespaceURI === HTML_NAMESPACE) {
995
+ return tagName === 'math';
996
+ }
997
+ // The only way to switch from SVG to MathML is via
998
+ // <math> and HTML integration points
999
+ if (parent.namespaceURI === SVG_NAMESPACE) {
1000
+ return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
1001
+ }
1002
+ // We only allow elements that are defined in MathML
1003
+ // spec. All others are disallowed in MathML namespace.
1004
+ return Boolean(ALL_MATHML_TAGS[tagName]);
1005
+ };
1006
+ /**
1007
+ * Namespace rules for an element in the HTML namespace.
1008
+ *
1009
+ * @param tagName the element's lowercase tag name
1010
+ * @param parent the (possibly simulated) parent node
1011
+ * @param parentTagName the parent's lowercase tag name
1012
+ * @returns true if a spec-compliant parser could produce this element
1013
+ */
1014
+ const _checkHtmlNamespace = function _checkHtmlNamespace(tagName, parent, parentTagName) {
1015
+ // The only way to switch from SVG to HTML is via
1016
+ // HTML integration points, and from MathML to HTML
1017
+ // is via MathML text integration points
1018
+ if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
1019
+ return false;
1020
+ }
1021
+ if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
1022
+ return false;
1023
+ }
1024
+ // We disallow tags that are specific for MathML
1025
+ // or SVG and should never appear in HTML namespace
1026
+ return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
1027
+ };
861
1028
  /**
862
1029
  * @param element a DOM element whose namespace is being checked
863
1030
  * @returns Return false if the element has a
@@ -880,51 +1047,13 @@
880
1047
  return false;
881
1048
  }
882
1049
  if (element.namespaceURI === SVG_NAMESPACE) {
883
- // The only way to switch from HTML namespace to SVG
884
- // is via <svg>. If it happens via any other tag, then
885
- // it should be killed.
886
- if (parent.namespaceURI === HTML_NAMESPACE) {
887
- return tagName === 'svg';
888
- }
889
- // The only way to switch from MathML to SVG is via`
890
- // svg if parent is either <annotation-xml> or MathML
891
- // text integration points.
892
- if (parent.namespaceURI === MATHML_NAMESPACE) {
893
- return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
894
- }
895
- // We only allow elements that are defined in SVG
896
- // spec. All others are disallowed in SVG namespace.
897
- return Boolean(ALL_SVG_TAGS[tagName]);
1050
+ return _checkSvgNamespace(tagName, parent, parentTagName);
898
1051
  }
899
1052
  if (element.namespaceURI === MATHML_NAMESPACE) {
900
- // The only way to switch from HTML namespace to MathML
901
- // is via <math>. If it happens via any other tag, then
902
- // it should be killed.
903
- if (parent.namespaceURI === HTML_NAMESPACE) {
904
- return tagName === 'math';
905
- }
906
- // The only way to switch from SVG to MathML is via
907
- // <math> and HTML integration points
908
- if (parent.namespaceURI === SVG_NAMESPACE) {
909
- return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
910
- }
911
- // We only allow elements that are defined in MathML
912
- // spec. All others are disallowed in MathML namespace.
913
- return Boolean(ALL_MATHML_TAGS[tagName]);
1053
+ return _checkMathMlNamespace(tagName, parent, parentTagName);
914
1054
  }
915
1055
  if (element.namespaceURI === HTML_NAMESPACE) {
916
- // The only way to switch from SVG to HTML is via
917
- // HTML integration points, and from MathML to HTML
918
- // is via MathML text integration points
919
- if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
920
- return false;
921
- }
922
- if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
923
- return false;
924
- }
925
- // We disallow tags that are specific for MathML
926
- // or SVG and should never appear in HTML namespace
927
- return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
1056
+ return _checkHtmlNamespace(tagName, parent, parentTagName);
928
1057
  }
929
1058
  // For XHTML and XML documents that support custom namespaces
930
1059
  if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
@@ -949,7 +1078,74 @@
949
1078
  // eslint-disable-next-line unicorn/prefer-dom-node-remove
950
1079
  getParentNode(node).removeChild(node);
951
1080
  } catch (_) {
1081
+ /* The normal detach failed — this is reached for a parentless node
1082
+ (getParentNode() is null, so .removeChild throws). Element.prototype
1083
+ .remove() is itself a spec no-op on a parentless node, so a recorded
1084
+ "removal" would otherwise hand the caller back an intact,
1085
+ payload-bearing node (e.g. a detached IN_PLACE root the mXSS canary or
1086
+ the style-with-element-child rule decided to kill). Fail closed by
1087
+ throwing — exactly as a clobbered root does at the IN_PLACE entry —
1088
+ rather than trying to "neutralize" the node via its own methods.
1089
+ Neutralizing would mean calling getAttributeNames()/removeAttribute()
1090
+ on the node, both of which a <form> root can clobber via a named child
1091
+ (and _isClobbered does not even probe getAttributeNames), so the
1092
+ neutralize step could itself be silently defeated, leaving the payload
1093
+ intact. A throw touches only the cached, clobber-safe remove() and
1094
+ getParentNode(). Generalizes GHSA-r47g-fvhr-h676 (clobbered-form root)
1095
+ to every root-kill reason. REPORT-3.
1096
+ This lives inside the catch, so it never fires for a normally-removed
1097
+ in-tree node: those have a parent, removeChild() succeeds, and the
1098
+ catch is not entered. Only a kept (parentless) root reaches here. */
952
1099
  remove(node);
1100
+ if (!getParentNode(node)) {
1101
+ throw typeErrorCreate('a node selected for removal could not be detached from its tree ' + 'and cannot be safely returned; refusing to sanitize in place');
1102
+ }
1103
+ }
1104
+ };
1105
+ /**
1106
+ * _neutralizeRoot
1107
+ *
1108
+ * Fail-closed teardown of an in-place root after the sanitize walk aborts
1109
+ * (campaign-3 F2). An internal throw mid-walk — e.g. a page-registered
1110
+ * custom element's reaction detaches a node so `_forceRemove`'s deliberate
1111
+ * parentless guard throws, or any other re-entrant engine mutation — would
1112
+ * otherwise leave the caller's *live* tree half-sanitized, with everything
1113
+ * after the abort point still carrying its handlers. There is no safe way
1114
+ * to resume the walk (the tree mutated under us), so we strip the root bare:
1115
+ * remove every child and every attribute, then let the caller's catch see
1116
+ * the original error. Clobber-safe (cached `remove`/`childNodes`/`attributes`
1117
+ * getters; the root was already clobber-pre-flighted at the IN_PLACE entry).
1118
+ *
1119
+ * @param root the in-place root to empty
1120
+ */
1121
+ const _neutralizeRoot = function _neutralizeRoot(root) {
1122
+ const childNodes = getChildNodes(root);
1123
+ if (childNodes) {
1124
+ const snapshot = [];
1125
+ arrayForEach(childNodes, child => {
1126
+ arrayPush(snapshot, child);
1127
+ });
1128
+ arrayForEach(snapshot, child => {
1129
+ try {
1130
+ remove(child);
1131
+ } catch (_) {
1132
+ /* Best-effort teardown; a still-attached child is handled below */
1133
+ }
1134
+ });
1135
+ }
1136
+ const attributes = getAttributes(root);
1137
+ if (attributes) {
1138
+ for (let i = attributes.length - 1; i >= 0; --i) {
1139
+ const attribute = attributes[i];
1140
+ const name = attribute && attribute.name;
1141
+ if (typeof name === 'string') {
1142
+ try {
1143
+ root.removeAttribute(name);
1144
+ } catch (_) {
1145
+ /* Clobbered removeAttribute — ignore (fail-closed best effort) */
1146
+ }
1147
+ }
1148
+ }
953
1149
  }
954
1150
  };
955
1151
  /**
@@ -984,6 +1180,72 @@
984
1180
  }
985
1181
  }
986
1182
  };
1183
+ /**
1184
+ * _stripDisallowedAttributes
1185
+ *
1186
+ * Removes every attribute the active configuration does not allow from a
1187
+ * single element, using the same allowlist as the main attribute pass (so
1188
+ * `on*` handlers go, but no `/^on/` blocklist is introduced). Used only to
1189
+ * neutralise nodes that are being discarded from an in-place tree.
1190
+ *
1191
+ * @param element the element to strip
1192
+ */
1193
+ const _stripDisallowedAttributes = function _stripDisallowedAttributes(element) {
1194
+ const attributes = getAttributes(element);
1195
+ if (!attributes) {
1196
+ return;
1197
+ }
1198
+ for (let i = attributes.length - 1; i >= 0; --i) {
1199
+ const attribute = attributes[i];
1200
+ const name = attribute && attribute.name;
1201
+ if (typeof name !== 'string' || ALLOWED_ATTR[transformCaseFunc(name)]) {
1202
+ continue;
1203
+ }
1204
+ try {
1205
+ element.removeAttribute(name);
1206
+ } catch (_) {
1207
+ /* Clobbered removeAttribute on a doomed node — ignore */
1208
+ }
1209
+ }
1210
+ };
1211
+ /**
1212
+ * _neutralizeSubtree
1213
+ *
1214
+ * Completes the audit-5 F1 fix across every removal path. The KEEP_CONTENT
1215
+ * move-hoist neutralises only disallowed-tag removals; clobber, mXSS-canary,
1216
+ * namespace, comment, processing-instruction and KEEP_CONTENT:false removals
1217
+ * all drop their subtree wholesale via `_forceRemove`. On the IN_PLACE path
1218
+ * those dropped nodes are detached from the caller's LIVE tree but a
1219
+ * handler-bearing original among them (an `<img onerror>`/`<video>` that was
1220
+ * loading) keeps its queued resource event, which fires in page scope after
1221
+ * sanitize returns. This walks a removed subtree and strips every attribute
1222
+ * the active configuration does not allow — so `on*` handlers are cancelled
1223
+ * through the SAME allowlist that governs kept nodes, not a separate `/^on/`
1224
+ * blocklist. Run synchronously before sanitize returns, i.e. before any
1225
+ * queued event can fire. Hook-free by design: these nodes leave the output,
1226
+ * so firing attribute hooks for them would be surprising. Clobber-safe reads;
1227
+ * a doomed clobbered node may shadow `removeAttribute` (its own attributes are
1228
+ * irrelevant — it is discarded — while its non-clobbered descendants, e.g.
1229
+ * the `<img>`, are reached and scrubbed).
1230
+ *
1231
+ * @param root the root of a removed subtree to neutralise
1232
+ */
1233
+ const _neutralizeSubtree = function _neutralizeSubtree(root) {
1234
+ const stack = [root];
1235
+ while (stack.length > 0) {
1236
+ const node = stack.pop();
1237
+ const nodeType = getNodeType ? getNodeType(node) : node.nodeType;
1238
+ if (nodeType === NODE_TYPE.element) {
1239
+ _stripDisallowedAttributes(node);
1240
+ }
1241
+ const childNodes = getChildNodes(node);
1242
+ if (childNodes) {
1243
+ for (let i = childNodes.length - 1; i >= 0; --i) {
1244
+ stack.push(childNodes[i]);
1245
+ }
1246
+ }
1247
+ }
1248
+ };
987
1249
  /**
988
1250
  * _initDocument
989
1251
  *
@@ -1045,6 +1307,20 @@
1045
1307
  // eslint-disable-next-line no-bitwise
1046
1308
  NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
1047
1309
  };
1310
+ /**
1311
+ * Replace template expression syntax (mustache, ERB, template
1312
+ * literal) with a space; shared by all SAFE_FOR_TEMPLATES scrub
1313
+ * sites. Order matters: mustache, then ERB, then template literal.
1314
+ *
1315
+ * @param value the string to scrub
1316
+ * @returns the scrubbed string
1317
+ */
1318
+ const _stripTemplateExpressions = function _stripTemplateExpressions(value) {
1319
+ value = stringReplace(value, MUSTACHE_EXPR$1, ' ');
1320
+ value = stringReplace(value, ERB_EXPR$1, ' ');
1321
+ value = stringReplace(value, TMPLIT_EXPR$1, ' ');
1322
+ return value;
1323
+ };
1048
1324
  /**
1049
1325
  * Strip template-engine expressions ({{...}}, ${...}, <%...%>) from the
1050
1326
  * character data of an element subtree. Used as the final safety net for
@@ -1065,29 +1341,27 @@
1065
1341
  * @param node The root element whose character data should be scrubbed.
1066
1342
  */
1067
1343
  const _scrubTemplateExpressions2 = function _scrubTemplateExpressions(node) {
1068
- var _node$querySelectorAl, _node$querySelectorAl2;
1344
+ var _node$querySelectorAl;
1069
1345
  node.normalize();
1070
1346
  const walker = createNodeIterator.call(node.ownerDocument || node, node,
1071
1347
  // eslint-disable-next-line no-bitwise
1072
1348
  NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_CDATA_SECTION | NodeFilter.SHOW_PROCESSING_INSTRUCTION, null);
1073
1349
  let currentNode = walker.nextNode();
1074
1350
  while (currentNode) {
1075
- let data = currentNode.data;
1076
- arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => {
1077
- data = stringReplace(data, expr, ' ');
1078
- });
1079
- currentNode.data = data;
1351
+ currentNode.data = _stripTemplateExpressions(currentNode.data);
1080
1352
  currentNode = walker.nextNode();
1081
1353
  }
1082
1354
  // NodeIterator does not descend into <template>.content per the DOM spec,
1083
1355
  // so we must explicitly recurse into each template's content fragment,
1084
1356
  // mirroring the approach used by _sanitizeShadowDOM.
1085
- 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 : [];
1086
- arrayForEach(Array.from(templates), tmpl => {
1087
- if (_isDocumentFragment(tmpl.content)) {
1088
- _scrubTemplateExpressions2(tmpl.content);
1089
- }
1090
- });
1357
+ const templates = (_node$querySelectorAl = node.querySelectorAll) === null || _node$querySelectorAl === void 0 ? void 0 : _node$querySelectorAl.call(node, 'template');
1358
+ if (templates) {
1359
+ arrayForEach(templates, tmpl => {
1360
+ if (_isDocumentFragment(tmpl.content)) {
1361
+ _scrubTemplateExpressions2(tmpl.content);
1362
+ }
1363
+ });
1364
+ }
1091
1365
  };
1092
1366
  /**
1093
1367
  * _isClobbered
@@ -1183,10 +1457,104 @@
1183
1457
  }
1184
1458
  };
1185
1459
  function _executeHooks(hooks, currentNode, data) {
1460
+ if (hooks.length === 0) {
1461
+ return;
1462
+ }
1186
1463
  arrayForEach(hooks, hook => {
1187
1464
  hook.call(DOMPurify, currentNode, data, CONFIG);
1188
1465
  });
1189
1466
  }
1467
+ /**
1468
+ * Structural-threat checks that condemn a node regardless of the
1469
+ * allowlists: mXSS via namespace confusion, risky CSS construction,
1470
+ * processing instructions, markup-bearing comments. Pure predicate;
1471
+ * the caller removes. Check order is load-bearing.
1472
+ *
1473
+ * @param currentNode the node to inspect
1474
+ * @param tagName the node's transformCaseFunc'd tag name
1475
+ * @return true if the node must be removed
1476
+ */
1477
+ const _isUnsafeNode = function _isUnsafeNode(currentNode, tagName) {
1478
+ /* Detect mXSS attempts abusing namespace confusion */
1479
+ if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.textContent) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.innerHTML)) {
1480
+ return true;
1481
+ }
1482
+ /* Remove risky CSS construction leading to mXSS */
1483
+ if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {
1484
+ return true;
1485
+ }
1486
+ /* Remove any occurrence of processing instructions */
1487
+ if (currentNode.nodeType === NODE_TYPE.processingInstruction) {
1488
+ return true;
1489
+ }
1490
+ /* Remove any kind of possibly harmful comments */
1491
+ if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, currentNode.data)) {
1492
+ return true;
1493
+ }
1494
+ return false;
1495
+ };
1496
+ /**
1497
+ * Handle a node whose tag is forbidden or not allowlisted: keep
1498
+ * allowed custom elements (false return exits _sanitizeElements
1499
+ * early - namespace/fallback checks and the afterSanitizeElements
1500
+ * hook are intentionally skipped for kept custom elements), else
1501
+ * hoist content per KEEP_CONTENT and remove.
1502
+ *
1503
+ * @param currentNode the disallowed node
1504
+ * @param tagName the node's transformCaseFunc'd tag name
1505
+ * @return true if the node was removed, false if kept
1506
+ */
1507
+ const _sanitizeDisallowedNode = function _sanitizeDisallowedNode(currentNode, tagName) {
1508
+ /* Check if we have a custom element to handle */
1509
+ if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
1510
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
1511
+ return false;
1512
+ }
1513
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
1514
+ return false;
1515
+ }
1516
+ }
1517
+ /* Keep content except for bad-listed elements.
1518
+ Use the cached prototype getters exclusively — the previous code
1519
+ had `|| currentNode.parentNode` / `|| currentNode.childNodes`
1520
+ fallbacks, but the cached getters always return the canonical
1521
+ value (or null for a real parent-less node), so the fallback
1522
+ path was dead in safe cases and a clobbering surface in unsafe
1523
+ ones. Falsy cached results stay falsy; the `if (childNodes &&
1524
+ parentNode)` check already gates correctly. */
1525
+ if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
1526
+ const parentNode = getParentNode(currentNode);
1527
+ const childNodes = getChildNodes(currentNode);
1528
+ if (childNodes && parentNode) {
1529
+ const childCount = childNodes.length;
1530
+ /* In-place: hoist the *original* children so the iterator visits
1531
+ and sanitises them through the same allowlist pass as every other
1532
+ node. The caller built the tree in the live document, so the
1533
+ originals carry already-queued resource events (`<img onerror>`,
1534
+ `<video>`/`<audio>` error, lazy/`onload`, …); cloning would leave
1535
+ those originals detached but still armed, firing in page scope
1536
+ while the returned tree looked clean. Moving is safe in-place: the
1537
+ root is pre-validated as an allowed tag and so is never the node
1538
+ being removed, which keeps `parentNode` inside the iterator root
1539
+ and the relocated child inside the serialised tree.
1540
+ Otherwise (string / DOM-copy paths): clone. The iterator is rooted
1541
+ at — and the result serialised from — `body`, so a restrictive
1542
+ ALLOWED_TAGS that removes `body` itself must leave its content in
1543
+ place, which only cloning does; and those paths parse into an
1544
+ inert document, so their discarded originals never had a queued
1545
+ event to neutralise.
1546
+ `childNodes` is live; a tail-to-head walk keeps `childNodes[i]`
1547
+ valid whether we move (drops the trailing entry) or clone (leaves
1548
+ the list intact). */
1549
+ for (let i = childCount - 1; i >= 0; --i) {
1550
+ const hoisted = IN_PLACE ? childNodes[i] : cloneNode(childNodes[i], true);
1551
+ parentNode.insertBefore(hoisted, getNextSibling(currentNode));
1552
+ }
1553
+ }
1554
+ }
1555
+ _forceRemove(currentNode);
1556
+ return true;
1557
+ };
1190
1558
  /**
1191
1559
  * _sanitizeElements
1192
1560
  *
@@ -1197,7 +1565,6 @@
1197
1565
  * @return true if node was killed, false if left alive
1198
1566
  */
1199
1567
  const _sanitizeElements = function _sanitizeElements(currentNode) {
1200
- let content = null;
1201
1568
  /* Execute a hook if present */
1202
1569
  _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
1203
1570
  /* Check if element is clobbered or can clobber */
@@ -1212,58 +1579,14 @@
1212
1579
  tagName,
1213
1580
  allowedTags: ALLOWED_TAGS
1214
1581
  });
1215
- /* Detect mXSS attempts abusing namespace confusion */
1216
- if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) {
1217
- _forceRemove(currentNode);
1218
- return true;
1219
- }
1220
- /* Remove risky CSS construction leading to mXSS */
1221
- if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {
1222
- _forceRemove(currentNode);
1223
- return true;
1224
- }
1225
- /* Remove any occurrence of processing instructions */
1226
- if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {
1227
- _forceRemove(currentNode);
1228
- return true;
1229
- }
1230
- /* Remove any kind of possibly harmful comments */
1231
- if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) {
1582
+ /* Remove mXSS vectors, processing instructions and risky comments */
1583
+ if (_isUnsafeNode(currentNode, tagName)) {
1232
1584
  _forceRemove(currentNode);
1233
1585
  return true;
1234
1586
  }
1235
1587
  /* Remove element if anything forbids its presence */
1236
1588
  if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) {
1237
- /* Check if we have a custom element to handle */
1238
- if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
1239
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
1240
- return false;
1241
- }
1242
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
1243
- return false;
1244
- }
1245
- }
1246
- /* Keep content except for bad-listed elements.
1247
- Use the cached prototype getters exclusively — the previous code
1248
- had `|| currentNode.parentNode` / `|| currentNode.childNodes`
1249
- fallbacks, but the cached getters always return the canonical
1250
- value (or null for a real parent-less node), so the fallback
1251
- path was dead in safe cases and a clobbering surface in unsafe
1252
- ones. Falsy cached results stay falsy; the `if (childNodes &&
1253
- parentNode)` check already gates correctly. */
1254
- if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
1255
- const parentNode = getParentNode(currentNode);
1256
- const childNodes = getChildNodes(currentNode);
1257
- if (childNodes && parentNode) {
1258
- const childCount = childNodes.length;
1259
- for (let i = childCount - 1; i >= 0; --i) {
1260
- const childClone = cloneNode(childNodes[i], true);
1261
- parentNode.insertBefore(childClone, getNextSibling(currentNode));
1262
- }
1263
- }
1264
- }
1265
- _forceRemove(currentNode);
1266
- return true;
1589
+ return _sanitizeDisallowedNode(currentNode, tagName);
1267
1590
  }
1268
1591
  /* Check whether element has a valid namespace.
1269
1592
  Realm-safe check (GHSA-hpcv-96wg-7vj8): use the cached Node.prototype
@@ -1277,17 +1600,14 @@
1277
1600
  return true;
1278
1601
  }
1279
1602
  /* Make sure that older browsers don't get fallback-tag mXSS */
1280
- if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {
1603
+ if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(FALLBACK_TAG_CLOSE, currentNode.innerHTML)) {
1281
1604
  _forceRemove(currentNode);
1282
1605
  return true;
1283
1606
  }
1284
1607
  /* Sanitize element content to be template-safe */
1285
1608
  if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
1286
1609
  /* Get the element's text content */
1287
- content = currentNode.textContent;
1288
- arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => {
1289
- content = stringReplace(content, expr, ' ');
1290
- });
1610
+ const content = _stripTemplateExpressions(currentNode.textContent);
1291
1611
  if (currentNode.textContent !== content) {
1292
1612
  arrayPush(DOMPurify.removed, {
1293
1613
  element: currentNode.cloneNode()
@@ -1322,7 +1642,7 @@
1322
1642
  (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
1323
1643
  XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
1324
1644
  We don't need to check the value; it's always URI safe. */
1325
- 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]) {
1645
+ if (ALLOW_DATA_ATTR && regExpTest(DATA_ATTR$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) ; else if (!nameIsPermitted) {
1326
1646
  if (
1327
1647
  // First condition does a very basic check if a) it's basically a valid custom element tagname AND
1328
1648
  // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
@@ -1354,6 +1674,63 @@
1354
1674
  const _isBasicCustomElement = function _isBasicCustomElement(tagName) {
1355
1675
  return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT$1, tagName);
1356
1676
  };
1677
+ /**
1678
+ * Wrap an attribute value in the matching Trusted Types object when
1679
+ * the active policy requires it. Namespaced attributes pass through
1680
+ * unchanged (no TT support yet, see
1681
+ * https://bugs.chromium.org/p/chromium/issues/detail?id=1305293).
1682
+ *
1683
+ * @param lcTag lowercase tag name of the containing element
1684
+ * @param lcName lowercase attribute name
1685
+ * @param namespaceURI the attribute's namespace, if any
1686
+ * @param value the attribute value to wrap
1687
+ * @return the value, wrapped when Trusted Types demand it
1688
+ */
1689
+ const _applyTrustedTypesToAttribute = function _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value) {
1690
+ if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function' && !namespaceURI) {
1691
+ switch (trustedTypes.getAttributeType(lcTag, lcName)) {
1692
+ case 'TrustedHTML':
1693
+ {
1694
+ return _createTrustedHTML(value);
1695
+ }
1696
+ case 'TrustedScriptURL':
1697
+ {
1698
+ return _createTrustedScriptURL(value);
1699
+ }
1700
+ }
1701
+ }
1702
+ return value;
1703
+ };
1704
+ /**
1705
+ * Write a modified attribute value back onto the element. On
1706
+ * success, re-probe for clobbering introduced by the new value and
1707
+ * remove the element when found; otherwise pop the removal entry
1708
+ * recorded by the earlier _removeAttribute (long-standing pairing
1709
+ * with the SANITIZE_NAMED_PROPS path - do not "fix" casually). On
1710
+ * failure, remove the attribute instead.
1711
+ *
1712
+ * @param currentNode the element carrying the attribute
1713
+ * @param name the attribute name as present on the element
1714
+ * @param namespaceURI the attribute's namespace, if any
1715
+ * @param value the new attribute value
1716
+ */
1717
+ const _setAttributeValue = function _setAttributeValue(currentNode, name, namespaceURI, value) {
1718
+ try {
1719
+ if (namespaceURI) {
1720
+ currentNode.setAttributeNS(namespaceURI, name, value);
1721
+ } else {
1722
+ /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
1723
+ currentNode.setAttribute(name, value);
1724
+ }
1725
+ if (_isClobbered(currentNode)) {
1726
+ _forceRemove(currentNode);
1727
+ } else {
1728
+ arrayPop(DOMPurify.removed);
1729
+ }
1730
+ } catch (_) {
1731
+ _removeAttribute(name, currentNode);
1732
+ }
1733
+ };
1357
1734
  /**
1358
1735
  * _sanitizeAttributes
1359
1736
  *
@@ -1380,6 +1757,7 @@
1380
1757
  forceKeepAttr: undefined
1381
1758
  };
1382
1759
  let l = attributes.length;
1760
+ const lcTag = transformCaseFunc(currentNode.nodeName);
1383
1761
  /* Go backwards over all attributes; safely remove bad ones */
1384
1762
  while (l--) {
1385
1763
  const attr = attributes[l];
@@ -1417,7 +1795,7 @@
1417
1795
  _removeAttribute(name, currentNode);
1418
1796
  continue;
1419
1797
  }
1420
- /* Did the hooks approve of the attribute? */
1798
+ /* Did the hooks force-keep the attribute? */
1421
1799
  if (hookEvent.forceKeepAttr) {
1422
1800
  continue;
1423
1801
  }
@@ -1427,56 +1805,24 @@
1427
1805
  continue;
1428
1806
  }
1429
1807
  /* Work around a security issue in jQuery 3.0 */
1430
- if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
1808
+ if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(SELF_CLOSING_TAG, value)) {
1431
1809
  _removeAttribute(name, currentNode);
1432
1810
  continue;
1433
1811
  }
1434
1812
  /* Sanitize attribute content to be template-safe */
1435
1813
  if (SAFE_FOR_TEMPLATES) {
1436
- arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => {
1437
- value = stringReplace(value, expr, ' ');
1438
- });
1814
+ value = _stripTemplateExpressions(value);
1439
1815
  }
1440
1816
  /* Is `value` valid for this attribute? */
1441
- const lcTag = transformCaseFunc(currentNode.nodeName);
1442
1817
  if (!_isValidAttribute(lcTag, lcName, value)) {
1443
1818
  _removeAttribute(name, currentNode);
1444
1819
  continue;
1445
1820
  }
1446
1821
  /* Handle attributes that require Trusted Types */
1447
- if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {
1448
- if (namespaceURI) ; else {
1449
- switch (trustedTypes.getAttributeType(lcTag, lcName)) {
1450
- case 'TrustedHTML':
1451
- {
1452
- value = _createTrustedHTML(value);
1453
- break;
1454
- }
1455
- case 'TrustedScriptURL':
1456
- {
1457
- value = trustedTypesPolicy.createScriptURL(value);
1458
- break;
1459
- }
1460
- }
1461
- }
1462
- }
1822
+ value = _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value);
1463
1823
  /* Handle invalid data-* attribute set by try-catching it */
1464
1824
  if (value !== initValue) {
1465
- try {
1466
- if (namespaceURI) {
1467
- currentNode.setAttributeNS(namespaceURI, name, value);
1468
- } else {
1469
- /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
1470
- currentNode.setAttribute(name, value);
1471
- }
1472
- if (_isClobbered(currentNode)) {
1473
- _forceRemove(currentNode);
1474
- } else {
1475
- arrayPop(DOMPurify.removed);
1476
- }
1477
- } catch (_) {
1478
- _removeAttribute(name, currentNode);
1479
- }
1825
+ _setAttributeValue(currentNode, name, namespaceURI, value);
1480
1826
  }
1481
1827
  }
1482
1828
  /* Execute a hook if present */
@@ -1518,9 +1864,9 @@
1518
1864
  iterator also surfaces. */
1519
1865
  const shadowNodeType = getNodeType ? getNodeType(shadowNode) : shadowNode.nodeType;
1520
1866
  if (shadowNodeType === NODE_TYPE.element) {
1521
- const innerSr = getShadowRoot ? getShadowRoot(shadowNode) : shadowNode.shadowRoot;
1867
+ const innerSr = getShadowRoot(shadowNode);
1522
1868
  if (_isDocumentFragment(innerSr)) {
1523
- _sanitizeAttachedShadowRoots2(innerSr);
1869
+ _sanitizeAttachedShadowRoots(innerSr);
1524
1870
  _sanitizeShadowDOM2(innerSr);
1525
1871
  }
1526
1872
  }
@@ -1547,46 +1893,81 @@
1547
1893
  *
1548
1894
  * @param root the subtree root to walk for attached shadow roots
1549
1895
  */
1550
- const _sanitizeAttachedShadowRoots2 = function _sanitizeAttachedShadowRoots(root) {
1551
- const nodeType = getNodeType ? getNodeType(root) : root.nodeType;
1552
- if (nodeType === NODE_TYPE.element) {
1553
- const sr = getShadowRoot ? getShadowRoot(root) : root.shadowRoot;
1554
- // Realm-safe check (GHSA-hpcv-96wg-7vj8): use nodeType-based
1555
- // detection rather than `instanceof DocumentFragment`, which is
1556
- // realm-bound and silently skipped shadow roots whose host element
1557
- // belonged to a foreign realm (e.g. iframe.contentDocument
1558
- // attachShadow). A foreign-realm ShadowRoot extends the foreign
1559
- // realm's DocumentFragment, not ours, so the old instanceof check
1560
- // returned false and the shadow subtree was never walked.
1561
- if (_isDocumentFragment(sr)) {
1562
- // Recurse first so that nested shadow roots are reached even if
1563
- // _sanitizeShadowDOM removes hosts at this level.
1564
- _sanitizeAttachedShadowRoots2(sr);
1565
- _sanitizeShadowDOM2(sr);
1566
- }
1567
- }
1568
- // Snapshot children before recursing. Sanitization of one subtree
1569
- // (e.g. via an uponSanitizeShadowNode hook) may detach siblings,
1570
- // and naive nextSibling traversal would silently skip the rest of
1571
- // the list once a node is detached.
1572
- const childNodes = getChildNodes ? getChildNodes(root) : root.childNodes;
1573
- if (!childNodes) {
1574
- return;
1575
- }
1576
- const snapshot = [];
1577
- arrayForEach(childNodes, child => {
1578
- arrayPush(snapshot, child);
1579
- });
1580
- for (const child of snapshot) {
1581
- _sanitizeAttachedShadowRoots2(child);
1582
- }
1583
- /* When the root is a <template>, also descend into root.content */
1584
- if (nodeType === NODE_TYPE.element) {
1585
- const rootName = getNodeName ? getNodeName(root) : null;
1586
- if (typeof rootName === 'string' && transformCaseFunc(rootName) === 'template') {
1587
- const content = root.content;
1588
- if (_isDocumentFragment(content)) {
1589
- _sanitizeAttachedShadowRoots2(content);
1896
+ const _sanitizeAttachedShadowRoots = function _sanitizeAttachedShadowRoots(root) {
1897
+ /* Iterative (explicit stack) rather than per-child recursion. DOM APIs
1898
+ impose no depth cap, so an attacker-shaped tree (JSON/CRDT/editor data
1899
+ built straight into the DOM — the IN_PLACE surface) deeper than the JS
1900
+ call-stack budget would otherwise overflow native recursion here and
1901
+ throw at the IN_PLACE entry pre-pass, before a single node is
1902
+ sanitized, leaving the caller's live tree untouched (fail-open). See
1903
+ campaign-3 F4. A heap stack keeps depth off the call stack.
1904
+ Each work item is either a node to descend into, or a deferred
1905
+ `_sanitizeShadowDOM` for an already-walked shadow root. The deferred
1906
+ form preserves the original post-order discipline: a shadow root's
1907
+ nested shadow roots are discovered before the outer shadow is
1908
+ sanitized (which may remove hosts). Pushes are in reverse of the
1909
+ desired processing order (LIFO): template content, then children, then
1910
+ the shadow-sanitize, then the shadow walk — so the order matches the
1911
+ previous recursion exactly. */
1912
+ const stack = [{
1913
+ node: root,
1914
+ shadow: null
1915
+ }];
1916
+ while (stack.length > 0) {
1917
+ const item = stack.pop();
1918
+ /* Deferred shadow-DOM sanitisation: runs after its subtree was walked. */
1919
+ if (item.shadow) {
1920
+ _sanitizeShadowDOM2(item.shadow);
1921
+ continue;
1922
+ }
1923
+ const node = item.node;
1924
+ const nodeType = getNodeType ? getNodeType(node) : node.nodeType;
1925
+ const isElement = nodeType === NODE_TYPE.element;
1926
+ /* (pushed last processed first) Children, snapshotted in reverse so
1927
+ the first child is processed first. Snapshotting matters because a
1928
+ hook may detach siblings mid-walk. */
1929
+ const childNodes = getChildNodes(node);
1930
+ if (childNodes) {
1931
+ for (let i = childNodes.length - 1; i >= 0; --i) {
1932
+ stack.push({
1933
+ node: childNodes[i],
1934
+ shadow: null
1935
+ });
1936
+ }
1937
+ }
1938
+ /* (pushed before children → processed after them, matching the old
1939
+ "template content last" order) When the node is a <template>,
1940
+ descend into its content. */
1941
+ if (isElement) {
1942
+ const rootName = getNodeName ? getNodeName(node) : null;
1943
+ if (typeof rootName === 'string' && transformCaseFunc(rootName) === 'template') {
1944
+ const content = node.content;
1945
+ if (_isDocumentFragment(content)) {
1946
+ stack.push({
1947
+ node: content,
1948
+ shadow: null
1949
+ });
1950
+ }
1951
+ }
1952
+ }
1953
+ /* Shadow root (processed first): walk its subtree, then sanitise it.
1954
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
1955
+ rather than `instanceof DocumentFragment`, which is realm-bound and
1956
+ silently skipped foreign-realm shadow roots (e.g.
1957
+ iframe.contentDocument attachShadow). */
1958
+ if (isElement) {
1959
+ const sr = getShadowRoot(node);
1960
+ if (_isDocumentFragment(sr)) {
1961
+ /* Push the deferred sanitise first so it pops after the shadow
1962
+ walk we push next, i.e. nested shadow roots are discovered
1963
+ before this one is sanitised. */
1964
+ stack.push({
1965
+ node: null,
1966
+ shadow: sr
1967
+ }, {
1968
+ node: sr,
1969
+ shadow: null
1970
+ });
1590
1971
  }
1591
1972
  }
1592
1973
  }
@@ -1617,16 +1998,41 @@
1617
1998
  return dirty;
1618
1999
  }
1619
2000
  /* Assign config vars */
1620
- if (!SET_CONFIG) {
2001
+ if (SET_CONFIG) {
2002
+ /* Persistent setConfig() path: _parseConfig is skipped, so the sets are
2003
+ * not re-derived per call. Restore them from the pristine bindings
2004
+ * captured at setConfig() time so a previous call's hook clone (mutated
2005
+ * below) does not carry over. */
2006
+ ALLOWED_TAGS = SET_CONFIG_ALLOWED_TAGS;
2007
+ ALLOWED_ATTR = SET_CONFIG_ALLOWED_ATTR;
2008
+ } else {
1621
2009
  _parseConfig(cfg);
1622
2010
  }
2011
+ /* Clone the hook-mutable allowlists before the walk whenever an
2012
+ * uponSanitize* hook is registered. The hook event exposes ALLOWED_TAGS
2013
+ * and ALLOWED_ATTR by reference (as allowedTags / allowedAttributes), so
2014
+ * a hook that widens them would otherwise mutate the shared set
2015
+ * permanently: across later calls and across every element. Cloning per
2016
+ * walk keeps documented in-call widening working while scoping it to the
2017
+ * call. A single guard for both config paths - the per-call path rebinds
2018
+ * the sets in _parseConfig each call, the persistent path restores them
2019
+ * from the captured bindings just above - so the two cannot diverge. */
2020
+ if (hooks.uponSanitizeElement.length > 0 || hooks.uponSanitizeAttribute.length > 0) {
2021
+ ALLOWED_TAGS = clone(ALLOWED_TAGS);
2022
+ }
2023
+ if (hooks.uponSanitizeAttribute.length > 0) {
2024
+ ALLOWED_ATTR = clone(ALLOWED_ATTR);
2025
+ }
1623
2026
  /* Clean up removed elements */
1624
2027
  DOMPurify.removed = [];
1625
- /* Check if dirty is correctly typed for IN_PLACE */
1626
- if (typeof dirty === 'string') {
1627
- IN_PLACE = false;
1628
- }
1629
- if (IN_PLACE) {
2028
+ /* Resolve IN_PLACE for this call without mutating persistent config.
2029
+ Writing the IN_PLACE closure variable here leaks under setConfig(),
2030
+ where _parseConfig is skipped on later calls: a single string call would
2031
+ disable in-place mode for every subsequent node call, returning a
2032
+ sanitized copy while leaving the caller's node — which in-place callers
2033
+ keep using and whose return value they ignore — unsanitized. REPORT-2. */
2034
+ const inPlace = IN_PLACE && typeof dirty !== 'string' && _isNode(dirty);
2035
+ if (inPlace) {
1630
2036
  /* Do some early pre-sanitization to avoid unsafe root nodes.
1631
2037
  Read nodeName through the cached prototype getter — a clobbering
1632
2038
  child named "nodeName" on the form root would otherwise shadow
@@ -1653,8 +2059,16 @@
1653
2059
  throw typeErrorCreate('root node is clobbered and cannot be sanitized in-place');
1654
2060
  }
1655
2061
  /* Sanitize attached shadow roots before the main iterator runs.
1656
- The iterator does not descend into shadow trees. */
1657
- _sanitizeAttachedShadowRoots2(dirty);
2062
+ The iterator does not descend into shadow trees. Same fail-closed
2063
+ barrier as the main walk (campaign-3 F2): a custom-element reaction
2064
+ inside a shadow root could abort this pre-pass before the walk runs,
2065
+ which would otherwise leave the entire live tree unsanitized. */
2066
+ try {
2067
+ _sanitizeAttachedShadowRoots(dirty);
2068
+ } catch (error) {
2069
+ _neutralizeRoot(dirty);
2070
+ throw error;
2071
+ }
1658
2072
  } else if (_isNode(dirty)) {
1659
2073
  /* If dirty is a DOM element, append to an empty document to avoid
1660
2074
  elements being stripped by the parser */
@@ -1674,7 +2088,7 @@
1674
2088
  descend into shadow trees. The walk routes every read through a
1675
2089
  cached prototype getter so clobbering descendants on a form root
1676
2090
  cannot hide a shadow host from this pass. */
1677
- _sanitizeAttachedShadowRoots2(importedNode);
2091
+ _sanitizeAttachedShadowRoots(importedNode);
1678
2092
  } else {
1679
2093
  /* Exit directly if we have nothing to do */
1680
2094
  if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
@@ -1694,23 +2108,50 @@
1694
2108
  _forceRemove(body.firstChild);
1695
2109
  }
1696
2110
  /* Get node iterator */
1697
- const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);
1698
- /* Now start iterating over the created document */
1699
- while (currentNode = nodeIterator.nextNode()) {
1700
- /* Sanitize tags and elements */
1701
- _sanitizeElements(currentNode);
1702
- /* Check attributes next */
1703
- _sanitizeAttributes(currentNode);
1704
- /* Shadow DOM detected, sanitize it.
1705
- Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
1706
- instead of instanceof, so foreign-realm <template>.content is
1707
- walked correctly. */
1708
- if (_isDocumentFragment(currentNode.content)) {
1709
- _sanitizeShadowDOM2(currentNode.content);
2111
+ const nodeIterator = _createNodeIterator(inPlace ? dirty : body);
2112
+ /* Now start iterating over the created document.
2113
+ The walk runs inside an exception barrier (campaign-3 F2): a re-entrant
2114
+ engine/custom-element mutation can detach a node mid-walk so
2115
+ `_forceRemove`'s parentless guard throws, aborting the loop. Without the
2116
+ barrier the caller's in-place tree would be left half-sanitized with the
2117
+ unvisited tail still armed. On any throw we fail closed — strip the
2118
+ in-place root bare then rethrow so the existing throw contract is
2119
+ preserved. (String/DOM-copy paths never return the partial body, so the
2120
+ propagating throw is already fail-closed there.) */
2121
+ try {
2122
+ while (currentNode = nodeIterator.nextNode()) {
2123
+ /* Sanitize tags and elements */
2124
+ _sanitizeElements(currentNode);
2125
+ /* Check attributes next */
2126
+ _sanitizeAttributes(currentNode);
2127
+ /* Shadow DOM detected, sanitize it.
2128
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
2129
+ instead of instanceof, so foreign-realm <template>.content is
2130
+ walked correctly. */
2131
+ if (_isDocumentFragment(currentNode.content)) {
2132
+ _sanitizeShadowDOM2(currentNode.content);
2133
+ }
2134
+ }
2135
+ } catch (error) {
2136
+ if (inPlace) {
2137
+ _neutralizeRoot(dirty);
1710
2138
  }
2139
+ throw error;
1711
2140
  }
1712
2141
  /* If we sanitized `dirty` in-place, return it. */
1713
- if (IN_PLACE) {
2142
+ if (inPlace) {
2143
+ /* Fail-closed completion of the audit-5 F1 fix: every node removed from
2144
+ the caller's live tree is detached but may still hold a queued
2145
+ resource-event handler that fires in page scope after we return. The
2146
+ move-hoist covers only disallowed-tag KEEP_CONTENT removals; strip the
2147
+ non-allow-listed attributes off every other removed subtree (clobber,
2148
+ mXSS, namespace, comments, KEEP_CONTENT:false, …) so those handlers are
2149
+ cancelled before any event can fire. Runs synchronously, pre-return. */
2150
+ arrayForEach(DOMPurify.removed, entry => {
2151
+ if (entry.element) {
2152
+ _neutralizeSubtree(entry.element);
2153
+ }
2154
+ });
1714
2155
  if (SAFE_FOR_TEMPLATES) {
1715
2156
  _scrubTemplateExpressions2(dirty);
1716
2157
  }
@@ -1749,9 +2190,7 @@
1749
2190
  }
1750
2191
  /* Sanitize final string template-safe */
1751
2192
  if (SAFE_FOR_TEMPLATES) {
1752
- arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => {
1753
- serializedHTML = stringReplace(serializedHTML, expr, ' ');
1754
- });
2193
+ serializedHTML = _stripTemplateExpressions(serializedHTML);
1755
2194
  }
1756
2195
  return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(serializedHTML) : serializedHTML;
1757
2196
  };
@@ -1759,10 +2198,20 @@
1759
2198
  let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1760
2199
  _parseConfig(cfg);
1761
2200
  SET_CONFIG = true;
2201
+ SET_CONFIG_ALLOWED_TAGS = ALLOWED_TAGS;
2202
+ SET_CONFIG_ALLOWED_ATTR = ALLOWED_ATTR;
1762
2203
  };
1763
2204
  DOMPurify.clearConfig = function () {
1764
2205
  CONFIG = null;
1765
2206
  SET_CONFIG = false;
2207
+ SET_CONFIG_ALLOWED_TAGS = null;
2208
+ SET_CONFIG_ALLOWED_ATTR = null;
2209
+ // Drop any caller-supplied Trusted Types policy so it cannot poison later
2210
+ // `RETURN_TRUSTED_TYPE` output. The internal default policy (cached, and
2211
+ // never recreated — Trusted Types throws on duplicate names) is restored by
2212
+ // the next `_parseConfig`. See GHSA-vxr8-fq34-vvx9.
2213
+ trustedTypesPolicy = defaultTrustedTypesPolicy;
2214
+ emptyHTML = '';
1766
2215
  };
1767
2216
  DOMPurify.isValidAttribute = function (tag, attr, value) {
1768
2217
  /* Initialize shared config vars if necessary. */
@@ -1777,9 +2226,19 @@
1777
2226
  if (typeof hookFunction !== 'function') {
1778
2227
  return;
1779
2228
  }
2229
+ /* Reject unknown entry points. Without this, a non-hook key (e.g.
2230
+ * '__proto__') indexes off the prototype chain rather than a real
2231
+ * hook array, and arrayPush then writes to Object.prototype. Guard
2232
+ * with an own-property check against the known hook names. */
2233
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
2234
+ return;
2235
+ }
1780
2236
  arrayPush(hooks[entryPoint], hookFunction);
1781
2237
  };
1782
2238
  DOMPurify.removeHook = function (entryPoint, hookFunction) {
2239
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
2240
+ return undefined;
2241
+ }
1783
2242
  if (hookFunction !== undefined) {
1784
2243
  const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);
1785
2244
  return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];
@@ -1787,6 +2246,9 @@
1787
2246
  return arrayPop(hooks[entryPoint]);
1788
2247
  };
1789
2248
  DOMPurify.removeHooks = function (entryPoint) {
2249
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
2250
+ return;
2251
+ }
1790
2252
  hooks[entryPoint] = [];
1791
2253
  };
1792
2254
  DOMPurify.removeAllHooks = function () {