From b5ce863300927b0b97c67de484a274807ce9a0e8 Mon Sep 17 00:00:00 2001 From: akysil Date: Sat, 28 Nov 2026 22:37:18 +0000 Subject: [PATCH] fix: ignore non-object window messages in isSameOrigin --- api/messaging/src/relay.test.ts | 31 +++++++++++++++++++++++++++++++ api/messaging/src/utils.ts | 2 ++ 2 files changed, 33 insertions(+) diff --git a/api/messaging/src/relay.test.ts b/api/messaging/src/relay.test.ts index 6c4fa9cc5..bfb7be642 100644 --- a/api/messaging/src/relay.test.ts +++ b/api/messaging/src/relay.test.ts @@ -96,6 +96,14 @@ describe("sendViaRelay", () => { sendViaRelay(req, port).then((res) => (response = res)) }) + + test("ignores messages with non-object data", () => { + sendViaRelay(req, port) + + for (const data of [null, undefined, "hello", 42]) { + expect(() => port.postMessage(data)).not.toThrow() + } + }) }) describe("relay", () => { @@ -149,4 +157,27 @@ describe("relay", () => { port.postMessage(mockedReq) }) + + test("ignores messages with non-object data", async () => { + const notCalledHandler = jest.fn((data) => Promise.resolve(data)) + relay(req, notCalledHandler, port) + + const [listener] = Array.from(port.callbacks) + for (const data of [null, undefined, "hello", 42]) { + await expect( + listener({ data, source: globalThis.window }) + ).resolves.toBeUndefined() + } + + expect(notCalledHandler).not.toBeCalled() + }) + + test("ignores primitive data even when the request has no name", () => { + const notCalledHandler = jest.fn((data) => Promise.resolve(data)) + relay({} as PlasmoMessaging.Request, notCalledHandler, port) + + port.postMessage(true) + + expect(notCalledHandler).not.toBeCalled() + }) }) diff --git a/api/messaging/src/utils.ts b/api/messaging/src/utils.ts index 72a50ddc8..25878bb55 100644 --- a/api/messaging/src/utils.ts +++ b/api/messaging/src/utils.ts @@ -36,6 +36,8 @@ export const isSameOrigin = ( ): req is PlasmoMessaging.Request => !req.__internal && event.source === globalThis.window && + typeof event.data === "object" && + event.data !== null && event.data.name === req.name && (req.relayId === undefined || event.data.relayId === req.relayId)