JavaScript

JavaScript

Made by DeepSource

Missing target origin in cross-origin communication JS-S1014

Security
Critical
a07 cwe-20 sans top 25 owasp top 10

The window.postMessage function is used for cross-origin communication between two entities. An "entity" here can be a page, an iframe, or a pop-up spawned by a page. It is recommended to always have an explicit targetOrigin parameter when using window.postMessage. This allows the message to be sent only to trusted receivers - those that have the required URI.

When sharing a password for example, it is critical that the password only be sent to the intended receiver, and not some malicious third party.

const password = getPassword()
window.postMessage(password, "https://safe.site.com")

If you have no preference for the origin of a window for a message to be dispatched, you can use *:

window.postMessage(data, "*")

Bad Practice

// send a message from a pop-up:
const popup = window.open(/* popup data */)

// INSECURE: The message can be received by any window that is currently active
// below the pop-up.
popup.postMessage("secret message for the parent")

Recommended

// send a message from a pop-up:
const popup = window.open(/* popup data */)

// SAFE: The message can only be received by example.com 
popup.postMessage("secret message for the parent", "https://www.example.com")

References