FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Safe Markdown Rendering for Token Streams

Parse streamed Markdown as untrusted input, disable raw HTML by default, and sanitize the final representation immediately before inserting it into the DOM.

Freshness: current•12 min read•AI User Experience and Human-AI Interaction
Full Technical Reference Document

Mental model

Treat every streamed model byte as untrusted data. Keep it as text until a Markdown parser constructs a representation, disable raw HTML unless the product has a clear need for it, then sanitize the rendered result with a maintained policy immediately before DOM insertion. Parsing, sanitizing, and rendering are separate steps; a network chunk boundary is never a security boundary.

Theory

A response stream may split one Markdown construct across many events. The first fragment of an image or link may be harmless text, while a later fragment completes syntax that changes how the browser interprets the whole message. The transport therefore cannot decide that one event is safe merely because its bytes look innocuous in isolation. Keep the accumulated source as text, parse it with a Markdown implementation whose raw HTML handling is disabled, and sanitize the parser output before it reaches an HTML sink.

Markdown parsing answers which syntax constructs exist; sanitization decides which resulting elements and attributes the application accepts. Neither stage replaces the other. A parser can intentionally produce anchors, code blocks, or raw HTML nodes according to its configuration. A sanitizer can remove script-capable elements and unsafe attributes, but it cannot repair a false trust decision made by the application or make a later mutation safe. If the product must support authored HTML, use a narrow allowlist and keep that policy next to the sink so every rendering path shares it.

The safest default for ordinary response prose is to render text through a framework's escaped text path. If Markdown formatting is required, parse the complete accumulated Markdown buffer, allow only the product's supported tags and attributes, and insert the sanitizer's DOM fragment without further string concatenation. Treat links as a separate policy: accept only schemes the product needs, provide safe link behavior, and do not assume that a valid-looking label proves the destination is safe.

Sanitization must be the last transformation before insertion. A common mistake is to sanitize a string, then append a wrapper, rewrite attributes, or pass the string through a highlighting plugin that can introduce new markup. Any post-sanitization transform can change the security properties of the output. Prefer operations on already-created text nodes. When a later component must modify HTML, return to the source representation and run the complete parse and sanitize pipeline again.

Trade-offs

Reparsing the entire accumulated message on each render is simple and keeps parser context across split tokens, but repeated full-prefix parsing uses more CPU than parsing one final document. Coalesce deltas to one render per animation frame and cap message size. A more advanced renderer can commit only complete Markdown blocks, but it must use parser state to identify those blocks; a hand-written regular expression that searches for a closing tag or fence will fail on escaped delimiters, nested syntax, and code examples.

Disabling raw HTML may change how imported documentation or user-authored content looks. That is usually a reasonable trade for chat output, which is generated or retrieved from sources that the renderer does not control. If HTML support is a product requirement, restrict it to a small documented subset, keep the sanitizer library current, test its policy against hostile inputs, and ensure every rendering path uses the same version and configuration.

Failure modes and misconceptions

  • Sanitizing each transport delta separately: A tag or URL can be split between deltas, so the sanitizer sees different input than the eventual parser. Accumulate source text and evaluate the current whole message.
  • Trusting Markdown because it is not HTML: Markdown can create HTML elements and links. Parser output still needs an explicit policy before reaching an HTML sink.
  • Allowing dangerous raw HTML for convenience: A raw event handler, SVG element, or unsafe URL can become active if the parser preserves it and the sink inserts it.
  • Sanitizing and then rewriting: A syntax highlighter, linkifier, or wrapper that edits the sanitized string can reintroduce markup. Make it operate on text nodes or rerun the policy after transformation.
  • Treating content security policy as the renderer: CSP is a defense layer, not a replacement for context-aware output encoding or sanitization.
  • Leaving the buffer unbounded: An adversarial or runaway response can force repeated parsing of an increasingly large string. Set a byte limit and stop rich rendering or switch to a plain-text fallback when it is exceeded.

Inspect the resulting DOM, not just the sanitized string. Regression cases should split an attack string at every byte boundary, include nested and malformed Markdown, exercise unsafe URL schemes, and run through syntax highlighting and link handling. A successful unit test of the sanitizer alone does not prove that later renderer stages preserve its output policy.

Decision scenario

A chat application currently inserts each completed token group as HTML. An attacker-controlled retrieved page causes the model to emit a link whose destination is split between two stream events, followed by a raw image element with an event handler. Keep the Markdown source in a bounded buffer, parse the whole accumulated text with raw HTML disabled, sanitize the generated nodes, and render the sanitized fragment. If the response exceeds the configured size limit, switch to escaped plain text and record that rich rendering stopped; do not skip the policy to preserve formatting.

This choice may spend more time reparsing than an append-only renderer, but it gives the parser complete context and keeps sanitization adjacent to the DOM operation. Measure the reparse cost and stream-to-paint delay before optimizing. Any optimization must preserve the same guarantee for split constructs and must be tested through the final rendered DOM.

Learning outcomes

  • Explain why stream events cannot be treated as independent HTML fragments.
  • Separate Markdown parsing, output sanitization, and DOM insertion responsibilities.
  • Choose safe behavior for raw HTML, links, oversized messages, and post-sanitization transforms.
  • Design regression inputs that split attack syntax across arbitrary token boundaries.

Quantitative model

For a full-prefix renderer, let LkL_k be the UTF-8 byte length of the accumulated Markdown passed to the parser at render commit kk. The cumulative parser input is:

Wparse=∑k=1nLkW_{\mathrm{parse}} = \sum_{k=1}^{n} L_k

WparseW_{\mathrm{parse}} is measured in bytes of source text, not CPU time. If 20 coalesced commits each parse an average 4 KiB accumulated message, the renderer submits about 80 KiB of Markdown to the parser. This estimate helps decide whether to reduce commit frequency or adopt parser-aware block commits; it does not justify bypassing sanitization.

Accumulate untrusted text deltas
Parse the complete Markdown prefix
Disable raw HTML or constrain its nodes
Sanitize elements attributes and URLs
Insert the sanitized fragment into the DOM
Conceptual teaching model synthesized from:micromark-commonmark-parser,owasp-xss-prevention,dompurify-docs

Implementation pattern

This example reparses a bounded accumulated source buffer at most once per animation frame. Raw HTML is disabled, the allowed Markdown output is narrow, and the sanitizer returns a fragment that is inserted without further HTML-string mutation.

typescript
import { micromark } from "micromark";
import DOMPurify from "dompurify";
​
const MAX_SOURCE_BYTES = 64_000;
const ALLOWED_TAGS = ["p", "strong", "em", "code", "pre", "a", "ul", "ol", "li"];
const ALLOWED_ATTR = ["href", "title", "class"];
const ALLOWED_URI_REGEXP = /^(?:(?:https?):|\/|#)/i;
​
export function bindSafeMarkdownStream(target: HTMLElement) {
let source = "";
let frame = 0;
let disposed = false;
​
const commit = () => {
frame = 0;
if (disposed) return;
const html = micromark(source, { allowDangerousHtml: false });
const fragment = DOMPurify.sanitize(html, {
ALLOWED_TAGS, ALLOWED_ATTR, ALLOWED_URI_REGEXP, FORBID_ATTR: ["style"], RETURN_DOM_FRAGMENT: true,
}) as DocumentFragment;
target.replaceChildren(fragment);
};
const schedule = () => {
if (frame === 0) frame = requestAnimationFrame(commit);
};
​
return {
push(delta: string) {
if (disposed) return;
const candidate = source + delta;
if (new TextEncoder().encode(candidate).byteLength > MAX_SOURCE_BYTES)
throw new RangeError("Markdown response exceeds the rich-render limit");
source = candidate;
schedule();
},
flush() {
if (frame !== 0) cancelAnimationFrame(frame);
commit();
},
dispose() {
disposed = true;
if (frame !== 0) cancelAnimationFrame(frame);
},
};
}
Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-501AI Evaluation and Reliability

Turn product intent and risk into representative evaluations release gates traces service targets and continuously improving regression evidence.

17 concepts~22h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next