Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions src/CortiEmbedded.ts
Original file line number Diff line number Diff line change
Expand Up @@ -699,12 +699,15 @@ export class CortiEmbedded extends LitElement implements CortiEmbeddedAPI {
}

try {
const response = await this.postMessageHandler.postMessage({
type: "CORTI_EMBEDDED",
version: "v1",
action: "showDeviceLinkQR",
payload,
});
const response = await this.postMessageHandler.postMessage(
{
type: "CORTI_EMBEDDED",
version: "v1",
action: "showDeviceLinkQR",
payload,
},
null,
);

if (response.success && response.payload) {
return response.payload as ShowDeviceLinkQRResponse;
Expand Down
26 changes: 17 additions & 9 deletions src/utils/PostMessageHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,9 @@ export class PostMessageHandler {
window.removeEventListener("message", this.messageListener);
this.messageListener = null;
}
for (const pendingRequest of this.pendingRequests.values()) {
pendingRequest.reject({ message: "PostMessageHandler destroyed" });
}
this.pendingRequests.clear();
}

Expand Down Expand Up @@ -257,11 +260,11 @@ export class PostMessageHandler {
/**
* Sends a postMessage to the iframe and returns a Promise that resolves with the response.
* @param message - The message to send
* @param timeout - Optional timeout in milliseconds. Defaults to the requestTimeout set at construction.
* @param timeout - Optional timeout in milliseconds. Defaults to the requestTimeout set at construction. Pass null to disable the timeout.
*/
async postMessage(
message: Omit<EmbeddedRequest, "requestId">,
timeout?: number,
timeout?: number | null,
): Promise<EmbeddedResponse> {
if (!this.iframe.contentWindow) {
throw new Error("Iframe not ready");
Expand All @@ -272,21 +275,25 @@ export class PostMessageHandler {

const { contentWindow } = this.iframe;
const requestId = PostMessageHandler.generateRequestId();
const effectiveTimeout = timeout ?? this.requestTimeout;
const effectiveTimeout =
timeout === undefined ? this.requestTimeout : timeout;

return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
this.pendingRequests.delete(requestId);
reject(new Error("Request timeout"));
}, effectiveTimeout);
const timeoutId =
effectiveTimeout === null
? null
: setTimeout(() => {
this.pendingRequests.delete(requestId);
Comment thread
barklund marked this conversation as resolved.
reject(new Error("Request timeout"));
}, effectiveTimeout);

this.pendingRequests.set(requestId, {
resolve: value => {
clearTimeout(timeoutId);
if (timeoutId !== null) clearTimeout(timeoutId);
resolve(value);
},
reject: reason => {
clearTimeout(timeoutId);
if (timeoutId !== null) clearTimeout(timeoutId);
reject(reason);
},
});
Expand All @@ -299,6 +306,7 @@ export class PostMessageHandler {
const targetOrigin = this.getTrustedOrigin();
if (!targetOrigin) {
this.pendingRequests.delete(requestId);
if (timeoutId !== null) clearTimeout(timeoutId);
reject(new Error("Cannot determine trusted origin for postMessage"));
return;
}
Expand Down
28 changes: 28 additions & 0 deletions test/corti-embedded.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -499,6 +499,34 @@ describe("CortiEmbedded", () => {
// Note: configure method would normally change baseURL, but our mock doesn't handle that
});

it("exempts showDeviceLinkQR from the default postMessage timeout", async () => {
const el = await fixture<CortiEmbedded>(
html`<corti-embedded baseurl=${validBaseURL}></corti-embedded>`,
);
const messages: Array<{ action: string; timeout?: number | null }> = [];

(el as any).postMessageHandler = {
postMessage: async (msg: { action: string }, timeout?: number | null) => {
messages.push({ action: msg.action, timeout });
return { success: true, payload: { status: "approved" } };
},
destroy: () => {},
ready: true,
};

const result = await el.showDeviceLinkQR({
access_token: "access-token",
expires_in: 300,
refresh_token: "refresh-token",
token_type: "Bearer",
});

expect(result).to.deep.equal({ status: "approved" });
expect(messages).to.deep.equal([
{ action: "showDeviceLinkQR", timeout: null },
]);
});

it("normalizes legacy string navigate input before forwarding", async () => {
const el = await fixture<CortiEmbedded>(
html`<corti-embedded baseurl=${validBaseURL}></corti-embedded>`,
Expand Down
67 changes: 67 additions & 0 deletions test/post-message-handler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,73 @@ describe("PostMessageHandler", () => {
}
});

it("does not time out when timeout is disabled", async () => {
const { handler, iframe, origin } = makeRealHandler();
(handler as any).isReady = true;
const origGen = (PostMessageHandler as any).generateRequestId;
(PostMessageHandler as any).generateRequestId = () => "req_test";
try {
const promise = handler.postMessage(
{
type: "CORTI_EMBEDDED",
version: "v1",
action: "showDeviceLinkQR",
payload: {},
},
null,
);

await new Promise(resolve => setTimeout(resolve, 60));

window.dispatchEvent(
new MessageEvent("message", {
data: {
type: "CORTI_EMBEDDED_RESPONSE",
action: "showDeviceLinkQR",
requestId: "req_test",
success: true,
payload: { status: "approved" },
},
origin,
source: iframe.contentWindow as any,
}),
);

const response = await promise;
expect(response.payload).to.deep.equal({ status: "approved" });
} finally {
(PostMessageHandler as any).generateRequestId = origGen;
handler.destroy();
iframe.remove();
}
});

it("rejects pending requests when destroyed", async () => {
const { handler, iframe } = makeRealHandler();
(handler as any).isReady = true;
const promise = handler.postMessage(
{
type: "CORTI_EMBEDDED",
version: "v1",
action: "showDeviceLinkQR",
payload: {},
},
null,
);

await new Promise(resolve => setTimeout(resolve, 0));
handler.destroy();

try {
await promise;
expect.fail("Expected pending request to reject on destroy");
} catch (e: any) {
expect(e.message).to.equal("PostMessageHandler destroyed");
} finally {
iframe.remove();
}
});

it("throws if iframe contentWindow not available", async () => {
const fakeIframe: any = {
getAttribute: (n: string) =>
Expand Down
Loading