Port patterns / Capabilities and trust boundaries
Privilege-separated parser sandbox (zero-network parsing)
Parsing untrusted uploads, Markdown or AI output inside your main origin puts your cookies, storage and session tokens one parser bug away from theft. Borrow OpenSSH's privilege separation and Chromium's DataDecoder utility process: spawn a throwaway <iframe sandbox="allow-scripts"> locked down with CSP default-src 'none', transfer raw bytes zero-copy over a MessagePort, and read back plain structured JSON. If a hostile input tries to exfiltrate data, CSP and the opaque origin block it; if a regex stalls, a watchdog kills the iframe and respawns a clean one.
When you'd use this
An authenticated web app accepts user-uploaded documents, third-party templates or raw LLM output and needs to parse them without exposing session cookies, storage or the DOM to a parser vulnerability. Running the parser inside an opaque-origin <iframe sandbox="allow-scripts"> with CSP default-src 'none' gives you browser-enforced zero-network isolation and instant teardown if a malicious payload hangs.
Code
// Host app: spawn a zero-network parser iframe with an opaque origin
const frame = document.createElement("iframe");
frame.sandbox = "allow-scripts";
frame.srcdoc = `<meta http-equiv="Content-Security-Policy"
content="default-src 'none'; script-src 'unsafe-inline'; connect-src 'none'; img-src 'none'; frame-src 'none'">...`;
// Transfer raw bytes zero-copy over a job port with a hard watchdog timeout
const bytes = new TextEncoder().encode(untrustedMarkdown);
port.postMessage({ id, buf: bytes.buffer }, [bytes.buffer]); // bytes.buffer.byteLength === 0
const watchdog = setTimeout(() => { port.close(); frame.remove(); respawn(); }, 300);
In practice
// Host app: isolate untrusted Markdown/YAML parsing in a throwaway zero-network frame
async function parseUntrusted(rawText, timeoutMs = 300) {
const { frame, port } = await getOrSpawnParserSandbox();
const bytes = new TextEncoder().encode(rawText);
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
port.close();
frame.remove(); // kill wedged sandbox on timeout
reject(new Error("parser timed out"));
}, timeoutMs);
port.onmessage = ({ data }) => { clearTimeout(timer); resolve(data.ast); };
port.postMessage({ buf: bytes.buffer }, [bytes.buffer]); // zero-copy transfer
});
}
How it works
Desktop and server software learnt this lesson decades ago: OpenSSH splits network parsing into an unprivileged chrooted process, and Chromium parses untrusted JSON, XML and images inside its sandboxed DataDecoder utility process. You can build the exact same privilege separation inside a web app with an <iframe sandbox="allow-scripts"> and a MessagePort.
Omitting allow-same-origin gives the iframe an opaque origin, so it can't read your page's DOM, cookies, localStorage or IndexedDB. Pairing that with a strict CSP (default-src 'none'; connect-src 'none'; img-src 'none'; frame-src 'none') cuts off every exfiltration channel: even if an attacker achieves full JavaScript execution inside the parser, fetch(), WebSocket, beacons and image tags are all blocked by the browser.
Data moves in and out over one narrow MessagePort. Transferring raw input as an ArrayBuffer hands ownership over zero-copy (the host buffer's byteLength drops to zero), and the host only accepts plain structured data back — never raw HTML injected straight into the DOM.
Because the sandbox is disposable and stateless, you can wrap every parse job in a short watchdog timer. If a catastrophic regex (ReDoS) or infinite loop wedges the parser, call port.close() and iframe.remove(), then spin up a clean replacement.
Step by step
What each press of Next does in the demo above.
- Spawn zero-network parser sandbox. Host app launches an opaque-origin <iframe sandbox="allow-scripts"> locked with CSP default-src 'none' and transfers a dedicated job port to it.
- Parse clean Markdown. Host encodes Markdown to a Uint8Array and transfers the ArrayBuffer zero-copy (byteLength drops to 0). The sandbox parses headings and links and sends clean JSON back.
- Feed hostile payload. Host feeds an attack payload that tries fetch(), localStorage and parent.document. CSP connect-src 'none' and the opaque origin block every exfiltration path.
- Kill hung parser on timeout. Host sends a ReDoS payload with a 300ms watchdog. When the sandbox stalls, Host kills the iframe completely and respawns a fresh sandbox while staying responsive.
What you can build with it
Other ideas
- Parsing untrusted user uploads (Markdown, CSV, YAML, EXIF, SVG metadata) before rendering anything in your authenticated app origin.
- Sanitising and validating structured tool outputs or code blocks returned by an LLM before acting on them.
- Running third-party WebAssembly codecs or document converters with zero network access and hard execution timeouts.
Things to try
- In Step 2, check the Host app log after parsing clean Markdown:
buf.byteLengthdrops to0the moment theArrayBufferis transferred. - In Step 3, watch the hostile payload attempt
localStorage,parent.documentandfetch()inside the sandbox — all three are blocked while Host's secret stays untouched. - In Step 4, trigger the hung parser and watch the 300ms watchdog destroy the iframe and spawn Parser sandbox #2, then parse clean Markdown again.
Gotchas
- Don't add
allow-same-originalongsideallow-scriptson a sandboxed iframe served from your own origin — that lets the iframe reach up and remove its ownsandboxattribute. - A
srcdociframe withscript-src 'unsafe-inline'is handy for self-contained demos, but in production serve the parser from a dedicated static sandbox origin (or with CSP hashes/nonces) so injected script tags inside the sandbox can't run either. - An infinite synchronous loop inside a same-process iframe can still compete for the main thread if the browser doesn't isolate it into its own site process. For guaranteed CPU preemption on heavy untrusted parsing, pair the sandboxed iframe with a Dedicated Worker inside a separate sandbox origin so
worker.terminate()kills the thread instantly. - You still need to validate the JSON coming back from the sandbox. A compromised parser can't steal your cookies, but it can return crafted strings if you pass them straight to
innerHTML.
References
The web platform features this page mentions, with what each one is, its documentation on MDN and the specification that defines it.
- <iframe>
- An element that shows another page inside this one. The inner page can be on a different origin, and the two can only talk by posting messages. MDNHTML Standard
- Content Security Policy
- A header that limits what a page may load and where it may connect. MDNContent Security Policy
- MessagePort
- One end of a message channel. Whatever is posted into it comes out of the other end, and it can be sent to another page, frame or worker. MDNHTML Standard
- localStorage
- A small store of strings that belongs to one origin and is kept between visits. MDNHTML Standard
- IndexedDB
- A database in the browser that belongs to one origin. It can store most things that can be posted, including a CryptoKey. MDNIndexed Database API
- WebSocket
- A two-way connection between a page and a server that stays open. MDNWebSockets Standard
- ArrayBuffer
- A block of raw bytes. It can be moved to another thread without copying. MDNECMAScript
- WebAssembly
- A compact binary format for code that browsers run at close to native speed. MDNWebAssembly JavaScript Interface
- Web Workers
- Scripts that run on their own thread, away from the page. MDNHTML Standard
For more, see Further reading: articles, talks, papers, libraries and the specifications, collected in one place.