dompurify 3.4.11 → 3.4.12

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.
package/dist/purify.js CHANGED
@@ -1,4 +1,4 @@
1
- /*! @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 */
1
+ /*! @license DOMPurify 3.4.12 | (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.12/LICENSE */
2
2
 
3
3
  (function (global, factory) {
4
4
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
@@ -317,7 +317,7 @@
317
317
  const text = freeze(['#text']);
318
318
 
319
319
  const html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'command', 'commandfor', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'exportparts', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inert', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'part', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns']);
320
- const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'mask-type', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);
320
+ const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dominant-baseline', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'mask-type', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-orientation', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);
321
321
  const mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnalign', 'columnlines', 'columnspacing', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lquote', 'lspace', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);
322
322
  const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
323
323
 
@@ -430,7 +430,7 @@
430
430
  function createDOMPurify() {
431
431
  let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
432
432
  const DOMPurify = root => createDOMPurify(root);
433
- DOMPurify.version = '3.4.11';
433
+ DOMPurify.version = '3.4.12';
434
434
  DOMPurify.removed = [];
435
435
  if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {
436
436
  // Not running in a browser, provide a factory function
@@ -1112,6 +1112,13 @@
1112
1112
  * @param root the in-place root to empty
1113
1113
  */
1114
1114
  const _neutralizeRoot = function _neutralizeRoot(root) {
1115
+ /* Strip every disallowed attribute (on* handlers included) off the whole
1116
+ subtree BEFORE detaching anything. Detaching first would hand back
1117
+ handler-bearing originals (e.g. an already-loading `<img onerror>`)
1118
+ whose queued resource event still fires in page scope after we throw.
1119
+ Clobber-safe reads; a doomed clobbered node's own attributes are
1120
+ irrelevant while its non-clobbered descendants are reached and scrubbed. */
1121
+ _neutralizeSubtree(root);
1115
1122
  const childNodes = getChildNodes(root);
1116
1123
  if (childNodes) {
1117
1124
  const snapshot = [];
@@ -1239,6 +1246,82 @@
1239
1246
  }
1240
1247
  }
1241
1248
  };
1249
+ /**
1250
+ * _neutralizePatchLinkage
1251
+ *
1252
+ * IN_PLACE entry pre-pass (declarative-partial-updates / streaming
1253
+ * hardening, https://github.com/WICG/declarative-partial-updates).
1254
+ *
1255
+ * The main walk strips patch linkage (`for`/`patchsrc`) and removes range
1256
+ * markers (PIs / markup comments) node-by-node, in document order, AS it
1257
+ * reaches each node. On a live in-place root that leaves a window: from the
1258
+ * moment the root is connected until the walk arrives at a given node, that
1259
+ * node's linkage is live. A patch applied on connection/stream can fire as
1260
+ * a microtask during the walk and inject or teleport an unsanitized DOM
1261
+ * range into a region the iterator has already passed and will not revisit,
1262
+ * so the post-return "tree is sanitized" contract is violated. Sweep the
1263
+ * whole tree once up front and sever every linkage before the walk begins,
1264
+ * closing that window.
1265
+ *
1266
+ * This CANNOT undo a patch that already fired before sanitize ran — that is
1267
+ * the irreducible "do not IN_PLACE a live-connected attacker tree" caveat —
1268
+ * but it closes everything from sanitize-start onward. Gated on SAFE_FOR_XML
1269
+ * to group with the rest of the declarative-partial-updates handling and
1270
+ * stay overridable, consistent with the codebase.
1271
+ *
1272
+ * Clobber-safe traversal (cached childNodes getter); per-node try/catch so a
1273
+ * clobbered root cannot defeat the sweep of its non-clobbered descendants.
1274
+ *
1275
+ * NOTE (pending real-Chrome confirmation, see test/declarative-patch-probe
1276
+ * .html Q1): this mirrors the existing policy of keeping `for` on
1277
+ * <label>/<output>. If the shipping feature can drive a patch through a
1278
+ * surviving `for`-on-label/output + `id` pair, this pre-pass and the
1279
+ * attribute check at _isBasicCustomElement's caller must additionally drop
1280
+ * that pair on the IN_PLACE path. Left as-is until the taxonomy is verified.
1281
+ *
1282
+ * @param root the in-place root to sweep
1283
+ */
1284
+ const _neutralizePatchLinkage = function _neutralizePatchLinkage(root) {
1285
+ if (!SAFE_FOR_XML) {
1286
+ return;
1287
+ }
1288
+ const stack = [root];
1289
+ while (stack.length > 0) {
1290
+ const node = stack.pop();
1291
+ const nodeType = getNodeType ? getNodeType(node) : node.nodeType;
1292
+ /* Remove range markers (the target side of a patch linkage): every
1293
+ processing instruction, and any markup-bearing comment. */
1294
+ if (nodeType === NODE_TYPE.processingInstruction || nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, node.data)) {
1295
+ try {
1296
+ remove(node);
1297
+ } catch (_) {
1298
+ /* Best-effort */
1299
+ }
1300
+ continue;
1301
+ }
1302
+ /* Strip patch-source attributes (the source side) off elements. */
1303
+ if (nodeType === NODE_TYPE.element) {
1304
+ const element = node;
1305
+ const lcTag = transformCaseFunc(getNodeName ? getNodeName(node) : node.nodeName);
1306
+ try {
1307
+ if (element.hasAttribute && element.hasAttribute('patchsrc')) {
1308
+ element.removeAttribute('patchsrc');
1309
+ }
1310
+ if (element.hasAttribute && element.hasAttribute('for') && lcTag !== 'label' && lcTag !== 'output') {
1311
+ element.removeAttribute('for');
1312
+ }
1313
+ } catch (_) {
1314
+ /* Clobbered removeAttribute/hasAttribute on a doomed node — ignore */
1315
+ }
1316
+ }
1317
+ const childNodes = getChildNodes(node);
1318
+ if (childNodes) {
1319
+ for (let i = childNodes.length - 1; i >= 0; --i) {
1320
+ stack.push(childNodes[i]);
1321
+ }
1322
+ }
1323
+ }
1324
+ };
1242
1325
  /**
1243
1326
  * _initDocument
1244
1327
  *
@@ -1489,9 +1572,15 @@
1489
1572
  /**
1490
1573
  * Handle a node whose tag is forbidden or not allowlisted: keep
1491
1574
  * allowed custom elements (false return exits _sanitizeElements
1492
- * early - namespace/fallback checks and the afterSanitizeElements
1493
- * hook are intentionally skipped for kept custom elements), else
1494
- * hoist content per KEEP_CONTENT and remove.
1575
+ * early - the namespace and fallback-tag removal checks are
1576
+ * intentionally skipped for kept custom elements), else hoist
1577
+ * content per KEEP_CONTENT and remove.
1578
+ *
1579
+ * A kept custom element is the ONLY case in which this function
1580
+ * returns false, so the caller uses that return value to run the
1581
+ * afterSanitizeElements hook on the kept element and keep the
1582
+ * element-hook lifecycle consistent with normal allowlisted
1583
+ * elements (GHSA-c2j3-45gr-mqc4).
1495
1584
  *
1496
1585
  * @param currentNode the disallowed node
1497
1586
  * @param tagName the node's transformCaseFunc'd tag name
@@ -1557,9 +1646,15 @@
1557
1646
  * @param currentNode to check for permission to exist
1558
1647
  * @return true if node was killed, false if left alive
1559
1648
  */
1560
- const _sanitizeElements = function _sanitizeElements(currentNode) {
1649
+ // eslint-disable-next-line complexity
1650
+ const _sanitizeElements = function _sanitizeElements(currentNode, root) {
1561
1651
  /* Execute a hook if present */
1562
1652
  _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
1653
+ /* A hook may have detached the node — treat it as removed (see the
1654
+ detached-node comment after the uponSanitizeElement hook below). */
1655
+ if (currentNode !== root && getParentNode(currentNode) === null) {
1656
+ return true;
1657
+ }
1563
1658
  /* Check if element is clobbered or can clobber */
1564
1659
  if (_isClobbered(currentNode)) {
1565
1660
  _forceRemove(currentNode);
@@ -1572,6 +1667,24 @@
1572
1667
  tagName,
1573
1668
  allowedTags: ALLOWED_TAGS
1574
1669
  });
1670
+ /* A hook may have detached the node from the tree — a long-standing
1671
+ user pattern (issue #469; draw.io-style foreignObject filtering).
1672
+ Per the cached, unclobberable parentNode getter the node is
1673
+ genuinely out of the tree, so it can reach neither the serialized
1674
+ output nor an IN_PLACE live tree; treat it as removed and stop
1675
+ processing it. Without this guard, the unsafe-node / namespace
1676
+ checks below would call _forceRemove on a parentless node and hit
1677
+ the REPORT-3 fail-closed throw — which exists for nodes DOMPurify
1678
+ wants gone but *cannot* detach (clobbered / parentless roots), the
1679
+ opposite of a node that is already safely gone. The walk root is
1680
+ exempt: a detached IN_PLACE root is legitimate input and must still
1681
+ be fully sanitized, and a kill-decision on it must keep hitting the
1682
+ REPORT-3 throw. Nodes detached by hooks are the hook's
1683
+ responsibility: they are not recorded in DOMPurify.removed and are
1684
+ not neutralized by the post-walk IN_PLACE pass. */
1685
+ if (currentNode !== root && getParentNode(currentNode) === null) {
1686
+ return true;
1687
+ }
1575
1688
  /* Remove mXSS vectors, processing instructions and risky comments */
1576
1689
  if (_isUnsafeNode(currentNode, tagName)) {
1577
1690
  _forceRemove(currentNode);
@@ -1579,7 +1692,22 @@
1579
1692
  }
1580
1693
  /* Remove element if anything forbids its presence */
1581
1694
  if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) {
1582
- return _sanitizeDisallowedNode(currentNode, tagName);
1695
+ const removed = _sanitizeDisallowedNode(currentNode, tagName);
1696
+ /* A false return means the node is a custom element kept via
1697
+ CUSTOM_ELEMENT_HANDLING - the only keep path through
1698
+ _sanitizeDisallowedNode. Run afterSanitizeElements on it so the
1699
+ element-hook lifecycle matches normal allowlisted elements: a
1700
+ security policy applied in this hook (e.g. stripping an attribute
1701
+ from every surviving element) must not silently skip kept custom
1702
+ elements (GHSA-c2j3-45gr-mqc4). This mirrors the normal-element
1703
+ tail below - the hook runs, then the walker's subsequent
1704
+ _sanitizeAttributes pass sanitizes the element's attributes. The
1705
+ deliberately skipped namespace and fallback-tag removal checks stay
1706
+ skipped; they are removal decisions, not the hook contract. */
1707
+ if (removed === false) {
1708
+ _executeHooks(hooks.afterSanitizeElements, currentNode, null);
1709
+ }
1710
+ return removed;
1583
1711
  }
1584
1712
  /* Check whether element has a valid namespace.
1585
1713
  Realm-safe check (GHSA-hpcv-96wg-7vj8): use the cached Node.prototype
@@ -1626,6 +1754,33 @@
1626
1754
  if (FORBID_ATTR[lcName]) {
1627
1755
  return false;
1628
1756
  }
1757
+ /* Reject declarative-partial-updates patch-linkage attributes
1758
+ (https://github.com/WICG/declarative-partial-updates).
1759
+ Empirical note (Chrome 150, verified — see
1760
+ test/declarative-patch-probe-v3.html): expansion is NOT applied after
1761
+ sanitization. For the string path it fires during sanitize()'s own
1762
+ parse, so the walk sees and sanitizes the fully materialized expanded
1763
+ tree — teleports into MathML/SVG integration points included; a
1764
+ weaponized `<template for>`->`<img onerror>` comes back with the handler
1765
+ stripped. For the IN_PLACE path it fires on connection, before the walk.
1766
+ Either way DOMPurify is NOT blind to the patch.
1767
+ This removal is therefore defense-in-depth rather than the sole barrier:
1768
+ it prevents live linkage from surviving into the OUTPUT and re-expanding
1769
+ in the caller's context, and keeps behaviour deterministic if a future
1770
+ engine defers expansion. `for` is legitimate only on <label>/<output>;
1771
+ anywhere else (notably <template for>) it links the element to a patch
1772
+ target and teleports or removes an arbitrary DOM range by id/marker name.
1773
+ `patchsrc` fetches remote markup and is treated as a script-loading
1774
+ mechanism (CSP). Gated on SAFE_FOR_XML so the removal groups with the
1775
+ other structural-threat checks and stays overridable, consistent with
1776
+ the rest of the codebase. PI range markers are already removed by
1777
+ _isUnsafeNode. */
1778
+ if (SAFE_FOR_XML && lcName === 'patchsrc') {
1779
+ return false;
1780
+ }
1781
+ if (SAFE_FOR_XML && lcName === 'for' && lcTag !== 'label' && lcTag !== 'output') {
1782
+ return false;
1783
+ }
1629
1784
  /* Make sure attribute cannot clobber */
1630
1785
  if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
1631
1786
  return false;
@@ -1835,7 +1990,7 @@
1835
1990
  /* Execute a hook if present */
1836
1991
  _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);
1837
1992
  /* Sanitize tags and elements */
1838
- _sanitizeElements(shadowNode);
1993
+ _sanitizeElements(shadowNode, fragment);
1839
1994
  /* Check attributes next */
1840
1995
  _sanitizeAttributes(shadowNode);
1841
1996
  /* Deep shadow DOM detected.
@@ -2026,6 +2181,11 @@
2026
2181
  keep using and whose return value they ignore — unsanitized. REPORT-2. */
2027
2182
  const inPlace = IN_PLACE && typeof dirty !== 'string' && _isNode(dirty);
2028
2183
  if (inPlace) {
2184
+ /* Declarative-partial-updates / streaming pre-pass: sever every patch
2185
+ linkage across the live tree BEFORE the walk, so no patch can fire
2186
+ mid-walk and inject into an already-processed region. Runs first, so
2187
+ it also covers the forbidden/clobbered roots that throw below. */
2188
+ _neutralizePatchLinkage(dirty);
2029
2189
  /* Do some early pre-sanitization to avoid unsafe root nodes.
2030
2190
  Read nodeName through the cached prototype getter — a clobbering
2031
2191
  child named "nodeName" on the form root would otherwise shadow
@@ -2035,6 +2195,9 @@
2035
2195
  if (typeof nn === 'string') {
2036
2196
  const tagName = transformCaseFunc(nn);
2037
2197
  if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
2198
+ /* Fail closed on a live root: neutralize handlers/children before
2199
+ throwing, exactly as the mid-walk abort path does. */
2200
+ _neutralizeRoot(dirty);
2038
2201
  throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
2039
2202
  }
2040
2203
  }
@@ -2049,6 +2212,10 @@
2049
2212
  the application unsanitized. Refuse to sanitize such a root
2050
2213
  the same way we refuse a forbidden tag. GHSA-r47g-fvhr-h676. */
2051
2214
  if (_isClobbered(dirty)) {
2215
+ /* Fail closed on a live clobbered root before throwing.
2216
+ _neutralizeRoot's reads are clobber-safe (cached getters); the
2217
+ form's non-clobbered descendants, e.g. an armed <img>, are scrubbed. */
2218
+ _neutralizeRoot(dirty);
2052
2219
  throw typeErrorCreate('root node is clobbered and cannot be sanitized in-place');
2053
2220
  }
2054
2221
  /* Sanitize attached shadow roots before the main iterator runs.
@@ -2101,7 +2268,8 @@
2101
2268
  _forceRemove(body.firstChild);
2102
2269
  }
2103
2270
  /* Get node iterator */
2104
- const nodeIterator = _createNodeIterator(inPlace ? dirty : body);
2271
+ const walkRoot = inPlace ? dirty : body;
2272
+ const nodeIterator = _createNodeIterator(walkRoot);
2105
2273
  /* Now start iterating over the created document.
2106
2274
  The walk runs inside an exception barrier (campaign-3 F2): a re-entrant
2107
2275
  engine/custom-element mutation can detach a node mid-walk so
@@ -2114,7 +2282,7 @@
2114
2282
  try {
2115
2283
  while (currentNode = nodeIterator.nextNode()) {
2116
2284
  /* Sanitize tags and elements */
2117
- _sanitizeElements(currentNode);
2285
+ _sanitizeElements(currentNode, walkRoot);
2118
2286
  /* Check attributes next */
2119
2287
  _sanitizeAttributes(currentNode);
2120
2288
  /* Shadow DOM detected, sanitize it.
@@ -2128,6 +2296,14 @@
2128
2296
  } catch (error) {
2129
2297
  if (inPlace) {
2130
2298
  _neutralizeRoot(dirty);
2299
+ /* Nodes _forceRemove'd earlier in the aborted walk are already
2300
+ detached from the root, so _neutralizeRoot's subtree pass does not
2301
+ reach them. Defuse them too, mirroring the success-path loop below. */
2302
+ arrayForEach(DOMPurify.removed, entry => {
2303
+ if (entry.element) {
2304
+ _neutralizeSubtree(entry.element);
2305
+ }
2306
+ });
2131
2307
  }
2132
2308
  throw error;
2133
2309
  }