Description
A page with a reference to the receiving window can send it a postMessage event. Without an event.origin check, a handler may accept untrusted data, execute it with eval, or use it for a privileged operation.
Potential impact
An untrusted message may expose data through the DOM, console or a reply, or cause the handler to run code or change state with the user's permissions. Large message volumes can also overwhelm the browser's event queue.
Remediation
- Compare
event.originto an exact trusted scheme, host and port. Partial matches withstartsWithorincludesare insufficient. If only one sender is allowed, require its window reference, such asiframe.contentWindow, and compare it withevent.source. - Parse
event.dataand check its type, fields and values before acting. Return immediately if validation fails. Never execute message data withevalornew Function. - When sending a sensitive message or reply, use the exact trusted
targetOrigin.
Examples
Before
javascript
// No origin validation before sensitive operations
window.addEventListener("message", (e) => {
// Trust delivered messages without checking the sending window
if (e.data && e.data.type === "setTheme") {
document.documentElement.setAttribute("data-theme", e.data.value);
}
// Dangerous: execute received data
if (e.data && e.data.exec) {
eval(e.data.exec); // An attacker may execute arbitrary code
}
// Set or transmit sensitive data such as tokens
if (e.data && e.data.accessToken) {
localStorage.setItem("access_token", e.data.accessToken);
}
});
After
javascript
// Validate origin, expected source and data schema
(() => {
const ALLOWED_ORIGINS = new Set([
"https://app.example.com",
"https://admin.example.com",
]);
// Retain a reference when the expected sender window is known
const settingsFrame = document.getElementById("settings-frame");
const expectedSource = settingsFrame ? settingsFrame.contentWindow : null;
function isValidPayload(payload) {
// Minimal schema check: require an object and an allowed message type
if (!payload || typeof payload !== "object") return false;
const allowedTypes = new Set(["setTheme", "ping"]);
return typeof payload.type === "string" && allowedTypes.has(payload.type);
}
window.addEventListener("message", (event) => {
// 1) Require an exact origin match
if (!ALLOWED_ORIGINS.has(event.origin)) return;
// 2) Check the sender window when its reference is available
if (expectedSource && event.source !== expectedSource) return;
// 3) Validate and process the data
const data =
typeof event.data === "string"
? (() => {
try {
return JSON.parse(event.data);
} catch {
return null;
}
})()
: event.data;
if (!isValidPayload(data)) return;
switch (data.type) {
case "setTheme":
if (
typeof data.value === "string" &&
/^(light|dark)$/.test(data.value)
) {
document.documentElement.setAttribute("data-theme", data.value);
}
break;
case "ping":
// Reply with the exact validated targetOrigin
event.source &&
event.source.postMessage(
JSON.stringify({ type: "pong" }),
event.origin
);
break;
default:
// no-op
break;
}
});
})();
The handler checks the origin and, when the settings frame is available, its window. It accepts light or dark for setTheme and replies to ping at the validated origin. If only the settings frame may send messages, also reject them when its reference is missing.