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