From 76f10fc0549d041dcd01468949df44948c50a423 Mon Sep 17 00:00:00 2001 From: Ed Eykholt Date: Fri, 3 Jan 2025 19:37:29 -0800 Subject: [PATCH] Overhaul of ContentScript. CsSwPort. Message Types. --- .../wwwroot/scripts/es6/ExCsInterfaces.ts | 24 +- .../wwwroot/scripts/es6/SwAppInterop.ts | 32 +-- .../wwwroot/scripts/esbuild/ContentScript.ts | 246 ++++++++++-------- .../wwwroot/scripts/esbuild/service-worker.ts | 37 +-- 4 files changed, 175 insertions(+), 164 deletions(-) diff --git a/KeriAuth.BrowserExtension/wwwroot/scripts/es6/ExCsInterfaces.ts b/KeriAuth.BrowserExtension/wwwroot/scripts/es6/ExCsInterfaces.ts index dfa35cc..ab21bec 100644 --- a/KeriAuth.BrowserExtension/wwwroot/scripts/es6/ExCsInterfaces.ts +++ b/KeriAuth.BrowserExtension/wwwroot/scripts/es6/ExCsInterfaces.ts @@ -9,7 +9,7 @@ export interface ICsSwMsg { } // Message types from Page to CS, which may be then forwarded to the extension service-worker. Aka "EVENT_TYPE" in the polaris-web code." -export enum CsSwMsgType { +export enum CsSwMsgEnum { POLARIS_SIGNIFY_EXTENSION = "signify-extension", POLARIS_SIGNIFY_EXTENSION_CLIENT = "signify-extension-client", POLARIS_CONFIGURE_VENDOR = "/signify/configure-vendor", @@ -21,27 +21,27 @@ export enum CsSwMsgType { POLARIS_GET_SESSION_INFO = "/signify/get-session-info", POLARIS_CLEAR_SESSION = "/signify/clear-session", POLARIS_CREATE_DATA_ATTESTATION = "/signify/credential/create/data-attestation", - POLARIS_GET_CREDENTIAL = "/signify/credential/get" + POLARIS_GET_CREDENTIAL = "/signify/credential/get", + PING = "ping" } // Message types from Extension to CS (and typically forward to Page and sometimes of type FooResponse) export interface ISwCsMsg { - type: string // SwCsMsgType + type: string // SwCsMsgEnum // TODO P2 typof SwCsMsgEnum ? requestId?: string // response to this requestId payload?: object error?: string } -export enum SwCsMsgType { - HELLO = "hello", +export enum SwCsMsgEnum { + PONG = "pong", CANCELED = "canceled", REPLY = "/signify/reply", - FSW = "fromServiceWorker", - // SE = "signify-extension" + FSW = "fromServiceWorker" } -export interface IExCsMsgHello extends ISwCsMsg { - type: SwCsMsgType.HELLO +export interface ISwCsMsgPong extends ISwCsMsg { + type: SwCsMsgEnum.PONG } // This IIdentifier is used in the context of responses from the extension service-worker, CS, to page @@ -89,11 +89,11 @@ export interface ReplyMessageData { source?: string; } -export const CsToPageMsgIndicator = "KeriAuthCs"; +export const CsTabMsgTag = "KeriAuthCs"; // This interface helps shape ContentScript messages to tab -export interface KeriAuthToPolarisMessageData extends Polaris.MessageData { - source: typeof CsToPageMsgIndicator; +export interface CsTabMsgData extends Polaris.MessageData { + source: typeof CsTabMsgTag; } // Signing related types from signify-browser-extension config/types.ts. Here because we don't want dependencies on signify-browser-extension, diff --git a/KeriAuth.BrowserExtension/wwwroot/scripts/es6/SwAppInterop.ts b/KeriAuth.BrowserExtension/wwwroot/scripts/es6/SwAppInterop.ts index c9fb22b..0025294 100644 --- a/KeriAuth.BrowserExtension/wwwroot/scripts/es6/SwAppInterop.ts +++ b/KeriAuth.BrowserExtension/wwwroot/scripts/es6/SwAppInterop.ts @@ -1,29 +1,9 @@ /// -import { - AuthorizeResultCredential, - AuthorizeArgs, - AuthorizeResultIdentifier, - AuthorizeResult, - SignDataArgs, - SignDataResultItem, - SignDataResult, - SignRequestArgs, - SignRequestResult, - ConfigureVendorArgs, - MessageData -} from "../types/polaris-web-client" +import * as PW from "../types/polaris-web-client" import { - CsSwMsgType, - IExCsMsgHello, - SwCsMsgType, - ISwCsMsg, - ICsSwMsg, - CsToPageMsgIndicator, - KeriAuthToPolarisMessageData, - ISignin, - ICredential, + SwCsMsgEnum, ReplyMessageData, ApprovedSignRequest } from "../es6/ExCsInterfaces.js"; @@ -47,7 +27,7 @@ export const SwAppInteropModule = { port.onMessage.addListener((message) => { console.log("SwAppInterop received port message: ", message); // TODO P2 message types fromApp vs fromServiceWorker? - if (message && message.type === SwCsMsgType.FSW) { + if (message && message.type === SwCsMsgEnum.FSW) { dotNetObjectReference.invokeMethodAsync('ReceiveMessage', message.data); } }); @@ -71,12 +51,12 @@ export const SwAppInteropModule = { switch (payloadTypeName) { case "CancelResult": // TODO P2 AuthorizeResult type is the closest match to CancelResult at the moment. - const msgCancelResult = JSON.parse(jsonReplyMessageData) as ReplyMessageData; + const msgCancelResult = JSON.parse(jsonReplyMessageData) as ReplyMessageData; console.log("SwAppInteropModule.sendMessageToServiceWorker messageData3: ", msgCancelResult); port.postMessage(msgCancelResult); break; case "AuthorizeResult": - const msgAuthorizeResult = JSON.parse(jsonReplyMessageData) as ReplyMessageData; + const msgAuthorizeResult = JSON.parse(jsonReplyMessageData) as ReplyMessageData; console.log("SwAppInteropModule.sendMessageToServiceWorker messageData2: ", msgAuthorizeResult); port.postMessage(msgAuthorizeResult); break; @@ -86,7 +66,7 @@ export const SwAppInteropModule = { port.postMessage(msgApprovedSignRequest); break; case "SignedRequestResult": - const msgSignRequestResult = JSON.parse(jsonReplyMessageData) as ReplyMessageData; + const msgSignRequestResult = JSON.parse(jsonReplyMessageData) as ReplyMessageData; console.log("SwAppInteropModule.sendMessageToServiceWorker messageData5: ", msgSignRequestResult); port.postMessage(msgSignRequestResult); break; diff --git a/KeriAuth.BrowserExtension/wwwroot/scripts/esbuild/ContentScript.ts b/KeriAuth.BrowserExtension/wwwroot/scripts/esbuild/ContentScript.ts index fc86c70..3af32c7 100644 --- a/KeriAuth.BrowserExtension/wwwroot/scripts/esbuild/ContentScript.ts +++ b/KeriAuth.BrowserExtension/wwwroot/scripts/esbuild/ContentScript.ts @@ -13,74 +13,93 @@ interface EventData { } import { - CsSwMsgType, - IExCsMsgHello, - SwCsMsgType, - ISwCsMsg, + CsSwMsgEnum, + SwCsMsgEnum, ICsSwMsg, - CsToPageMsgIndicator, - ISignin, - ICredential, - KeriAuthToPolarisMessageData + CsTabMsgTag, + CsTabMsgData } from "../es6/ExCsInterfaces.js"; -import * as PolarisWeb from "../types/polaris-web-client"; +import * as PW from "../types/polaris-web-client"; + +/* + * This section is evaluated on document-start, as specified in the extension manifest + */ + +// TODO P2 clarify naming consistency and use of: tab, page (including DOM and properties), document (high-level properties), and DOM + +// Unique port name for communications between the content script and the extension +let uniquePortName: string; +let portWithSw: chrome.runtime.Port | null; + +// Add a listener for messages and create port with SW +console.info("CS adding message listener and creating port with SW"); +window.addEventListener("message", (event: MessageEvent) => handleWindowMessage(event)); +createPortWithSw(); + +// Observe URL changes in an SPA.Just log it for now to help with debugging issues. +window.addEventListener('popstate', () => { + console.info("CS popstate change:", window.location.href); +}); + +// Add listener for when DOMContentLoaded +document.addEventListener('DOMContentLoaded', (event) => { + console.info(`CS ${event.type} ${window.location.href}`); +}); + /* * Generate a unique and unguessable identifier for the port name for communications between the content script and the extension */ function generateUniqueIdentifier(): string { const array = new Uint32Array(4); - window.crypto.getRandomValues(array); // TODO P4 consider randumUUID() instead + // TODO P4 consider randumUUID() instead + window.crypto.getRandomValues(array); return Array.from(array, dec => ('00000000' + dec.toString(16)).slice(-8)).join('-'); } -// Create the unique port name for communications between the content script and the extension -const uniquePortName: string = generateUniqueIdentifier(); - /* * */ function postMessageToPage(msg: T): void { - console.log("KeriAuthCs to tab:", (msg as PolarisWeb.MessageData).type, msg); + console.log("KeriAuthCs to tab:", (msg as CsTabMsgData).type, msg); window.postMessage(msg, currentOrigin); } /* - * Handle messages from the extension + * Handle messages from SW */ -function handleMessageFromServiceWorker(message: PolarisWeb.MessageData): void { +function handleMsgFromSW(message: PW.MessageData): void { if (!message.type) { - console.error("KeriAuthCs from Sw: type not found in message:", message); + console.error("KeriAuthCs from SW: type not found in message:", message); return; } - console.info(`KeriAuthCs from Sw: ${message.type}`, message); + console.info(`KeriAuthCs from SW: ${message.type}`, message); switch (message.type) { - case SwCsMsgType.HELLO: // TODO P0 Pong - window.addEventListener("message", (event: MessageEvent) => handleWindowMessage(event)); + case SwCsMsgEnum.PONG: break; - case SwCsMsgType.REPLY: - const msg: KeriAuthToPolarisMessageData = { - source: CsToPageMsgIndicator, + + case SwCsMsgEnum.REPLY: + const msg: CsTabMsgData = { + source: CsTabMsgTag, type: message.type, requestId: message.requestId, payload: message.payload, error: message.error, } - postMessageToPage>(msg); + postMessageToPage>(msg); break; - case SwCsMsgType.CANCELED: - const msg2: KeriAuthToPolarisMessageData = { - source: CsToPageMsgIndicator, + case SwCsMsgEnum.CANCELED: + const msg2: CsTabMsgData = { + source: CsTabMsgTag, type: message.type, requestId: message.requestId, payload: null, error: "KERI Auth: User canceled or operation timed out.", } - postMessageToPage>(msg2); - + postMessageToPage>(msg2); break; default: @@ -89,18 +108,19 @@ function handleMessageFromServiceWorker(message: PolarisWeb.MessageData } } -let portWithSw: chrome.runtime.Port; + /* * */ -function createPortWithSw(withHandshake: boolean): void { - console.log(`KeriAuthCs to SW: (re-)creating port`); +function createPortWithSw(): void { + console.log(`KeriAuthCs to SW: creating port`); + uniquePortName = generateUniqueIdentifier(); portWithSw = chrome.runtime.connect({ name: uniquePortName }); console.log("KeriAuthCs to SW connected port:", portWithSw); // register to receive and handle messages from the extension (and indirectly also from the web page) - portWithSw.onMessage.addListener((message: PolarisWeb.MessageData) => handleMessageFromServiceWorker(message)); + portWithSw.onMessage.addListener((message: PW.MessageData) => handleMsgFromSW(message)); portWithSw.onDisconnect.addListener((p) => { // disconnect will typically happen when the service-worker becomes inactive @@ -108,76 +128,107 @@ function createPortWithSw(withHandshake: boolean): void { portWithSw = null; }); - if (withHandshake) { - // Send a hello message to the service worker (versus waiting on a triggering message from the page) - // TODO P3 use a constructor for the message object - const helloMsg: ICsSwMsg = { type: CsSwMsgType.POLARIS_SIGNIFY_EXTENSION }; // TODO P0 Ping to set up connections - console.log("KeriAuthCs to SW:", helloMsg); - portWithSw.postMessage(helloMsg); - // Delay call of advertiseToPage so that polaris-web module to be loaded and ready to receive the message. - // TODO P3 hack - find a more deterministic approach vs delay? - // setTimeout(advertiseToPage, 500); - } + // Send a ping message to the service worker to help complete the setup of connection port + const pingMsg: ICsSwMsg = { type: CsSwMsgEnum.PING }; + console.log("KeriAuthCs to SW Ping:", pingMsg); + portWithSw.postMessage(pingMsg); } /* - * + * Assure port with SW exists, then postMessage */ -document.addEventListener('DOMContentLoaded', (event) => { - console.info("CS DOMContentLoaded"); - window.addEventListener("message", (event: MessageEvent) => handleWindowMessage(event)); - createPortWithSw(true); - return; -}); +function assurePortAndSend(msg: any) { + if (portWithSw === null) { + console.info(`KeriAuthCs re-createPortWithCs()`); + createPortWithSw(); + } + console.info(`KeriAuthCs to SW postMessage:`, msg); + portWithSw.postMessage(msg); +} /* -// Handle messages from the page -*/ + * Handle messages from the page + */ function handleWindowMessage(event: MessageEvent) { - // Check if the payload is sent from the current window and is safe to process - if (window.location.href.indexOf(event.origin) !== 0 && event.source !== window) { - // Reject likely malicious messages, such as those that might be sent by a malicious extension (Cross-Extension Communication). - // set at info level because its not unusal for the ContentScript to be injected into an unsupported page - console.warn('KeriAuthCs from tab: ignoring potentially malicious message event:', event.data); + + if (event === undefined) { return; } - // Ignore messages from Cs intended for the Page - if (event.data.source == CsToPageMsgIndicator) { - // console.log("KeriAuthCs ignoring message from source, event: ", event.data.source, event); + // Ignore messages not sent from current window + if (window.location.href.indexOf(event.origin) !== 0 && event.source !== window) { + // console.info('KeriAuthCs from tab: ignoring message event from other window:', event.data); return; } - console.log("KeriAuthCs from tab: ", event.data.type, event.data); + // Ignore messages from Cs sent to the Tab (instead of from Tab) + if (event.data.source == CsTabMsgTag) { + // console.info("KeriAuthCs ignoring message from source, event data: ", event.data); + return; + } + // handle messages from current tab + console.info(`KeriAuthCs from tab:`, event.data.type, event.data,); try { - const requestId = (event.data as PolarisWeb.MessageData).requestId; + const requestId = (event.data as PW.MessageData).requestId; switch (event.data.type) { - case CsSwMsgType.POLARIS_SIGNIFY_EXTENSION: - case CsSwMsgType.POLARIS_SIGNIFY_EXTENSION_CLIENT: + case CsSwMsgEnum.POLARIS_SIGNIFY_EXTENSION_CLIENT: + const extensionMessage2: any = { + source: CsTabMsgTag, + type: CsSwMsgEnum.POLARIS_SIGNIFY_EXTENSION, + data: { extensionId: chrome.runtime.id }, + requestId: requestId + } + postMessageToPage(extensionMessage2); + break; + + case CsSwMsgEnum.POLARIS_SIGNIFY_EXTENSION: const extensionMessage: any = { - source: CsToPageMsgIndicator, - type: CsSwMsgType.POLARIS_SIGNIFY_EXTENSION, + source: CsTabMsgTag, + type: CsSwMsgEnum.POLARIS_SIGNIFY_EXTENSION, data: { extensionId: chrome.runtime.id }, requestId: requestId } postMessageToPage(extensionMessage); break; - case CsSwMsgType.POLARIS_CONFIGURE_VENDOR: - const configureVendorArgsMessage = event.data.payload as PolarisWeb.MessageData; + case CsSwMsgEnum.POLARIS_GET_SESSION_INFO: + const authorizeArgsMessage2 = event.data as PW.MessageData; + const authorizeResult: PW.AuthorizeResult = {}; + // TODO P2 implement sessions? + const msg: CsTabMsgData = { + source: CsTabMsgTag, + type: SwCsMsgEnum.REPLY, + requestId: requestId, + error: "KERIAuthCs: sessions not supported", // note that including error string appears to be processed as null in polaris-web + }; + postMessageToPage>(msg); + break; + + case CsSwMsgEnum.POLARIS_CONFIGURE_VENDOR: + const configureVendorArgsMessage = event.data.payload as PW.MessageData; console.info(`KeriAuthCs: ${event.data.type} not implemented`, configureVendorArgsMessage); + const msg3: CsTabMsgData = { + source: CsTabMsgTag, + type: SwCsMsgEnum.REPLY, + requestId: requestId, + // TODO P2 the type definition doesn't appear to handled what may used in signify-browser-extension, e.g.: + // error: { code: 503, message: error?.message }, + error: "KERIAuthCs: configure-vendor not supported", // note that including error string appears to be processed as null in polaris-web + }; + postMessageToPage>(msg3); break; - case CsSwMsgType.POLARIS_SIGNIFY_AUTHORIZE: - case CsSwMsgType.POLARIS_SELECT_AUTHORIZE_CREDENTIAL: - case CsSwMsgType.POLARIS_SELECT_AUTHORIZE_AID: - case CsSwMsgType.POLARIS_SIGN_REQUEST: + case CsSwMsgEnum.POLARIS_SIGNIFY_AUTHORIZE: + case CsSwMsgEnum.POLARIS_SELECT_AUTHORIZE_CREDENTIAL: + case CsSwMsgEnum.POLARIS_SELECT_AUTHORIZE_AID: + case CsSwMsgEnum.POLARIS_SIGN_REQUEST: try { - const authorizeRequestMessage = event.data as PolarisWeb.MessageData; + const authorizeRequestMessage = event.data as PW.MessageData; console.info(`KeriAuthCs: ${authorizeRequestMessage.type}:`, authorizeRequestMessage); - // TODO this could be simplified with the correct type above? + // TODO P2 this could be simplified with the correct type above? + // only relevant for POLARIS_SIGN_REQUEST ? if (event.data.payload?.headers) { console.log("KeriAuthCs from tab payload headers: "); const hs: Headers = event.data.payload?.headers; @@ -185,57 +236,36 @@ function handleWindowMessage(event: MessageEvent) { console.log(` ${pair[0]}: ${pair[1]}`); } } - console.log(`KeriAuthCs to SW:`, event.data); - - // since the portWithSw may have disconnected when the service-worker transitioned to inactive state, we may need to recreate it here - if (portWithSw === null) { - createPortWithSw(true); - } - portWithSw.postMessage(event.data); - + assurePortAndSend(event.data); } catch (error) { console.error("KeriAuthCs to SW: error sending message {event.data} {e}:", event.data, error); return; } break; - case CsSwMsgType.POLARIS_GET_SESSION_INFO: - const authorizeArgsMessage2 = event.data as PolarisWeb.MessageData; - - // TODO P2 implement sessions? - const msg: KeriAuthToPolarisMessageData = { - source: CsToPageMsgIndicator, - type: SwCsMsgType.REPLY, - requestId: requestId, - // source: CsToPageMsgIndicator, - error: "KERIAuthCs: sessions not supported", - }; - postMessageToPage>(msg); - break; - - case CsSwMsgType.POLARIS_CLEAR_SESSION: - const authorizeArgsMessage3 = event.data as PolarisWeb.MessageData; - // TODO P3 although sessions are not implemented, we can respond as expected when Clear is requested - const clearResult: KeriAuthToPolarisMessageData = { - source: CsToPageMsgIndicator, - type: "tab", + case CsSwMsgEnum.POLARIS_CLEAR_SESSION: + const authorizeArgsMessage3 = event.data as PW.MessageData; + // Although sessions are not implemented, we can respond as expected when Clear is requested + const clearResult: CsTabMsgData = { + source: CsTabMsgTag, + type: SwCsMsgEnum.REPLY, // type: "tab", requestId: requestId, payload: null } - postMessageToPage>(clearResult); + postMessageToPage>(clearResult); break; - case CsSwMsgType.POLARIS_CREATE_DATA_ATTESTATION: - const createDataAttestationMessage = event.data as PolarisWeb.MessageData; + case CsSwMsgEnum.POLARIS_CREATE_DATA_ATTESTATION: + const createDataAttestationMessage = event.data as PW.MessageData; console.info("KeriAuthCs: handler not implemented for:", event.data.type, createDataAttestationMessage); break; - case CsSwMsgType.POLARIS_GET_CREDENTIAL: + case CsSwMsgEnum.POLARIS_GET_CREDENTIAL: console.info("KeriAuthCs: handler not implemented for:", event.data.type, event.data); break; - case CsSwMsgType.POLARIS_SIGN_DATA: - const signDataArgsMsg = event.data as PolarisWeb.MessageData; + case CsSwMsgEnum.POLARIS_SIGN_DATA: + const signDataArgsMsg = event.data as PW.MessageData; console.info("KeriAuthCs: handler not implemented for:", signDataArgsMsg.type, signDataArgsMsg); break; diff --git a/KeriAuth.BrowserExtension/wwwroot/scripts/esbuild/service-worker.ts b/KeriAuth.BrowserExtension/wwwroot/scripts/esbuild/service-worker.ts index 94ddbde..5f51aa4 100644 --- a/KeriAuth.BrowserExtension/wwwroot/scripts/esbuild/service-worker.ts +++ b/KeriAuth.BrowserExtension/wwwroot/scripts/esbuild/service-worker.ts @@ -9,7 +9,7 @@ // import MessageSender = chrome.runtime.MessageSender; import { Utils } from "../es6/uiHelper.js"; -import { CsSwMsgType, IExCsMsgHello, SwCsMsgType } from "../es6/ExCsInterfaces.js"; +import { CsSwMsgEnum, ISwCsMsgPong, SwCsMsgEnum } from "../es6/ExCsInterfaces.js"; import { ICsSwMsg } from "../es6/ExCsInterfaces.js"; import { connect, getSignedHeaders, getNameByPrefix, getIdentifierByPrefix } from "./signify_ts_shim.js"; // import { decode } from '@cbor'; @@ -420,7 +420,7 @@ chrome.runtime.onConnect.addListener(async (connectedPort: chrome.runtime.Port) // First check if the port is from a content script and its pattern const cSPortNamePattern = /^[0-9a-f]{8}-[0-9a-f]{8}-[0-9a-f]{8}-[0-9a-f]{8}$/; if (cSPortNamePattern.test(connectedPort.name)) { - const cSPort: chrome.runtime.Port = connectedPort; + const cSPort: chrome.runtime.Port | null = connectedPort; // TODO P2 test and update assumptions of having a longrunning port established, especially when sending. With back-forward cache (bfcache), ports can get suspended or terminated, leading to errors such as: // "Unchecked runtime.lastError: The page keeping the extension port is moved into back/forward cache, so the msg channel is closed." console.log(`SW with CS via port`, cSPort); @@ -459,7 +459,7 @@ chrome.runtime.onConnect.addListener(async (connectedPort: chrome.runtime.Port) console.log("SW adding onMessage listener for App port... done", appPort); // Send an initial msg from SW to App - appPort.postMessage({ type: SwCsMsgType.FSW, data: 'Service worker connected' }); + appPort.postMessage({ type: SwCsMsgEnum.FSW, data: 'Service worker connected' }); } else { console.error('Invalid port:', connectedPort); @@ -478,7 +478,7 @@ chrome.runtime.onConnect.addListener(async (connectedPort: chrome.runtime.Port) const csConnection: CsConnection = pageCsConnections[key]; if (csConnection.tabId != -1) { const lastGasp = { - type: SwCsMsgType.REPLY, + type: SwCsMsgEnum.REPLY, error: "User closed KERI Auth or canceled pending request", requestId: 999999, // TODO P3: maybe this requestId value is filled in by content script? }; @@ -534,10 +534,10 @@ async function signReqSendToTab(message: any, port: chrome.runtime.Port) { if (await connectToKeria()) { const payload = message.payload; const initHeaders: { [key: string]: string } = { method: payload.method, path: payload.url }; - console.warn("tmp signReqSendToTab message: ", message); + // console.warn("tmp signReqSendToTab message: ", message); const headers: { [key: string]: string } = await getSignedHeaders(payload.origin, payload.url, payload.method, initHeaders, payload.selectedName); const signedHeaderResult = { - type: SwCsMsgType.REPLY, + type: SwCsMsgEnum.REPLY, requestId: message.requestId, payload: { headers }, rurl: payload.requestUrl @@ -560,13 +560,13 @@ async function handleMessageFromApp(message: any, appPort: chrome.runtime.Port, // TODO P3 check for nonexistance of appPort.sender?.tab, which would indicate a msg from a non-tab source // Send a response to the KeriAuth App - appPort.postMessage({ type: SwCsMsgType.FSW, data: `SW received your message: ${message.data} for tab ${appPort.sender?.tab}` }); + appPort.postMessage({ type: SwCsMsgEnum.FSW, data: `SW received your message: ${message.data} for tab ${appPort.sender?.tab}` }); // Forward the msg to the content script, if appropriate if (cSConnection) { console.log("SW from App: handling App message of type: ", message.type); switch (message.type) { - case SwCsMsgType.REPLY: + case SwCsMsgEnum.REPLY: cSConnection.port.postMessage(message); break; case "ApprovedSignRequest": @@ -592,7 +592,7 @@ async function handleMessageFromApp(message: any, appPort: chrome.runtime.Port, headers: headers }; const authorizeResult = { - type: SwCsMsgType.REPLY, + type: SwCsMsgEnum.REPLY, requestId: message.requestId, payload: authorizeResultCredential, rurl: "" @@ -611,7 +611,7 @@ async function handleMessageFromApp(message: any, appPort: chrome.runtime.Port, case "/KeriAuth/signify/replyCancel": try { const cancelResult = { - type: SwCsMsgType.REPLY, + type: SwCsMsgEnum.REPLY, requestId: message.requestId, payload: {}, rurl: "" @@ -637,25 +637,26 @@ async function handleMessageFromPageCs(message: ICsSwMsg, cSPort: chrome.runtime // assure tab is still connected if (pageCsConnections[connectionId]) { switch (message.type) { - case CsSwMsgType.POLARIS_SIGNIFY_AUTHORIZE: - case CsSwMsgType.POLARIS_SELECT_AUTHORIZE_AID: - case CsSwMsgType.POLARIS_SELECT_AUTHORIZE_CREDENTIAL: + case CsSwMsgEnum.POLARIS_SIGNIFY_AUTHORIZE: + case CsSwMsgEnum.POLARIS_SELECT_AUTHORIZE_AID: + case CsSwMsgEnum.POLARIS_SELECT_AUTHORIZE_CREDENTIAL: handleSelectAuthorize(message as any, pageCsConnections[connectionId].port); break; - // case CsSwMsgType.SIGN_DATA: + // case CsSwMsgEnum.SIGN_DATA: // TODO P1 request user to sign data (or request?) - case CsSwMsgType.POLARIS_SIGN_REQUEST: + case CsSwMsgEnum.POLARIS_SIGN_REQUEST: await handleSignRequest(message as any, pageCsConnections[connectionId].port); break; - case CsSwMsgType.POLARIS_SIGNIFY_EXTENSION: // TODO P0 Ping + case CsSwMsgEnum.PING: pageCsConnections[connectionId].tabId = tabId; const url = new URL(String(cSPort.sender?.url)); pageCsConnections[connectionId].pageAuthority = url.host; - const response: IExCsMsgHello = { - type: SwCsMsgType.HELLO, // TODO P0 Pong + const response: ISwCsMsgPong = { + type: SwCsMsgEnum.PONG, requestId: message.requestId, payload: {} }; + console.log("SW to CS: ", SwCsMsgEnum.PONG) cSPort.postMessage(response); break; default: