Skip to content

DOMPurify: IN_PLACE: node-removing afterSanitize hook leaves detached subtree event handlers armed, causing DOM XSS

Low severity GitHub Reviewed Published Sep 23, 2026 in cure53/DOMPurify • Updated Sep 30, 2026

Package

npm dompurify (npm)

Affected versions

>= 3.4.13, <= 3.4.15

Patched versions

3.4.16

Description

Summary

In IN_PLACE mode DOMPurify sanitizes the caller's live DOM subtree directly. To close a known hazard (GHSA-55q2-fjhq-7xh7), the library neutralizes any node a hook detaches during sanitization by stripping its subtree's non-allow-listed attributes, but this neutralization is wired only into the beforeSanitizeElements and uponSanitizeElement hook sites. An afterSanitizeElements or afterSanitizeAttributes hook that removes a non-root element (a documented, supported pattern) detaches that element's subtree with no neutralization, so descendant on* handlers remain armed on the caller's live tree after sanitize() returns, yielding DOM XSS. No special privilege is required beyond supplying markup to an application that uses IN_PLACE together with a node-removing afterSanitize hook.

Root Cause

IN_PLACE sanitization mutates the caller's live document, so any element a hook detaches from that tree must have its subtree neutralized before sanitize() returns; otherwise a queued resource-event handler (for example an <img onerror> that began loading when the caller built the tree) fires in page scope even though the handler never reached the sanitized output. The guard helper _handleHookDetachedNode (which calls _neutralizeSubtree in IN_PLACE) is invoked only after beforeSanitizeElements and after uponSanitizeElement. It is never invoked from the afterSanitize return paths, and _sanitizeAttributes never calls it at all. The post-walk IN_PLACE neutralization pass iterates only DOMPurify.removed, and hook-detached nodes are intentionally not recorded there, so that pass cannot reach them either.

src/purify.ts
  _sanitizeElements: _handleHookDetachedNode present at lines 2142 and 2175
    (before/upon), absent after afterSanitizeElements at lines 2208 and 2249.
  _sanitizeAttributes: afterSanitizeAttributes fires at line 2670 with no
    detach re-check; the function never calls _handleHookDetachedNode.
  Post-walk IN_PLACE pass (lines 3081-3090) iterates DOMPurify.removed only,
    which by design (comment at lines 2096-2099) excludes hook-detached nodes.

Impact

An attacker who supplies markup processed by a victim application that runs DOMPurify.sanitize(node, { IN_PLACE: true }) and registers a node-removing afterSanitizeElements or afterSanitizeAttributes hook can retain arbitrary on* event handlers on descendants of a removed non-root element. Because IN_PLACE operates on the caller's live document, a queued resource-event handler on such a descendant fires in the page origin after the synchronous sanitize() call returns, giving script execution in the victim's session (DOM XSS). This defeats DOMPurify's IN_PLACE contract to neutralize handlers on subtrees removed from the live tree. The capability is script execution in the victim origin; exact confidentiality and integrity effects depend on the hosting application's session.

Proof of Concept

Dependencies: Node.js and jsdom. The harness builds a live tree, registers a
removal hook, runs IN_PLACE sanitize(), then inspects whether the attacker
onerror handler survives on the detached descendant. jsdom does not perform
real image loads, so the retained handler (rather than an actual fired event)
is the observed hazard; the retained on* attribute on a live detached node
after a synchronous sanitize() return is the neutralization failure.

Reproduction steps:

  1. Build a live subtree #root > section#wrap > img[onerror] where #root is the walk root and section#wrap is a non-root wrapper.
  2. Register an afterSanitizeElements (or afterSanitizeAttributes) hook that calls node.remove() on the wrapper.
  3. Call DOMPurify.sanitize(root, { IN_PLACE: true }).
  4. Observe that the descendant <img> retains its onerror handler, whereas the same removal performed in a beforeSanitizeElements/uponSanitizeElement hook strips it.
const { JSDOM } = require('jsdom');
const createDOMPurify = require('dompurify');
const { window } = new JSDOM('<!DOCTYPE html><body></body>');
const DOMPurify = createDOMPurify(window);

const root = window.document.createElement('div');
root.id = 'root';
root.innerHTML = '<section id="wrap"><img src="x" onerror="ATTACKER()"></section>';
window.document.body.appendChild(root);

DOMPurify.addHook('afterSanitizeElements', (node) => {
  if (node.id === 'wrap') node.remove();
});
DOMPurify.sanitize(root, { IN_PLACE: true });

// The detached <img> still carries its onerror handler:
console.log(root.querySelector('#wrap') === null,               // true (removed from live tree)
            !!window.document.querySelector('img[onerror]') ||  // handler survives on the detached node
            root.innerHTML);
PASS: beforeSanitizeElements detach neutralizes descendant onerror (control)
PASS: uponSanitizeElement detach neutralizes descendant onerror (control)
PASS: without a removal hook the descendant onerror is stripped normally
PASS: afterSanitizeElements detach LEAVES descendant onerror armed (GAP)
PASS: afterSanitizeAttributes detach LEAVES descendant onerror armed (GAP)
PASS: kept custom element removed in afterSanitizeElements leaves descendant onerror armed (GAP)

Attack Chain

  1. Exposure: The victim application calls DOMPurify.sanitize(liveNode, { IN_PLACE: true }) on attacker-influenced markup and has registered a node-removing afterSanitizeElements or afterSanitizeAttributes hook per an application policy (src/purify.ts:3026 walk, 2136 element pass, 2522 attribute pass).
  2. Control: The attacker controls the markup, including a non-root wrapper element and, inside it, a descendant carrying an on* resource-event handler such as <img src=x onerror=...>.
  3. Path: The pre-order walk visits the wrapper before its descendants. During the wrapper's element or attribute pass the application hook detaches the wrapper from the live tree.
  4. Guard: The detach-neutralization guard _handleHookDetachedNode runs only after beforeSanitizeElements (2142) and uponSanitizeElement (2175); it is absent after afterSanitizeElements (2208, 2249) and is never called by _sanitizeAttributes (afterSanitizeAttributes at 2670). The NodeIterator advances past the detached subtree, so the descendants are never revisited, and the post-walk pass iterates only DOMPurify.removed, which excludes hook-detached nodes.
  5. Primitive: The descendant retains its on* handler on the caller's live document after sanitize() returns.
  6. Result: The queued resource event fires the attacker handler in the victim page origin, achieving DOM XSS despite IN_PLACE sanitization.

Bypass Evidence

The relevant prior fix is GHSA-55q2-fjhq-7xh7 ("IN_PLACE hook removal leaves a detached subtree executable, causing XSS"), whose change (#1557) added _neutralizeSubtree at the beforeSanitizeElements and uponSanitizeElement detach sites. Inspection of that change shows it touches no afterSanitize site: the diff adds the neutralization only at the before/upon locations, later refactored into _handleHookDetachedNode at src/purify.ts:2142 and 2175. A subsequent hardening change (#1616) added a rootWasRemoved throw and a neutralization sweep over DOMPurify.removed, but that sweep still iterates only DOMPurify.removed, which by design excludes hook-detached non-root nodes, so it does not close this gap. The afterSanitizeElements-on-kept-custom-element site at 2208 was itself introduced by the fix for GHSA-c2j3-45gr-mqc4 (#1527), adding another uncovered hook site.

Disproof attempts, all failed: (a) that a later release closed the afterSanitize gap, refuted by inspecting the published 3.4.13, 3.4.14, and 3.4.15 artifacts; (b) that detached descendants are revisited or re-sanitized, refuted at runtime (the onerror is retained only at the afterSanitize sites and stripped at the before/upon sites and with no removal hook); (c) that the post-walk pass catches hook-detached nodes, refuted by the design that excludes them from DOMPurify.removed; (d) that the precondition is contrived, refuted by parity with the accepted GHSA-55q2 threat model and the library's own supported pattern of removing a node inside afterSanitizeElements. The only edge not directly executed is the browser resource-event dispatch (jsdom performs no real image load); it is established by the proven retention of the live handler after a synchronous return, the library's own comments describing exactly this hazard, and parity with the accepted GHSA-55q2 mechanism.

Affected Versions

  • Ecosystem: npm
  • Package: dompurify
  • Confirmed affected range: >= 3.4.13, <= 3.4.15
  • Latest release checked: 3.4.15 (npm registry)
  • Fix status: fixed in 3.4.16

The before/upon detach neutralization introduced for GHSA-55q2-fjhq-7xh7 first shipped in 3.4.13; the residual afterSanitize gap was verified by reproducing it against the published npm artifacts for 3.4.13, 3.4.14, and 3.4.15. The 3.4.12 artifact predates that neutralization and behaves differently at the before/upon sites, so it is outside this specific incomplete-fix range. No release through 3.4.15 neutralizes detached subtrees at the afterSanitize sites, so no fixed version is established.

Suggested Fix

Enforce the same IN_PLACE detach-neutralization invariant at every hook site that can detach a node, not only the before/upon sites. Concretely, apply a _handleHookDetachedNode(currentNode, root) re-check after afterSanitizeElements at both src/purify.ts:2208 and 2249 (returning as removed when the node was detached), and add an equivalent IN_PLACE detach check plus _neutralizeSubtree after afterSanitizeAttributes at 2670. As an interim mitigation without a code change, applications using IN_PLACE can avoid removing nodes inside afterSanitizeElements/afterSanitizeAttributes hooks and instead perform such removals in beforeSanitizeElements/uponSanitizeElement, or avoid IN_PLACE for attacker-influenced content.

Reported by zx (GitHub: @manus-pi).

References

@cure53 cure53 published to cure53/DOMPurify Sep 23, 2026
Published to the GitHub Advisory Database Sep 30, 2026
Reviewed Sep 30, 2026
Last updated Sep 30, 2026

Severity

Low

CVSS overall score

This score calculates overall vulnerability severity from 0 to 10 and is based on the Common Vulnerability Scoring System (CVSS).
/ 10

CVSS v4 base metrics

Exploitability Metrics
Attack Vector Network
Attack Complexity Low
Attack Requirements Present
Privileges Required None
User interaction Passive
Vulnerable System Impact Metrics
Confidentiality Low
Integrity Low
Availability None
Subsequent System Impact Metrics
Confidentiality None
Integrity None
Availability None

CVSS v4 base metrics

Exploitability Metrics
Attack Vector: This metric reflects the context by which vulnerability exploitation is possible. This metric value (and consequently the resulting severity) will be larger the more remote (logically, and physically) an attacker can be in order to exploit the vulnerable system. The assumption is that the number of potential attackers for a vulnerability that could be exploited from across a network is larger than the number of potential attackers that could exploit a vulnerability requiring physical access to a device, and therefore warrants a greater severity.
Attack Complexity: This metric captures measurable actions that must be taken by the attacker to actively evade or circumvent existing built-in security-enhancing conditions in order to obtain a working exploit. These are conditions whose primary purpose is to increase security and/or increase exploit engineering complexity. A vulnerability exploitable without a target-specific variable has a lower complexity than a vulnerability that would require non-trivial customization. This metric is meant to capture security mechanisms utilized by the vulnerable system.
Attack Requirements: This metric captures the prerequisite deployment and execution conditions or variables of the vulnerable system that enable the attack. These differ from security-enhancing techniques/technologies (ref Attack Complexity) as the primary purpose of these conditions is not to explicitly mitigate attacks, but rather, emerge naturally as a consequence of the deployment and execution of the vulnerable system.
Privileges Required: This metric describes the level of privileges an attacker must possess prior to successfully exploiting the vulnerability. The method by which the attacker obtains privileged credentials prior to the attack (e.g., free trial accounts), is outside the scope of this metric. Generally, self-service provisioned accounts do not constitute a privilege requirement if the attacker can grant themselves privileges as part of the attack.
User interaction: This metric captures the requirement for a human user, other than the attacker, to participate in the successful compromise of the vulnerable system. This metric determines whether the vulnerability can be exploited solely at the will of the attacker, or whether a separate user (or user-initiated process) must participate in some manner.
Vulnerable System Impact Metrics
Confidentiality: This metric measures the impact to the confidentiality of the information managed by the VULNERABLE SYSTEM due to a successfully exploited vulnerability. Confidentiality refers to limiting information access and disclosure to only authorized users, as well as preventing access by, or disclosure to, unauthorized ones.
Integrity: This metric measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of information. Integrity of the VULNERABLE SYSTEM is impacted when an attacker makes unauthorized modification of system data. Integrity is also impacted when a system user can repudiate critical actions taken in the context of the system (e.g. due to insufficient logging).
Availability: This metric measures the impact to the availability of the VULNERABLE SYSTEM resulting from a successfully exploited vulnerability. While the Confidentiality and Integrity impact metrics apply to the loss of confidentiality or integrity of data (e.g., information, files) used by the system, this metric refers to the loss of availability of the impacted system itself, such as a networked service (e.g., web, database, email). Since availability refers to the accessibility of information resources, attacks that consume network bandwidth, processor cycles, or disk space all impact the availability of a system.
Subsequent System Impact Metrics
Confidentiality: This metric measures the impact to the confidentiality of the information managed by the SUBSEQUENT SYSTEM due to a successfully exploited vulnerability. Confidentiality refers to limiting information access and disclosure to only authorized users, as well as preventing access by, or disclosure to, unauthorized ones.
Integrity: This metric measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of information. Integrity of the SUBSEQUENT SYSTEM is impacted when an attacker makes unauthorized modification of system data. Integrity is also impacted when a system user can repudiate critical actions taken in the context of the system (e.g. due to insufficient logging).
Availability: This metric measures the impact to the availability of the SUBSEQUENT SYSTEM resulting from a successfully exploited vulnerability. While the Confidentiality and Integrity impact metrics apply to the loss of confidentiality or integrity of data (e.g., information, files) used by the system, this metric refers to the loss of availability of the impacted system itself, such as a networked service (e.g., web, database, email). Since availability refers to the accessibility of information resources, attacks that consume network bandwidth, processor cycles, or disk space all impact the availability of a system.
CVSS:4.0/AV:N/AC:L/AT:P/PR:N/UI:P/VC:L/VI:L/VA:N/SC:N/SI:N/SA:N

EPSS score

Weaknesses

Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')

The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. Learn more on MITRE.

CVE ID

No known CVE

GHSA ID

GHSA-p98j-92pf-mc4p

Source code

Credits

Loading Checking history
See something to contribute? Suggest improvements for this vulnerability.