Skip to content

Commit

Permalink
Add fix for event security (MessageEvent source issue) (#79)
Browse files Browse the repository at this point in the history
* Add fix for event security (MessageEvent source issue)

* Refactor (remove ts-expect-error and add assertions)

* Refactor (review proposal)
  • Loading branch information
david0xd authored Mar 7, 2023
1 parent 799dba7 commit 22fe341
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions src/window/WindowPostMessageStream.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { assert } from '@metamask/utils';
import {
BasePostMessageStream,
PostMessageEvent,
Expand All @@ -11,6 +12,20 @@ interface WindowPostMessageStreamArgs {
targetWindow?: Window;
}

/* istanbul ignore next */
const getSource = Object.getOwnPropertyDescriptor(
MessageEvent.prototype,
'source',
)?.get;
assert(getSource, 'MessageEvent.prototype.source getter is not defined.');

/* istanbul ignore next */
const getOrigin = Object.getOwnPropertyDescriptor(
MessageEvent.prototype,
'origin',
)?.get;
assert(getOrigin, 'MessageEvent.prototype.origin getter is not defined.');

/**
* A {@link Window.postMessage} stream.
*/
Expand Down Expand Up @@ -77,14 +92,17 @@ export class WindowPostMessageStream extends BasePostMessageStream {
private _onMessage(event: PostMessageEvent): void {
const message = event.data;

/* eslint-disable @typescript-eslint/no-non-null-assertion */
if (
(this._targetOrigin !== '*' && event.origin !== this._targetOrigin) ||
event.source !== this._targetWindow ||
(this._targetOrigin !== '*' &&
getOrigin!.call(event) !== this._targetOrigin) ||
getSource!.call(event) !== this._targetWindow ||
!isValidStreamMessage(message) ||
message.target !== this._name
) {
return;
}
/* eslint-enable @typescript-eslint/no-non-null-assertion */

this._onData(message.data);
}
Expand Down

0 comments on commit 22fe341

Please sign in to comment.