When do I need to check the origin property on events that implement the MessageEvent interface in order to avoid security vulnerabilities?
The origin attribute must return the value it was initialized to. It represents, in server-sent events and cross-document messaging, the origin of the document that sent the message (typically the scheme, hostname, and port of the document, but not its path or fragment).
This property is exposed by server-sent events, Web sockets, cross-document messaging, channel messaging, and broadcast channels.
What should I know? What do I need to beware of? What should I keep in mind?
What scenarios would it make sense to check the origin property?
Do I even need to check origin at all, or just the isTrusted property?
var websocket = new WebSocket('ws://echo.websocket.org/');
websocket.onmessage = function(e) {
// Can I trust this event?
// Do I need to check e.origin?
};
Best practise: always.
Whenever you are communicating with some other party, that party might be hostile. Depending on what the communication is about, that can be a security issue, especially if you a) share data b) act on requests - which is pretty much always.
The point is that any party can try to initiate communication with you, and even if you initiated it, in the case of cross-document messaging (frames, tabs etc) and channels your counterpart may change (by navigation, by forwarding). You should explicitly check whom you are communicating with and whether you want that.
To cite MDN on
postMessage:No, the
isTrustedproperty does something entirely different. Also, the browser cannot know which domains you trust and which not, especially when you want to do cross-origin messaging.