-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge branch 'fix/acknowledge-message' into 'feat/beacon-v2'
Fix/acknowledge message See merge request papers/airgap/beacon-extension!22
- Loading branch information
Showing
11 changed files
with
313 additions
and
18 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
3 changes: 1 addition & 2 deletions
3
src/extension/extension-client/action-handler/ActionMessageHandler.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
129 changes: 129 additions & 0 deletions
129
src/extension/extension-client/chrome-message-transport/ChromeMessageClient.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,129 @@ | ||
import { | ||
EncryptedExtensionMessage, | ||
ExtendedPostMessagePairingResponse, | ||
ExtensionMessage, | ||
ExtensionMessageTarget, | ||
MessageBasedClient, | ||
PostMessagePairingRequest | ||
} from '@airgap/beacon-sdk' | ||
|
||
export class ChromeMessageClient extends MessageBasedClient { | ||
protected readonly activeListeners: Map< | ||
string, | ||
( | ||
message: ExtensionMessage<string> | EncryptedExtensionMessage, | ||
sender: chrome.runtime.MessageSender, | ||
sendResponse: (response?: unknown) => void | ||
) => void | ||
> = new Map() | ||
|
||
public async init(): Promise<void> { | ||
this.subscribeToMessages().catch(console.error) | ||
} | ||
|
||
public async listenForEncryptedMessage( | ||
senderPublicKey: string, | ||
messageCallback: ( | ||
message: ExtensionMessage<string>, | ||
sender: chrome.runtime.MessageSender, | ||
sendResponse: (response?: unknown) => void | ||
) => void | ||
): Promise<void> { | ||
if (this.activeListeners.has(senderPublicKey)) { | ||
return | ||
} | ||
|
||
const callbackFunction = async ( | ||
message: ExtensionMessage<string> | EncryptedExtensionMessage, | ||
sender: chrome.runtime.MessageSender, | ||
sendResponse: (response?: unknown) => void | ||
): Promise<void> => { | ||
if (message.hasOwnProperty('encryptedPayload')) { | ||
const encryptedMessage: EncryptedExtensionMessage = message as EncryptedExtensionMessage | ||
|
||
try { | ||
const decrypted = await this.decryptMessage(senderPublicKey, encryptedMessage.encryptedPayload) | ||
const decryptedMessage: ExtensionMessage<string> = { | ||
payload: decrypted, | ||
target: encryptedMessage.target, | ||
sender: encryptedMessage.sender | ||
} | ||
messageCallback(decryptedMessage, sender, sendResponse) | ||
} catch (decryptionError) { | ||
/* NO-OP. We try to decode every message, but some might not be addressed to us. */ | ||
} | ||
} | ||
} | ||
|
||
this.activeListeners.set(senderPublicKey, callbackFunction) | ||
} | ||
|
||
public async sendMessage( | ||
message: string, | ||
peer?: PostMessagePairingRequest | ExtendedPostMessagePairingResponse | ||
): Promise<void> { | ||
let msg: EncryptedExtensionMessage | ExtensionMessage<string> = { | ||
target: ExtensionMessageTarget.PAGE, | ||
payload: message | ||
} | ||
|
||
// If no recipient public key is provided, we respond with an unencrypted message | ||
if (peer && peer.publicKey) { | ||
const payload = await this.encryptMessage(peer.publicKey, message) | ||
|
||
msg = { | ||
target: ExtensionMessageTarget.PAGE, | ||
encryptedPayload: payload | ||
} | ||
} | ||
|
||
chrome.tabs.query({}, (tabs: chrome.tabs.Tab[]) => { | ||
// TODO: Find way to have direct communication with tab | ||
tabs.forEach(({ id }: chrome.tabs.Tab) => { | ||
if (id) { | ||
chrome.tabs.sendMessage(id, msg) | ||
} | ||
}) // Send message to all tabs | ||
}) | ||
} | ||
|
||
public async sendPairingResponse(pairingRequest: PostMessagePairingRequest): Promise<void> { | ||
const pairingResponse = await this.getPairingResponseInfo(pairingRequest) | ||
|
||
const encryptedMessage: string = await this.encryptMessageAsymmetric( | ||
pairingRequest.publicKey, | ||
JSON.stringify(pairingResponse) | ||
) | ||
|
||
const message: ExtensionMessage<string> = { | ||
target: ExtensionMessageTarget.PAGE, | ||
payload: encryptedMessage | ||
} | ||
chrome.tabs.query({}, (tabs: chrome.tabs.Tab[]) => { | ||
// TODO: Find way to have direct communication with tab | ||
tabs.forEach(({ id }: chrome.tabs.Tab) => { | ||
if (id) { | ||
chrome.tabs.sendMessage(id, message) | ||
} | ||
}) // Send message to all tabs | ||
}) | ||
} | ||
|
||
private async subscribeToMessages(): Promise<void> { | ||
chrome.runtime.onMessage.addListener( | ||
( | ||
message: ExtensionMessage<string> | EncryptedExtensionMessage, | ||
sender: chrome.runtime.MessageSender, | ||
sendResponse: (response?: unknown) => void | ||
) => { | ||
this.activeListeners.forEach(listener => { | ||
listener(message, sender, sendResponse) | ||
}) | ||
|
||
// return true from the event listener to indicate you wish to send a response asynchronously | ||
// (this will keep the message channel open to the other end until sendResponse is called). | ||
return true | ||
} | ||
) | ||
} | ||
} |
165 changes: 165 additions & 0 deletions
165
src/extension/extension-client/chrome-message-transport/ChromeMessageTransport.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,165 @@ | ||
// eslint-disable-next-line spaced-comment | ||
/// <reference types="chrome"/> | ||
|
||
import { | ||
ConnectionContext, | ||
ExtendedPostMessagePairingResponse, | ||
ExtensionMessage, | ||
ExtensionMessageTarget, | ||
getSenderId, | ||
Origin, | ||
PeerManager, | ||
PostMessagePairingRequest, | ||
Serializer, | ||
Storage, | ||
StorageKey, | ||
Transport, | ||
TransportStatus, | ||
TransportType | ||
} from '@airgap/beacon-sdk' | ||
import * as sodium from 'libsodium-wrappers' | ||
|
||
import { Logger } from '../Logger' | ||
|
||
import { ChromeMessageClient } from './ChromeMessageClient' | ||
|
||
const logger = new Logger('ChromeMessageTransport') | ||
|
||
export class ChromeMessageTransport< | ||
T extends PostMessagePairingRequest | ExtendedPostMessagePairingResponse, | ||
K extends StorageKey.TRANSPORT_POSTMESSAGE_PEERS_DAPP | StorageKey.TRANSPORT_POSTMESSAGE_PEERS_WALLET | ||
> extends Transport<T, K, ChromeMessageClient> { | ||
public readonly type: TransportType = TransportType.CHROME_MESSAGE | ||
|
||
constructor(name: string, keyPair: sodium.KeyPair, storage: Storage, storageKey: K) { | ||
super(name, new ChromeMessageClient(name, keyPair, false), new PeerManager(storage, storageKey)) | ||
this.init().catch(error => console.error(error)) | ||
this.connect().catch(error => console.error(error)) | ||
} | ||
|
||
public static async isAvailable(): Promise<boolean> { | ||
const isAvailable: boolean = Boolean(window.chrome && chrome.runtime && chrome.runtime.id) | ||
|
||
return Promise.resolve(isAvailable) | ||
} | ||
|
||
public async connect(): Promise<void> { | ||
logger.log('connect') | ||
this._isConnected = TransportStatus.CONNECTING | ||
|
||
const knownPeers = await this.getPeers() | ||
|
||
if (knownPeers.length > 0) { | ||
logger.log('connect', `connecting to ${knownPeers.length} peers`) | ||
const connectionPromises = knownPeers.map(async peer => this.listen(peer.publicKey)) | ||
await Promise.all(connectionPromises) | ||
} | ||
|
||
await super.connect() | ||
} | ||
|
||
public async send(payload: string | Record<string, unknown>): Promise<void> { | ||
const message: ExtensionMessage<string | Record<string, unknown>> = { | ||
target: ExtensionMessageTarget.PAGE, | ||
payload | ||
} | ||
chrome.runtime.sendMessage(message, (data?: unknown): void => { | ||
logger.log('send', 'got response', data) | ||
}) | ||
} | ||
|
||
public async sendToTabs(publicKey: string | undefined, payload: string): Promise<void> { | ||
const peers = await this.getPeers() | ||
const peer = peers.find(peerEl => peerEl.publicKey === publicKey) | ||
|
||
return this.client.sendMessage(payload, peer) | ||
} | ||
|
||
public async addPeer(newPeer: T): Promise<void> { | ||
await super.addPeer(newPeer) | ||
} | ||
|
||
public async listen(publicKey: string): Promise<void> { | ||
await this.client | ||
.listenForEncryptedMessage( | ||
publicKey, | ||
async ( | ||
message: ExtensionMessage<string>, | ||
sender: chrome.runtime.MessageSender, | ||
sendResponse: (response?: unknown) => void | ||
) => { | ||
const connectionContext: ConnectionContext = { | ||
origin: Origin.WEBSITE, | ||
id: sender.url ? sender.url : '', | ||
extras: { sender, sendResponse } | ||
} | ||
|
||
this.notifyListeners(message, connectionContext).catch(error => { | ||
throw error | ||
}) | ||
} | ||
) | ||
.catch(error => { | ||
throw error | ||
}) | ||
} | ||
|
||
private async init(): Promise<void> { | ||
chrome.runtime.onMessage.addListener( | ||
( | ||
message: ExtensionMessage<string>, | ||
sender: chrome.runtime.MessageSender, | ||
sendResponse: (response?: unknown) => void | ||
) => { | ||
logger.log('init', 'receiving chrome message', message, sender) | ||
|
||
if (message && message.payload && typeof message.payload === 'string') { | ||
// Handling PairingRequest and connect peer | ||
new Serializer() | ||
.deserialize(message.payload) | ||
.then(async deserialized => { | ||
// TODO: Add check if it's a peer | ||
if ((deserialized as any).publicKey) { | ||
const peer = deserialized as any | ||
this.addPeer({ ...peer, senderId: await getSenderId(peer.publicKey) }).catch(console.error) | ||
} else { | ||
// V1 does not support encryption, so we handle the message directly | ||
if ((deserialized as any).version === '1') { | ||
this.notify(message, sender, sendResponse).catch(error => { | ||
throw error | ||
}) | ||
} | ||
} | ||
}) | ||
.catch(undefined) | ||
} else if (message && message.payload) { | ||
// Most likely an internal, unencrypted message | ||
this.notify(message, sender, sendResponse).catch(error => { | ||
throw error | ||
}) | ||
} | ||
|
||
// return true from the event listener to indicate you wish to send a response asynchronously | ||
// (this will keep the message channel open to the other end until sendResponse is called). | ||
|
||
// return true | ||
} | ||
) | ||
} | ||
|
||
private async notify( | ||
message: ExtensionMessage<string>, | ||
sender: chrome.runtime.MessageSender, | ||
sendResponse: (response?: unknown) => void | ||
): Promise<void> { | ||
const connectionContext: ConnectionContext = { | ||
origin: Origin.WEBSITE, | ||
id: sender.url ? sender.url : '', | ||
extras: { sender, sendResponse } | ||
} | ||
|
||
this.notifyListeners(message, connectionContext).catch(error => { | ||
throw error | ||
}) | ||
} | ||
} |
5 changes: 3 additions & 2 deletions
5
src/extension/extension-client/chrome-message-transport/WalletChromeMessageTransport.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.