When a ‘sandboxed’ result is painted back into the app origin
The app isolated the code that builds HTML but then rendered the resulting HTML in its own origin, making it stored XSS.
Published on medium.com
Cybersecurity
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
Products that let people run templates, macros, or little preview scripts usually put that work in a Web Worker or a sandboxed iframe. That is a good instinct. A worker has no DOM and no cookies. A sandboxed iframe, if you leave allow-same-origin off, sits in an opaque unique origin and cannot reach the parent page. Teams often stop at that point and call the feature safe.
The isolation only covers the place that produced the string. It does not travel with the string. If the parent application later takes that HTML and inserts it into its own document, the browser parses it in the application origin, with the user's session and the rest of the page's JavaScript. The sandbox never got a vote on the step that matters.
This is a stored XSS problem wearing a sandbox label. The pattern was reported and, in the case the author has in mind, it was fixed. The product itself is not described here. The walk-through uses a made-up app, Ledgerly, on app.example.test, so the data flow can be shown without describing anyone's real host, API, or UI.
Ledgerly is a team workspace. People attach small "views" to a record: a snippet that turns row data into a status card or a formatted note. The snippet is deliberately kept away from the main page.
Setup
No accounts, roles, tools or versions are given. The scenario is a team workspace where a record carries a macro source and row data, and a runner executes that source in isolation. The runner is either a module worker or an iframe with sandbox="allow-scripts" and a runner document that is, on paper, sealed off from the parent.
Both setups do real work. The worker cannot touch document. The iframe, without allow-same-origin, cannot read the parent's DOM or the parent's cookies. If the result stayed there, that is, if Ledgerly displayed the preview inside that frame or on a separate origin such as preview.example.test, the design would hold.
Finding it
The last step is where it usually breaks. The runner finishes and posts a message back. The payload looks ordinary: a title, maybe some metadata, and a field named html. A renderer on app.example.test listens for that message and paints the preview into the page it already has open.
The mix-up is almost always a category error. People talk about "sandboxed HTML" as if a string could carry a privilege level. It cannot. A browsing context can be sandboxed. A worker can be denied access to a document. A string is just a string. The browser decides what that string means at the moment something trusted, the parent page, feeds it to a parser.
The WHATWG HTML Standard and MDN's iframe documentation are explicit about what sandbox actually restricts: the nested browsing context. Flags like allow-scripts and allow-same-origin change what that nested context may do. They say nothing about a copy of its output pasted somewhere else.
Two details show up in otherwise careful designs.
First, sandbox="allow-scripts allow-same-origin" on a frame that is served from the application origin is not a sandbox in any useful sense. Scripts run, and they run same-origin with the parent. The flags cancel each other out. MDN warns about this combination for a reason.
Second, storing the HTML and rendering it later does not make it safer. If Ledgerly saves result.html on the record and a teammate opens that record tomorrow, or a notification view renders the same field, you have stored XSS. The person who hits the sink may not be the person who edited the macro. PortSwigger's DOM XSS material is about sources and sinks in the page itself; this class is the same idea with an extra hop. The source is "output of an isolated engine", which looks trustworthy in a code review, and the sink is still in the application origin.
Exploitation
Step 1: the isolated runner
A typical runner hands the macro source and the row data to a module worker:
const worker = new Worker("/macros/runner.js", { type: "module" });worker.postMessage({ source: record.macroSource, rows: record.rows,});
The worker receives the source and the rows. It has no DOM and no cookies, so the code it runs cannot reach the page directly. The same job is sometimes handed to an iframe with sandbox="allow-scripts" and a sealed runner document instead.
Step 2: the message back
The payload contains a title, possibly some metadata, and a field named html.
Step 3: the assignment in the parent
worker.onmessage = (event) => { const result = event.data; const preview = document.querySelector("#preview"); preview.innerHTML = result.html;};
That single assignment is the bug. innerHTML parses the string in the parent document. Anything the HTML parser will honour now runs as Ledgerly, not as the worker. The origin of the insertion is the origin that matters, not the origin of the code that built the string.
Step 4: the marker
A reviewer does not need a dramatic payload to show this. A marker is enough:
function renderStatus() { return { html: "Status: <b>injected</b>" };}
If "injected" shows up bold in the main application chrome, styled like the rest of the page and sitting outside any iframe, the sandbox is no longer the boundary. That is the finding. You can stop there and talk to the developer. You do not need to demonstrate session theft or data exfiltration to prove the class.
When a clean demonstration is wanted, the bold marker is used. If it needs to be shown that the node is really in the parent tree, the element inspector is enough: the <b> sits under #preview, in the application's document, not inside the runner frame.
Other sinks
The same hole appears with outerHTML, insertAdjacentHTML, document.write, jQuery's .html(), a framework helper that sets element.innerHTML, and React's dangerouslySetInnerHTML. DOMParser.parseFromString followed by adopting those nodes into the live document is the same sink with an extra step. If the nodes end up in the parent tree, the parent origin owns them.
Root cause
The isolation covers the producer, not the consumer. The worker or sandboxed iframe is correctly denied access to the document, but the string it returns is then handed to an HTML parser in the application origin. The browser applies the privileges of the document doing the insertion, so the sandbox has no effect on the result.
The sandbox attribute restricts a nested browsing context, and the worker's lack of a DOM restricts the worker. Neither says anything about a copy of the output pasted elsewhere. Persisting the HTML and rendering it later does not help either: it turns the same sink into stored XSS, and the person who hits the sink may not be the person who edited the macro.
Impact
Once the markup runs in the app origin, it can do what the user's browser can do on that origin. It can call the same APIs the page calls, change records the user is allowed to change, and present UI that looks like Ledgerly. If the result was saved, anyone who later opens the view is exposed, including people who never touched the macro.
That is already a serious integrity problem in a shared workspace. The author deliberately does not recite exploit recipes. The architecture is the point: a boundary that does not contain the output is not a boundary.
Fix
The cleanest fix is not to take HTML out of the sandbox. Keep the preview in a nested context that cannot reach the parent, or put it on a dedicated origin such as preview.example.test.
function paintPreview(result) { const frame = document.querySelector("#preview-frame"); frame.setAttribute("sandbox", ""); frame.srcdoc = result.html;}
An empty sandbox attribute is strict, and for a static preview that is usually what you want. If the preview genuinely needs scripts, do not add allow-same-origin on a same-origin frame. Serve it from a separate origin and keep the sandbox tight: no allow-top-navigation, no allow-popups unless there is a specific reason, and a narrow CSP on that origin (base-uri, form-action, and a locked-down script-src). The parent should talk to it only through postMessage, with origin checks, and should never copy HTML back out.
If the product does not need rich markup at all, drop HTML from the contract. Return data and build the DOM with safe APIs:
worker.onmessage = (event) => { const { title, items } = event.data; const heading = document.createElement("h3"); heading.textContent = title; const list = document.createElement("ul"); for (const item of items) { const li = document.createElement("li"); li.textContent = item; list.append(li); } preview.replaceChildren(heading, list);};
textContent and createElement do not parse markup. A <b>injected</b> string in title would show up as literal text, which is the correct failure mode.
If HTML must be inserted into the parent, sanitise it with a well-maintained library, and treat that as a second layer, not as permission to skip isolation. The OWASP XSS Prevention Cheat Sheet is blunt on this: untrusted data should not land in HTML sinks unsanitized, and output encoding or a sanitizer has to match the context.
Then make the dangerous sinks hard to use by accident. Trusted Types exist for this. A policy is the only way to produce a TrustedHTML value, and innerHTML will refuse a raw string. Google's walk-through of Trusted Types is the practical version of the same idea: force every sink through a function you can audit, and enforce it with require-trusted-types-for 'script' in CSP.
const policy = trustedTypes.createPolicy("ledgerly-preview", { createHTML: (unsafe) => DOMPurify.sanitize(unsafe, { USE_PROFILES: { html: true }, }),});preview.innerHTML = policy.createHTML(result.html);
CSP is a backstop, not a substitute for the architecture fix. A strict script-src (nonces or hashes, no unsafe-inline) will block many inline handlers and injected scripts. It will not save you from every markup injection, and it does nothing to restore a sandbox you already left.
None of this changes the rule at the top. Treat worker and iframe output as untrusted input, the same way you treat a JSON field from an API. The runner's isolation is a fact about the runner. It is not a fact about the string it returned.
Variants to test
- Worker output into
innerHTML. Look for aWorkerconstructor and follow the result. A positive result is a harmless marker such as<b>injected</b>rendering bold in the main application chrome, outside any iframe. - Sandboxed iframe output copied back. Look for an iframe with a
sandboxattribute whose result is read out and inserted into the parent. A positive result is the marker appearing in the parent document, confirmed in the element inspector under the preview container. - Same-origin frame with both flags. Check for
sandbox="allow-scripts allow-same-origin"on a frame served from the application origin. Check forsandbox="allow-scripts allow-same-origin"on a frame served from the application origin. - Delayed sinks. Look for a field written to storage and read by a different screen, an export, a share view, or a mobile webview. Save the view and open it as a second user, or on a different screen that also renders the field.
- Alternative sinks. Search the parent for
outerHTML,insertAdjacentHTML,document.write,.html(),dangerouslySetInnerHTML, andDOMParser.parseFromStringfollowed by adoption of the nodes. Search the parent for these sinks and follow whether the string reaches them. - Structured contract check. Determine whether the message contract is a structured object or a blob of markup. If it is markup, the interesting question is not whether the worker has a DOM, but whether any document at the application origin ever treats the string as HTML.
For developers, the checklist is: inspect the live document to see where the preview actually runs; search application-origin code for the sinks above; confine required HTML to a sandboxed iframe or separate origin and never copy it back; avoid allow-scripts plus allow-same-origin on a same-origin frame; prefer structured data rendered with textContent and createElement; apply a maintained sanitizer at the sink; and enforce Trusted Types with a strict CSP as a backstop.
For testers: follow the output from the isolated engine to every sink before reaching for a payload; start with a harmless marker and look at which document it landed in; save the view and open it as a second user or on a different screen; check delayed paths such as notifications, exports, share links and embedded views; and if the product claims the runner is sandboxed, treat that as a hypothesis about the producer and test the consumer.
The sandbox in these designs often did its job. The application then scooped the result back into the place the sandbox was there to protect. That last assignment is the one worth reading twice.
What happened, in plain words
Imagine a company that lets you write tiny recipes to decorate your own data. You type a little snippet, the product runs it somewhere out of the way, and the result is shown to you as a nice card. The product is careful: it runs your snippet in a separate, locked room so that a badly written or malicious snippet cannot reach the main page. That is a sensible thing to do.
The problem in this write-up is what happens after the locked room finishes. The locked room hands back a piece of text, and the main page takes that text and pastes it straight into itself. The moment the main page does that, the text is no longer in the locked room. It is in the main page, with the user's login, the user's data and all the page's own powers. The lock on the room never applied to the copy that was carried out.
Security people call this kind of bug Cross-Site Scripting, or XSS for short. XSS means that an attacker manages to get their own instructions (usually a bit of HTML or JavaScript) treated as part of a trusted page, so the browser runs them as if the site itself had written them. When the bad text is saved somewhere and shown to other people later, it is called stored XSS.
The author says the pattern was reported and that, in the case they have in mind, it was fixed. They do not describe that real product. Instead they invent a pretend app called Ledgerly, running at app.example.test, so they can show the flow of data without exposing anyone's real website, real programming interface or real screens.
Ledgerly is a team workspace. People attach small "views" to a record: a snippet that turns row data into a status card or a formatted note. The snippet is deliberately kept away from the main page. The rest of this article walks through how that separation is built, how it is defeated, and how to fix it, in the same order as the technical write-up.
The comforting architecture
Before we look at the bug, we need a few everyday ideas.
A web page in a browser is a document. The browser reads the document's HTML (the markup language that says "this is a heading, this is bold, this is a button") and turns it into things you can see and click. The document also has a DOM, which is the browser's live, in-memory model of that page: every heading, paragraph and button is an object in a tree, and JavaScript code can read and change that tree. When people say "the page's JavaScript", they mean code running inside that document, with the same powers the page has.
An origin is the browser's way of deciding which website a piece of code belongs to. It is made of the scheme (http or https), the host name (like app.example.test) and the port. Two pages with the same origin can read each other's data; pages with different origins are kept apart. This separation is one of the most important safety walls in a browser.
A cookie is a small piece of data the browser stores for a website and sends back on every request. Websites commonly use a cookie to remember that you are logged in. If another website could read your cookies for a site, it could often act as you. That is why browsers guard cookies so carefully.
A Web Worker is a way for a page to run JavaScript in a background thread. It is like hiring a helper who works in a separate room: the helper can do heavy calculations without freezing the page you are looking at. Crucially, a worker has no DOM and no cookies. It cannot touch the page's elements and it cannot read the user's login. That makes it a good place to run code you do not fully trust.
An iframe is a page inside a page. It is a rectangular window embedded in the main document, showing another document. The sandbox attribute on an iframe is a list of permissions. By default, a sandboxed iframe is heavily restricted: it cannot run scripts, and so on. You can switch specific abilities back on with flags such as allow-scripts (let it run JavaScript) and allow-same-origin (let it keep its normal origin instead of being treated as a stranger).
A browsing context is the technical name for "a place where a document is displayed": a tab, a window, or an iframe. When the write-up says the sandbox restricts a nested browsing context, it means the sandbox rules apply to that inner frame, not to anything outside it.
With those ideas in place, here is Ledgerly's design. A typical runner looks like this:
const worker = new Worker("/macros/runner.js", { type: "module" });worker.postMessage({ source: record.macroSource, rows: record.rows,});
Line by line:
const worker = new Worker("/macros/runner.js", { type: "module" });creates a new background worker. The browser fetches the file/macros/runner.jsfrom the site and starts it in its own thread. The{ type: "module" }part tells the browser to treat that file as a modern JavaScript module (a file that can import other files). The result is stored in a variable calledworkerso the page can talk to it later.worker.postMessage({ ... });sends a message to the worker.postMessageis the standard way for a page and a worker to exchange data. The message here is an object with two fields:source, which is the snippet the user wrote (record.macroSource), androws, which is the data the snippet should work on (record.rows).
Why do it this way? Because the snippet is untrusted. The user wrote it, and users can write anything. By handing it to a worker, the page ensures that even if the snippet is hostile, it runs in a place with no DOM and no cookies. It cannot reach the page directly.
Sometimes the same job is handed to an iframe with sandbox="allow-scripts" and a runner document that is, on paper, sealed off from the parent. Both setups do real work. The worker cannot touch document (the object that represents the page). The iframe, without allow-same-origin, cannot read the parent's DOM or the parent's cookies. If the result stayed there, that is, if Ledgerly displayed the preview inside that frame or on a separate origin such as preview.example.test, the design would hold.
The last step is where it usually breaks.
The last assignment
The runner finishes and posts a message back. The payload looks ordinary: a title, maybe some metadata, and a field named html. A renderer on app.example.test listens for that message and paints the preview into the page it already has open.
worker.onmessage = (event) => { const result = event.data; const preview = document.querySelector("#preview"); preview.innerHTML = result.html;};
Line by line:
worker.onmessage = (event) => { ... };sets up a listener. When the worker sends a message back, the browser calls this function and passes it aneventobject containing the message. This is the receiving end of thepostMessagefrom the previous step.const result = event.data;pulls the actual message out of the event. In this design,resultis an object with a title, some metadata and anhtmlfield.const preview = document.querySelector("#preview");finds the element on the page whoseidispreview.querySelectoris the browser's standard way of looking up an element by a CSS selector;#previewmeans "the element with id preview". This is the box where the preview should appear.preview.innerHTML = result.html;is the dangerous line.innerHTMLis a property that means "the HTML inside this element". Assigning a string to it tells the browser: take this string, parse it as HTML, and build the resulting elements insidepreview.
That single assignment is the bug. innerHTML parses the string in the parent document. Anything the HTML parser will honour now runs as Ledgerly, not as the worker. The origin of the insertion is the origin that matters, not the origin of the code that built the string.
A reviewer does not need a dramatic payload to show this. A marker is enough:
function renderStatus() { return { html: "Status: <b>injected</b>" };}
Line by line:
function renderStatus() { ... }defines a function calledrenderStatus. In the pretend app, this stands in for whatever the runner does when it produces a result.return { html: "Status: <b>injected</b>" };returns an object with one field,html, whose value is the stringStatus: <b>injected</b>. The<b>tag is HTML for "bold". Nothing here is malicious; it is just a bold word.
If "injected" shows up bold in the main application chrome, styled like the rest of the page and sitting outside any iframe, the sandbox is no longer the boundary. That is the finding. You can stop there and talk to the developer. You do not need to demonstrate session theft or data exfiltration to prove the class.
Why is a harmless marker enough? Because the point being proven is not "I can steal data". The point is "the string I produced in the locked room was parsed as HTML by the main page". A bold word proves exactly that, with no risk to anyone. If the bold word appears in the main page's own styling, the browser treated it as part of the app. That is the whole bug.
When a clean demonstration is wanted, the bold marker is used. If it needs to be shown that the node is really in the parent tree, the element inspector is enough: the <b> sits under #preview, in the application's document, not inside the runner frame. The element inspector is the panel in a browser's developer tools that shows the live DOM tree, so you can see exactly which document an element belongs to.
Why the sandbox does not follow the output
The mix-up is almost always a category error. People talk about "sandboxed HTML" as if a string could carry a privilege level. It cannot. A browsing context can be sandboxed. A worker can be denied access to a document. A string is just a string. The browser decides what that string means at the moment something trusted, the parent page, feeds it to a parser.
A useful comparison: a sandbox is like a fenced play area for a child. The fence keeps the child inside. But if you take a drawing the child made and hang it on your living-room wall, the drawing is now in your living room. The fence had nothing to say about that. The drawing did not carry the fence with it.
The WHATWG HTML Standard and MDN's iframe documentation are explicit about what sandbox actually restricts: the nested browsing context. Flags like allow-scripts and allow-same-origin change what that nested context may do. They say nothing about a copy of its output pasted somewhere else.
Two details show up in otherwise careful designs.
First, sandbox="allow-scripts allow-same-origin" on a frame that is served from the application origin is not a sandbox in any useful sense. Scripts run, and they run same-origin with the parent. The flags cancel each other out. MDN warns about this combination for a reason. In plain words: allow-scripts says "this frame may run JavaScript", and allow-same-origin says "this frame counts as the same website as the parent". Put together, the frame can run code that is allowed to read and change the parent page. The fence has a gate, and the gate is open.
Second, storing the HTML and rendering it later does not make it safer. If Ledgerly saves result.html on the record and a teammate opens that record tomorrow, or a notification view renders the same field, you have stored XSS. The person who hits the sink may not be the person who edited the macro. A sink is the place in code where data ends up being used in a way that matters, here the innerHTML assignment. A source is where the data comes from. PortSwigger's DOM XSS material is about sources and sinks in the page itself; this class is the same idea with an extra hop. The source is "output of an isolated engine", which looks trustworthy in a code review, and the sink is still in the application origin.
How I look for it
I start with the data flow, not with a payload. A payload is the piece of input an attacker uses to trigger a bug. Starting with the payload means guessing; starting with the data flow means following the data from where it is produced to where it is used.
I look for the isolated execution: a Worker constructor, an iframe with a sandbox attribute, a same-origin "macro engine", a server-side renderer that returns HTML for a preview. Then I follow the result. Is the contract a structured object, a title, a list of strings, a set of numbers, or is it a blob of markup? A contract here means the agreed shape of the message: what fields it has and what type each field is.
If it is markup, I search the parent for the sinks above. I also search for delayed ones: a field written to storage and read by a different screen, an export, a share view, a mobile webview. The interesting question is not "does this worker have a DOM?" It is "does any document at the application origin ever treat this string as HTML?"
When I want a clean demonstration, I use the bold marker. If I need to show that the node is really in the parent tree, the element inspector is enough: the <b> sits under #preview, in the application's document, not inside the runner frame.
Impact, in plain terms
Once the markup runs in the app origin, it can do what the user's browser can do on that origin. It can call the same APIs the page calls, change records the user is allowed to change, and present UI that looks like Ledgerly. An API (Application Programming Interface) is the set of requests a program can make to a service. When the page calls the site's API, it does so with the user's login attached, so the API treats the request as coming from that user. If injected markup runs in the page, it can make the same calls.
If the result was saved, anyone who later opens the view is exposed, including people who never touched the macro. That is already a serious integrity problem in a shared workspace. Integrity here means the data is what it claims to be and has not been tampered with. The author deliberately does not recite exploit recipes. The architecture is the point: a boundary that does not contain the output is not a boundary.
Fixes that actually hold
The cleanest fix is not to take HTML out of the sandbox. Keep the preview in a nested context that cannot reach the parent, or put it on a dedicated origin such as preview.example.test.
function paintPreview(result) { const frame = document.querySelector("#preview-frame"); frame.setAttribute("sandbox", ""); frame.srcdoc = result.html;}
Line by line:
function paintPreview(result) { ... }defines a function that takes the runner's result and displays it.const frame = document.querySelector("#preview-frame");finds the iframe element with idpreview-frame. This is the frame that will hold the preview.frame.setAttribute("sandbox", "");sets thesandboxattribute to an empty string. An empty sandbox is the strictest setting: the frame gets no special permissions at all.frame.srcdoc = result.html;puts the HTML into the frame.srcdocis an iframe attribute that holds the frame's document as a string, instead of loading it from a URL. The browser parses that string inside the frame, not in the parent page.
An empty sandbox attribute is strict, and for a static preview that is usually what you want. If the preview genuinely needs scripts, do not add allow-same-origin on a same-origin frame. Serve it from a separate origin and keep the sandbox tight: no allow-top-navigation, no allow-popups unless there is a specific reason, and a narrow CSP on that origin (base-uri, form-action, and a locked-down script-src). The parent should talk to it only through postMessage, with origin checks, and should never copy HTML back out.
A CSP (Content Security Policy) is a set of rules a website sends to the browser saying which scripts, styles and other resources are allowed. script-src controls which scripts may run; base-uri controls what the page's base URL can be set to; form-action controls where forms may submit. A narrow CSP is a second lock on the door.
If the product does not need rich markup at all, drop HTML from the contract. Return data and build the DOM with safe APIs:
worker.onmessage = (event) => { const { title, items } = event.data; const heading = document.createElement("h3"); heading.textContent = title; const list = document.createElement("ul"); for (const item of items) { const li = document.createElement("li"); li.textContent = item; list.append(li); } preview.replaceChildren(heading, list);};
Line by line:
worker.onmessage = (event) => { ... };again sets up the listener for messages from the worker.const { title, items } = event.data;unpacks the message. This is destructuring: it takes thetitleanditemsfields out ofevent.dataand puts them in variables with those names. Notice that the message now contains data, not HTML.const heading = document.createElement("h3");creates a new heading element in memory.createElementbuilds an element from a tag name; it does not parse any string.heading.textContent = title;sets the heading's text.textContenttreats the value as plain text, so any<or>in it is shown literally, not interpreted as markup.const list = document.createElement("ul");creates an empty bulleted list element.for (const item of items) { ... }loops over each item in the list.const li = document.createElement("li");creates a list item element.li.textContent = item;puts the item's text into the list item, again as plain text.list.append(li);adds the list item to the list.preview.replaceChildren(heading, list);replaces whatever was inside the preview box with the new heading and list.replaceChildrenswaps the children in one go.
textContent and createElement do not parse markup. A <b>injected</b> string in title would show up as literal text, which is the correct failure mode. In other words, if someone tries to inject HTML, they see the characters <b>injected</b> on screen instead of a bold word. That is exactly what should happen.
If HTML must be inserted into the parent, sanitise it with a well-maintained library, and treat that as a second layer, not as permission to skip isolation. Sanitising means cleaning a string so that dangerous parts are removed or neutralised before it is used. The OWASP XSS Prevention Cheat Sheet is blunt on this: untrusted data should not land in HTML sinks unsanitized, and output encoding or a sanitizer has to match the context.
Then make the dangerous sinks hard to use by accident. Trusted Types exist for this. A policy is the only way to produce a TrustedHTML value, and innerHTML will refuse a raw string. Google's walk-through of Trusted Types is the practical version of the same idea: force every sink through a function you can audit, and enforce it with require-trusted-types-for 'script' in CSP.
const policy = trustedTypes.createPolicy("ledgerly-preview", { createHTML: (unsafe) => DOMPurify.sanitize(unsafe, { USE_PROFILES: { html: true }, }),});preview.innerHTML = policy.createHTML(result.html);
Line by line:
const policy = trustedTypes.createPolicy("ledgerly-preview", { ... });creates a Trusted Types policy with the nameledgerly-preview. A policy is a named set of rules for turning ordinary strings into trusted values.createHTML: (unsafe) => DOMPurify.sanitize(unsafe, { ... }),defines what the policy does when asked to create HTML. It takes the untrusted string (unsafe) and passes it through DOMPurify, a well-known sanitising library, with the optionUSE_PROFILES: { html: true }, which tells DOMPurify to allow normal HTML but not scripts and similar dangerous content.preview.innerHTML = policy.createHTML(result.html);asks the policy to turnresult.htmlinto a trusted HTML value, then assigns it toinnerHTML. Because Trusted Types is enforced,innerHTMLwould refuse a plain string here; only a value produced by a policy is accepted.
CSP is a backstop, not a substitute for the architecture fix. A strict script-src (nonces or hashes, no unsafe-inline) will block many inline handlers and injected scripts. A nonce is a random one-time value that a page includes in its CSP and in each legitimate script tag, so only scripts carrying the right nonce run. A hash is a fingerprint of a script's contents, so only scripts with exactly that content run. unsafe-inline is a CSP keyword that allows inline scripts, which weakens the policy. CSP will not save you from every markup injection, and it does nothing to restore a sandbox you already left.
None of this changes the rule at the top. Treat worker and iframe output as untrusted input, the same way you treat a JSON field from an API. JSON is a plain-text format for structured data, like {"title": "x", "items": [1, 2]}. The runner's isolation is a fact about the runner. It is not a fact about the string it returned.
A checklist
For developers:
- Where does the preview actually run? Inspect the live document, not just the
Workeror<iframe>that produced it. - Does any application-origin code assign runner output to
innerHTML,outerHTML,insertAdjacentHTML,document.write,.html(), ordangerouslySetInnerHTML? These are all different ways of telling the browser "parse this string as HTML".outerHTMLreplaces the element itself plus its contents;insertAdjacentHTMLinserts HTML at a position relative to an element;document.writewrites directly into the document;.html()is jQuery's version ofinnerHTML;dangerouslySetInnerHTMLis React's version, named that way as a warning. - If HTML is required, is it confined to a sandboxed iframe or a separate origin, and never copied back into the parent?
- If you set
sandbox, did you avoid theallow-scriptsplusallow-same-origincombination on a same-origin frame? - Is the message contract structured data when it can be, and rendered with
textContent/createElement? - If a sanitizer is in play, is it a maintained library, applied at the sink, with a policy you can explain?
- Are Trusted Types enforced, and is CSP strict enough to be a real backstop?
For testers:
- Follow the output from the isolated engine to every sink before you reach for a payload.
- Start with a harmless marker such as
<b>injected</b>. Look at which document it landed in. - Save the view and open it as a second user, or on a different screen that also renders the field.
- Check delayed paths: notifications, exports, share links, embedded views.
- If the product claims the runner is sandboxed, treat that as a hypothesis about the producer, and test the consumer.
The sandbox in these designs often did its job. The application then scooped the result back into the place the sandbox was there to protect. That last assignment is the one worth reading twice.
Glossary
- API: the set of requests a program can make to a service; the page's own API calls carry the user's login.
- Browsing context: a place where a document is displayed, such as a tab, a window or an iframe.
- Cookie: a small piece of data the browser stores for a website and sends back on every request, often used to remember that you are logged in.
- CSP (Content Security Policy): rules a website sends to the browser saying which scripts, styles and other resources are allowed.
- Contract: the agreed shape of a message between two parts of a program, such as which fields it has and what type each field is.
- DOM: the browser's live, in-memory tree of a page's elements, which JavaScript can read and change.
dangerouslySetInnerHTML: React's way of setting HTML from a string, named to warn you that it is risky.- Destructuring: JavaScript syntax that pulls named fields out of an object into variables.
document.write: a JavaScript function that writes a string directly into the document as HTML.- Element inspector: the panel in a browser's developer tools that shows the live DOM tree.
- Hash (CSP): a fingerprint of a script's contents, so only scripts with exactly that content run.
- HTML: the markup language that describes the structure of a web page.
innerHTML: a property that sets the HTML inside an element; assigning a string makes the browser parse it as HTML.insertAdjacentHTML: a function that inserts HTML at a position relative to an element.- Integrity: the property that data is what it claims to be and has not been tampered with.
- iframe: a page embedded inside another page.
- JSON: a plain-text format for structured data.
- Nonce: a random one-time value included in a CSP and in each legitimate script tag, so only scripts carrying it run.
- Origin: the combination of scheme, host name and port that the browser uses to decide which website a piece of code belongs to.
outerHTML: a property that replaces an element itself plus its contents with parsed HTML.- Payload: the piece of input an attacker uses to trigger a bug.
- Policy (Trusted Types): a named set of rules for turning ordinary strings into trusted values.
postMessage: the standard way for a page and a worker, or two frames, to exchange data.- Sanitising: cleaning a string so dangerous parts are removed or neutralised before use.
sandboxattribute: a list of permissions on an iframe; empty means the strictest setting.allow-scripts: a sandbox flag that lets the frame run JavaScript.allow-same-origin: a sandbox flag that lets the frame keep its normal origin instead of being treated as a stranger.allow-top-navigation: a sandbox flag that lets the frame navigate the top-level page.allow-popups: a sandbox flag that lets the frame open pop-up windows.- Sink: the place in code where data is used in a way that matters, such as an
innerHTMLassignment. - Source: where data comes from before it reaches a sink.
srcdoc: an iframe attribute that holds the frame's document as a string instead of loading it from a URL.- Stored XSS: XSS where the malicious input is saved and shown to other people later.
textContent: a property that sets an element's text as plain text, without parsing markup.- Trusted Types: a browser feature that forces dangerous sinks to accept only values produced by an approved policy.
unsafe-inline: a CSP keyword that allows inline scripts, which weakens the policy.- Web Worker: a way to run JavaScript in a background thread with no DOM and no cookies.
- XSS (Cross-Site Scripting): a bug where an attacker's instructions are treated as part of a trusted page and run by the browser.