Validating postMessage from an iframe you don't control
When your widget is embedded on domains you don't own, the usual event.origin check doesn't work. There is no fixed list of merchant domains to whitelist, and accepting everything means any page can drive your UI. The fi
When your widget is embedded on domains you don't own, the usual event.origin check doesn't work. There is no fixed list of merchant domains to whitelist, and accepting everything means any page can drive your UI. The fix is one line: compare event.source with the contentWindow of the iframe you created.
The handler with no sender check
window.addEventListener('message', function (ev) {
var d = ev.data || {};
if (!d.type) return;
var f = document.getElementById('widget-frame');
if (!f) return;
if (d.type === 'panel_state' && d.open) {
f.style.width = '375px';
f.style.height = '667px';
}
});
Any window that can get a reference to your page can post the same message and change the layout. On a merchant's site that includes every ad and analytics script.
An origin whitelist doesn't survive contact with reality: merchants embed you on their own domain, their staging domain, a page-builder subdomain. You cannot enumerate them.
Compare the source instead
MessageEvent.source is the WindowProxy of the sender. For an iframe you own, it is exactly that iframe's contentWindow โ even cross-origin, even after the iframe navigates.
window.addEventListener('message', function (ev) {
var d = ev.data || {};
if (!d || !d.type) return;
var f = document.getElementById('widget-frame');
if (!f) return;
if (ev.source !== f.contentWindow) return;
if (d.type === 'panel_state' && d.open) {
f.style.width = '375px';
f.style.height = '667px';
}
});
Two details:
-
contentWindowis a live reference and stays stable across iframe reloads. - This does not replace validating the payload. Check
.typeagainst an allowlist and clamp numbers.
The sending side
postMessage with '*' leaks the message to whoever ends up in that window. If the parent is same-origin, name it:
window.parent.postMessage(
{ type: 'payment_paid', source: 'billing' },
window.location.origin
);
If the parent can really be any merchant domain, keep '*' but never put tokens, customer data, or credential-bearing URLs in the payload. The message should be a UI signal, not a data channel.
Checklist
- [ ] Every
messagelistener checksevent.sourceagainst the iframe it owns - [ ]
event.datais treated as untrusted input - [ ] Outbound messages use an explicit
targetOriginwhen known - [ ] No secrets in messages that must use
'*' - [ ] One listener per iframe, not a global one comparing the last-known frame
The whole fix is about ten lines. The hard part is remembering that "we're behind an iframe" doesn't make the parent page a trusted sender.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes โ full credit and traffic to the original publisher.