
Safely Rendering Untrusted HTML and Markdown: CSP, Sandboxed Iframes, and Origin Isolation
A security architecture guide to hosting and previewing user-supplied or AI-generated HTML and Markdown without exposing session cookies, API keys, or your primary domain to XSS.
Rendering user-supplied or AI-generated HTML is one of the highest-risk features a web application can ship. The moment arbitrary markup runs inside your application's origin (https://yourapp.com), a single missed script vector gives an attacker full access to session storage, CSRF tokens, authenticated fetch() calls, and every pixel of your UI.
Even "Markdown-only" renderers routinely fall victim to Cross-Site Scripting (XSS) through raw HTML passthrough, javascript: links, or SVG payloads. Protecting users requires defense in depth: combining origin isolation, browser sandboxing, Content Security Policy (CSP), and strict HTML sanitization.
Why HTML Sanitization Alone Is Not Enough
Sanitizers like DOMPurify and rehype-sanitize are essential when you need to render rich text inline inside your main app (such as comments or Markdown previews). They parse the markup into a real DOM tree and strip dangerous elements (<script>, <iframe>, <object>) and event attributes (onload, onerror, onclick).
However, relying solely on a sanitizer breaks down in two common situations:
- You actually want interactive HTML/JS to run (for example, hosting a calculator, chart, or prototype generated by an LLM). A sanitizer strips the exact
<script>tags the author needs. - Mutation XSS (mXSS) and parser differentials: Browsers repair malformed HTML differently depending on context (
<math>,<svg>,<noscript>). Even mature sanitizers ship periodic patches for edge-case bypasses.
That is why security-critical platforms (GitHub Pages, CodePen, Notion embeds, Google Docs previews, and static document hosts) never serve untrusted HTML from the same origin as their logged-in dashboard.
Layer 1: Origin Isolation (The Most Important Boundary)
The browser's Same-Origin Policy (SOP) is the strongest security boundary on the web. An origin is the tuple of (scheme, host, port).
If your authenticated app lives on https://app.example.com, never serve untrusted HTML on https://app.example.com/u/123—and avoid serving it on a sibling subdomain like https://user.example.com if your auth cookies set Domain=.example.com.
Instead, serve untrusted content from a completely separate registrable domain (for example, exampleusercontent.com or a dedicated .co content domain):
| Architecture | Cookie Isolation | localStorage Isolation | Risk if XSS Occurs |
|---|---|---|---|
Same origin (app.com/p/123) | None | None | Full account takeover |
Sibling subdomain (u.app.com) | Only if cookies omit Domain | Isolated | Cookie-tossing & parent-domain cookie theft |
Separate domain (app-content.co) | Complete | Complete | Confined to anonymous content origin |
With a separate content domain, even a full JavaScript execution inside a hosted page cannot read your main app's cookies, call authenticated APIs with credentials, or access the logged-in user's localStorage.
Layer 2: Sandboxed Iframes (sandbox Attribute)
When you embed a live preview inside your editor or viewer shell, wrap the untrusted document in an <iframe> with the sandbox attribute:
<iframe
src="https://sandbox.example-content.co/preview/abc123"
sandbox="allow-scripts allow-forms"
referrerpolicy="no-referrer"
loading="lazy"
title="Document preview"
></iframe>Pay close attention to one notorious misconfiguration:
Never combine allow-scripts and allow-same-origin on an iframe served from your main application origin.
If an iframe has both allow-scripts and allow-same-origin on the same origin as its parent page, the embedded script can simply traverse window.frameElement, remove the sandbox attribute, and reload itself—completely escaping the sandbox.
Keep allow-same-origin off whenever possible (which forces the iframe into a unique opaque null origin), or serve the iframe src from your dedicated separate content domain.
Layer 3: Content Security Policy (CSP) Headers
A strict Content-Security-Policy HTTP response header limits what an untrusted document can do even if it runs JavaScript.
For Markdown / Static Document Views (No Scripts Needed)
When serving rendered Markdown where no author JavaScript should execute, lock the page down completely:
Content-Security-Policy: default-src 'none'; img-src https: data:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; frame-ancestors 'none'; base-uri 'none'; form-action 'none'
X-Content-Type-Options: nosniff
Referrer-Policy: no-referrer
Every directive has a concrete job:
default-src 'none'blocks scripts, frames, objects, and network beacons by default.base-uri 'none'stops<base href="https://evil.com/">hijacking of relative URLs.form-action 'none'prevents phishing forms from submitting credentials to an attacker's server.X-Content-Type-Options: nosniffprevents browsers from MIME-sniffing a.txtor.svgupload into executable HTML.
For Interactive HTML Pages (Scripts Allowed on Isolated Domain)
When hosting interactive HTML on your isolated content domain, you still want to prevent clickjacking, cross-site data exfiltration, and framing abuse:
Content-Security-Policy: frame-ancestors 'self' https://app.example.com; object-src 'none'; base-uri 'self'
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Layer 4: Defending Against Phishing and Malware Hosting
Security for a public HTML/Markdown host isn't only about protecting your own domain—it's also about preventing attackers from using your clean domain reputation to host credential-harvesting pages.
A practical moderation stack combines three automated checks at publish time:
- URL extraction & threat intelligence: Parse every
href,src, andactionURL from the submitted HTML/Markdown and check them against Google Web Risk / Safe Browsing APIs before publishing. - Form & credential heuristics: Flag pages containing
<input type="password">combined with brand-impersonation titles (bank logins, cloud storage sign-in clones) for automated quarantine or human review. - Fast takedown & CDN purge: Store a clean audit trail and build a single-command moderation path that immediately restricts public routes, removes generated OG thumbnails, and purges edge CDN caches without losing abuse-investigation evidence.
Layer 5: Sanitizing Markdown Pipelines Properly
If you render Markdown directly into HTML on the server or client, verify these four checklist items:
- Disable raw HTML in the Markdown parser unless explicitly needed (
html: falseinmarkdown-it, or omitrehype-rawinremark). - Filter URL protocols: Allow only
https:,http:,mailto:, and relative#anchors. Blockjavascript:,vbscript:, anddata:text/html. - Add
rel="noopener noreferrer ugc"to user-authored external links so untrusted pages cannot abusewindow.openeror pass search-ranking authority to spam domains. - Treat SVG as code, not an image: An
<svg>file can contain<script>tags andonloadhandlers. Either sanitize SVGs through DOMPurify with the SVG profile or serve them withContent-Security-Policy: sandboxheaders.
FAQ
Is sandbox="allow-scripts" safe without allow-same-origin?
Yes, for origin isolation. Without allow-same-origin, the browser assigns the iframe an opaque null origin, blocking access to the parent DOM, cookies, and localStorage. You should still set frame-ancestors, referrerpolicy="no-referrer", and avoid allow-top-navigation so the iframe cannot redirect the parent tab.
Why shouldn't I use srcdoc iframes on my main domain for untrusted HTML?
A srcdoc iframe inherits the parent page's origin unless allow-same-origin is omitted from sandbox. Even with sandbox="allow-scripts", serving untrusted payloads inside your main HTML response inflates page size, complicates CSP, and puts untrusted bytes on the same network origin as your app. A separate content domain is cleaner and safer.
Does DOMPurify protect against CSS-based data exfiltration?
Not automatically if you allow <style> tags or arbitrary style attributes. Attackers can use CSS attribute selectors (input[value^="a"] { background: url(...) }) to leak sensitive text. Pair DOMPurify with a strict img-src / default-src CSP and strip <style> tags in untrusted inline contexts.
Why do static hosts put user pages on a separate domain like *.github.io or dochost.co?
Because cookies, localStorage, Service Workers, and browser permissions are scoped by registrable domain and origin. Separating the application domain from the user-content domain ensures that arbitrary JavaScript inside a user page can never compromise signed-in user accounts on the main platform.
作者
dochost(Xhorizon Labs LLC)创始人。长期专注于静态网页发布、HTML/Markdown 渲染与安全隔离,以及 AI 辅助开发工作流的软件工程师。
分类
sandbox Attribute)Layer 3: Content Security Policy (CSP) HeadersFor Markdown / Static Document Views (No Scripts Needed)For Interactive HTML Pages (Scripts Allowed on Isolated Domain)Layer 4: Defending Against Phishing and Malware HostingLayer 5: Sanitizing Markdown Pipelines ProperlyFAQIs sandbox="allow-scripts" safe without allow-same-origin?Why shouldn't I use srcdoc iframes on my main domain for untrusted HTML?Does DOMPurify protect against CSS-based data exfiltration?Why do static hosts put user pages on a separate domain like *.github.io or dochost.co?更多文章

Claude Skills vs Projects vs Artifacts: What Each One Actually Is
Three Claude features with overlapping names and completely different jobs. Skills are procedures, Projects are context, Artifacts are output — here's how to tell which one you need.

How to Publish a Claude or ChatGPT Page in One Click With the Chrome Extension
The dochost extension adds a Publish button next to the HTML and Markdown your AI writes — including Claude's file cards. Here is the full flow, recorded in a real Claude chat, and what each option in the panel does.

How to Turn a Claude Artifact Into a PDF
Chat artifacts have no export-to-PDF button, and printing from the chat prints the conversation instead. Here's the route that actually produces a clean PDF of the artifact itself.
邮件列表
加入我们的社区
订阅邮件列表,及时获取最新消息和更新