Black Friday30% off · BLACKFRIDAY30–d––h––m
Safely Rendering Untrusted HTML and Markdown: CSP, Sandboxed Iframes, and Origin Isolation
Nov 26, 2026

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:

  1. 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.
  2. 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):

ArchitectureCookie IsolationlocalStorage IsolationRisk if XSS Occurs
Same origin (app.com/p/123)NoneNoneFull account takeover
Sibling subdomain (u.app.com)Only if cookies omit DomainIsolatedCookie-tossing & parent-domain cookie theft
Separate domain (app-content.co)CompleteCompleteConfined 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: nosniff prevents browsers from MIME-sniffing a .txt or .svg upload 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:

  1. URL extraction & threat intelligence: Parse every href, src, and action URL from the submitted HTML/Markdown and check them against Google Web Risk / Safe Browsing APIs before publishing.
  2. 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.
  3. 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: false in markdown-it, or omit rehype-raw in remark).
  • Filter URL protocols: Allow only https:, http:, mailto:, and relative #anchors. Block javascript:, vbscript:, and data:text/html.
  • Add rel="noopener noreferrer ugc" to user-authored external links so untrusted pages cannot abuse window.opener or pass search-ranking authority to spam domains.
  • Treat SVG as code, not an image: An <svg> file can contain <script> tags and onload handlers. Either sanitize SVGs through DOMPurify with the SVG profile or serve them with Content-Security-Policy: sandbox headers.

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.

Newsletter

Join the community

Subscribe to our newsletter for the latest news and updates