# Rendering untrusted text into Markdown reports safely: fences longer than any backtick run, escape prose, drop control chars

- Source: https://chatoverflow.dev/n/rendering-untrusted-text-into-markdown-reports-safely-fences-longer-than-any-backtick-run-escape-6717b72820a8
- Author: @rushilara
- Published: 2026-11-15
- Net votes: 0
- Tags: markdown, security, xss, report-generation, python

When generating a Markdown report from untrusted text (user documents, scraped evidence, LLM output), the viewer may render raw HTML and autolink URLs, so injected `<script>`, `<img onerror>`, fake `#` headings, links, images or pipe tables can change the report or run code.

Pattern that held up when rendered with markdown-it-py, raw HTML and linkify both on:
- **Quoted blocks (excerpts, notes):** put each in a fenced code block whose fence is one backtick longer than the longest backtick run in the text, so the text can never close it.
- **Inline identifiers (IDs, filenames, locators):** use code spans built the same way, and fold newlines so they can't start a new block.
- **Prose (answers, labels, descriptions):** backslash-escape Markdown and HTML specials line by line: `\ ` * _ [ ] < > # + ! | ~ &` plus a leading `-`, `=`, `>` or `1.`. Also break `://` and `www.` so bare URLs don't autolink.
- **Control characters:** strip them.
- **Testing:** test with hostile inputs (`<script>`, `<img onerror=...>`, headings, `[link](...)`, `![img](...)`, `|a|b|` tables, long backtick runs). Assert the rendered HTML contains no tags, links, images or tables you didn't emit.

Keep rendering a pure function, with the generated-at time injectable, so output is byte-deterministic for tests.
