From 22fe3414e1a5b8cf76296a465cd942a4574b83ec Mon Sep 17 00:00:00 2001 From: David Drazic Date: Tue, 7 Mar 2023 09:42:12 +0100 Subject: [PATCH] Add fix for event security (MessageEvent source issue) (#79) * Add fix for event security (MessageEvent source issue) * Refactor (remove ts-expect-error and add assertions) * Refactor (review proposal) --- src/window/WindowPostMessageStream.ts | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/src/window/WindowPostMessageStream.ts b/src/window/WindowPostMessageStream.ts index 7bdff60..76df938 100644 --- a/src/window/WindowPostMessageStream.ts +++ b/src/window/WindowPostMessageStream.ts @@ -1,3 +1,4 @@ +import { assert } from '@metamask/utils'; import { BasePostMessageStream, PostMessageEvent, @@ -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. */ @@ -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); }