Skip to content

Commit 48a5149

Browse files
committed
Fix TypeError for non-string action values in postMessage handler
Address code review feedback: - Add typeof check to reject non-string action values early - Use startsWith() safely after confirming action is a string - Add test cases for action as object, number, and array
1 parent 2898b3f commit 48a5149

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

src/services/WebExtensionService.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,8 @@ export default class WebExtensionService {
4444
}
4545

4646
private receive(event: { data: ExtensionResponse }): void {
47-
if (!event.data?.action?.startsWith("web-eid:")) return;
47+
if (typeof event.data?.action !== "string") return;
48+
if (!event.data.action.startsWith("web-eid:")) return;
4849

4950
const message = event.data;
5051
const suffix = ["success", "failure", "ack"].find((s) => message.action.endsWith(s));

src/services/__tests__/WebExtensionService-test.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,42 @@ describe("WebExtensionService", () => {
6262

6363
expect(console.warn).not.toHaveBeenCalled();
6464
});
65+
66+
it("should ignore messages with action as an object", async () => {
67+
jest.spyOn(console, "warn").mockImplementation();
68+
69+
window.postMessage({ action: { id: "123", _t: "456" } }, "*");
70+
await new Promise((resolve) => setTimeout(resolve));
71+
72+
expect(console.warn).not.toHaveBeenCalled();
73+
});
74+
75+
it("should ignore messages with action as an object with startsWith property", async () => {
76+
jest.spyOn(console, "warn").mockImplementation();
77+
78+
window.postMessage({ action: { startsWith: "2022-10-12", endsWith: "2026-10-12" } }, "*");
79+
await new Promise((resolve) => setTimeout(resolve));
80+
81+
expect(console.warn).not.toHaveBeenCalled();
82+
});
83+
84+
it("should ignore messages with action as a number", async () => {
85+
jest.spyOn(console, "warn").mockImplementation();
86+
87+
window.postMessage({ action: 12345 }, "*");
88+
await new Promise((resolve) => setTimeout(resolve));
89+
90+
expect(console.warn).not.toHaveBeenCalled();
91+
});
92+
93+
it("should ignore messages with action as an array", async () => {
94+
jest.spyOn(console, "warn").mockImplementation();
95+
96+
window.postMessage({ action: ["web-eid:test"] }, "*");
97+
await new Promise((resolve) => setTimeout(resolve));
98+
99+
expect(console.warn).not.toHaveBeenCalled();
100+
});
65101
});
66102

67103
describe("action web-eid:warning", () => {

0 commit comments

Comments
 (0)