Skip to main content

postMessage origin validation: how a missing check becomes XSS or token theft

window.postMessage is how a page talks to an iframe, a popup or its opener across origins. Payment widgets, chat embeds, OAuth popups, analytics frames and micro-frontends all use it. The API is safe by design in one sense: the browser always tells the receiver who sent the message. The problem is that it never forces the receiver to look.

A message listener that skips the event.origin check accepts input from any page that can get a reference to the window. A sender that passes "*" as the target origin will deliver its data to whatever page the target window happens to show. One mistake gives attackers a way in, the other a way to read out. This post covers both, the broken origin checks that keep turning up in review, and the fixes.

The receiver side: trusting event.data

Any page that can obtain a handle to your window can post to it. That includes a page that opens yours in a popup (it holds the window.open return value), a page that frames yours, and any frame within the same window hierarchy. If your listener acts on event.data without checking where it came from, the attacker's page controls that data.

// Vulnerable: any origin can post HTML into the page
window.addEventListener('message', (event) => {
  if (event.data.type === 'render') {
    document.getElementById('panel').innerHTML = event.data.html;
  }
});

An attacker hosts a page that opens yours and posts { type: 'render', html: '<img src=x onerror="...">' }. The script runs in your origin, with your cookies and your session. That is DOM XSS, and no server log will ever show it, because the payload never touched your server.

The sink does not have to be innerHTML for this to hurt. Common variations:

  • location.href = event.data.url gives an open redirect, or script execution with a javascript: URL.
  • eval or new Function on message data is direct code execution.
  • A listener that calls an authenticated API with parameters from the message lets the attacker drive actions as the user.
  • A listener that replies with state (event.source.postMessage(sessionInfo, event.origin)) hands that state to whoever asked.

MDN's guidance is direct: if you do not expect messages from other sites, do not add a message listener at all; if you do, always verify the sender with origin and possibly source, and then still validate the message syntax (Window.postMessage security concerns). The weakness has its own CWE entry: CWE-346, Origin Validation Error.

The fix: exact origin, then validate the payload

// Fixed: exact origin match, expected source, typed payload, safe sink
const TRUSTED_ORIGIN = 'https://widget.example.com';
const widgetFrame = document.getElementById('widget');

window.addEventListener('message', (event) => {
  if (event.origin !== TRUSTED_ORIGIN) return;
  if (event.source !== widgetFrame.contentWindow) return;

  const msg = event.data;
  if (msg?.type !== 'status' || typeof msg.text !== 'string') return;

  document.getElementById('panel').textContent = msg.text;
});

Four things are happening:

  1. Exact string comparison against a known origin, including scheme and port. Return early on anything else.
  2. Source check when you know which frame should be talking. This stops a different frame from the same trusted origin, or a stale one, from speaking for it.
  3. Shape validation. A trusted sender can still be compromised, or can relay data it got elsewhere. Check type and fields.
  4. A safe sink. textContent instead of innerHTML. If you genuinely need HTML, sanitise it with a maintained library.

For several trusted origins, use a Set of exact strings: if (!ALLOWED.has(event.origin)) return;.

Origin checks that look right and are not

A check exists in many vulnerable listeners. It is just wrong. These are the patterns to look for in review:

// All of these are bypassable
if (event.origin.indexOf('example.com') !== -1) {}  // https://example.com.attacker.net
if (event.origin.includes('example.com')) {}        // https://notexample.com
if (event.origin.endsWith('example.com')) {}        // https://attackerexample.com
if (/https:\/\/.*\.example.com/.test(event.origin)) {}  // unanchored, and "." matches any char
if (event.origin.startsWith('https://app.example')) {} // https://app.example.attacker.net

Substring tests match attacker domains that contain your name. Regular expressions need ^ and $ anchors and escaped dots, and are still easy to get wrong, so prefer exact comparison. Two more traps: checking event.origin but then acting on data before the check returns, and accepting "null", which is the origin reported by sandboxed iframes and some local files, and which an attacker can produce on demand.

The sender side: targetOrigin "*"

The second argument to postMessage tells the browser which origin is allowed to receive the message. With "*", the browser delivers it to whatever document is in the target window at that moment.

// Vulnerable: an OAuth popup returns the token to "whoever opened me"
window.opener.postMessage({ accessToken: token }, '*');

If an attacker's page opened that popup, the attacker's page is the opener, and it receives the token. The same applies to a widget that posts session data to window.parent with "*": if a hostile site frames the widget, the hostile site is the parent. MDN also notes that a malicious site can change the location of a window without your knowledge, so a window you opened to a trusted page may not be showing that page when the message arrives.

// Fixed: delivered only if the opener is still the expected origin
window.opener.postMessage({ accessToken: token }, 'https://app.example.com');

Always name the exact target origin when the data is sensitive. Better still, avoid sending long-lived tokens through postMessage at all: an authorisation code exchanged server-side, or a short-lived token with a narrow scope, limits what an interception is worth.

Finding these in a codebase

Listeners are easy to grep for (addEventListener('message', onmessage =) and tedious to review, because the origin check may live in a helper, a named function, or not exist. Vulkro reports the receiver-side case as POSTMSG-001 (Medium), documented on the postMessage origin validation rule page. It fires on a message handler whose body does no origin validation, and confidence rises to High when the same handler writes the data into a DOM sink. It reads JavaScript and TypeScript files, including .vue and .svelte components, and Vulkro for Salesforce runs the same check on Lightning Web Components and Aura. Severity stays Medium on purpose: which origin should be trusted is a decision only your application can make, so the finding asks the question rather than claiming a proof.

FAQ

How do I validate the origin in a postMessage listener?

Compare event.origin with an exact, hardcoded origin string (or a Set of them) and return early on a mismatch. Then check event.source if you know the sending frame, and validate the shape of event.data before using it.

Is postMessage with targetOrigin "*" safe?

Only for data that is safe for any website to read. With "*", the browser delivers the message to whatever origin the target window currently shows, so tokens, user data and session state must always be sent with an exact target origin.

Can a missing postMessage origin check cause XSS?

Yes. If the listener writes message data into a DOM sink such as innerHTML, location or eval, any page that can post to your window can run script in your origin.

Start a 14-day trial at /start/ to scan your front end for unchecked listeners. Related: Lightning Web Components security and Taint analysis: sources, sinks and sanitizers.