@airgap/beacon-transport-postmessage
Advanced tools
Comparing version 0.0.1-beta.9 to 0.0.1-beta.10
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.PostMessageTransport = void 0; | ||
var PostMessageTransport_1 = require("./PostMessageTransport"); | ||
Object.defineProperty(exports, "PostMessageTransport", { enumerable: true, get: function () { return PostMessageTransport_1.PostMessageTransport; } }); | ||
//# sourceMappingURL=index.js.map |
@@ -6,6 +6,8 @@ "use strict"; | ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || | ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; | ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; | ||
return extendStatics(d, b); | ||
}; | ||
return function (d, b) { | ||
if (typeof b !== "function" && b !== null) | ||
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); | ||
extendStatics(d, b); | ||
@@ -153,3 +155,4 @@ function __() { this.constructor = d; } | ||
fn = function (event) { return __awaiter(_this, void 0, void 0, function () { | ||
var data, _a, payload, pairingResponse, _b, _c, _d, _e, _f, decryptionError_2; | ||
var data, _a, payload, pairingResponse, _b, _c, _d, _e, decryptionError_2; | ||
var _f; | ||
var _g, _h; | ||
@@ -175,3 +178,3 @@ return __generator(this, function (_j) { | ||
_c = (_b = JSON).parse; | ||
return [4 /*yield*/, beacon_utils_1.openCryptobox(payload, this.keyPair.publicKey, this.keyPair.privateKey)]; | ||
return [4 /*yield*/, (0, beacon_utils_1.openCryptobox)(payload, this.keyPair.publicKey, this.keyPair.privateKey)]; | ||
case 4: | ||
@@ -182,3 +185,3 @@ pairingResponse = _c.apply(_b, [_j.sent()]); | ||
_f = {}; | ||
return [4 /*yield*/, beacon_core_1.getSenderId(pairingResponse.publicKey)]; | ||
return [4 /*yield*/, (0, beacon_core_1.getSenderId)(pairingResponse.publicKey)]; | ||
case 5: | ||
@@ -201,16 +204,17 @@ _d.apply(void 0, [__assign.apply(void 0, _e.concat([(_f.senderId = _j.sent(), _f.extensionId = (_h = event === null || event === void 0 ? void 0 : event.data) === null || _h === void 0 ? void 0 : _h.sender.id, _f)]))]); | ||
return __awaiter(this, void 0, void 0, function () { | ||
var message, _a, _b, _c; | ||
var message, _a, _b; | ||
var _c; | ||
return __generator(this, function (_d) { | ||
switch (_d.label) { | ||
case 0: | ||
_a = { | ||
_c = { | ||
target: beacon_types_1.ExtensionMessageTarget.EXTENSION | ||
}; | ||
_c = (_b = new beacon_core_1.Serializer()).serialize; | ||
_b = (_a = new beacon_core_1.Serializer()).serialize; | ||
return [4 /*yield*/, this.getPairingRequestInfo()]; | ||
case 1: return [4 /*yield*/, _c.apply(_b, [_d.sent()])]; | ||
case 1: return [4 /*yield*/, _b.apply(_a, [_d.sent()])]; | ||
case 2: | ||
message = (_a.payload = _d.sent(), | ||
_a.targetId = id, | ||
_a); | ||
message = (_c.payload = _d.sent(), | ||
_c.targetId = id, | ||
_c); | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
@@ -217,0 +221,0 @@ beacon_core_1.windowRef.postMessage(message, beacon_core_1.windowRef.location.origin); |
@@ -6,6 +6,8 @@ "use strict"; | ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || | ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; | ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; | ||
return extendStatics(d, b); | ||
}; | ||
return function (d, b) { | ||
if (typeof b !== "function" && b !== null) | ||
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); | ||
extendStatics(d, b); | ||
@@ -12,0 +14,0 @@ function __() { this.constructor = d; } |
@@ -1,10 +0,1 @@ | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
import { crypto_secretbox_NONCEBYTES, crypto_secretbox_MACBYTES } from 'libsodium-wrappers'; | ||
@@ -20,101 +11,86 @@ import { windowRef, Serializer, getSenderId, MessageBasedClient } from '@airgap/beacon-core'; | ||
export class PostMessageClient extends MessageBasedClient { | ||
constructor() { | ||
super(...arguments); | ||
this.activeListeners = new Map(); | ||
activeListeners = new Map(); | ||
async init() { | ||
this.subscribeToMessages().catch(console.error); | ||
} | ||
init() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
this.subscribeToMessages().catch(console.error); | ||
}); | ||
} | ||
listenForEncryptedMessage(senderPublicKey, messageCallback) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (this.activeListeners.has(senderPublicKey)) { | ||
return; | ||
async listenForEncryptedMessage(senderPublicKey, messageCallback) { | ||
if (this.activeListeners.has(senderPublicKey)) { | ||
return; | ||
} | ||
const callbackFunction = async (message, context) => { | ||
try { | ||
const decryptedMessage = await this.decryptMessage(senderPublicKey, message.encryptedPayload); | ||
// console.log('calculated sender ID', await getSenderId(senderPublicKey)) | ||
// TODO: Add check for correct decryption key / sender ID | ||
messageCallback(decryptedMessage, context); | ||
} | ||
const callbackFunction = (message, context) => __awaiter(this, void 0, void 0, function* () { | ||
try { | ||
const decryptedMessage = yield this.decryptMessage(senderPublicKey, message.encryptedPayload); | ||
// console.log('calculated sender ID', await getSenderId(senderPublicKey)) | ||
// TODO: Add check for correct decryption key / sender ID | ||
messageCallback(decryptedMessage, context); | ||
} | ||
catch (decryptionError) { | ||
/* NO-OP. We try to decode every message, but some might not be addressed to us. */ | ||
} | ||
}); | ||
this.activeListeners.set(senderPublicKey, callbackFunction); | ||
}); | ||
catch (decryptionError) { | ||
/* NO-OP. We try to decode every message, but some might not be addressed to us. */ | ||
} | ||
}; | ||
this.activeListeners.set(senderPublicKey, callbackFunction); | ||
} | ||
sendMessage(message, peer) { | ||
var _a; | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const payload = yield this.encryptMessage(peer.publicKey, message); | ||
const targetId = (_a = peer) === null || _a === void 0 ? void 0 : _a.extensionId; | ||
// if no targetId, we remove peer | ||
const msg = { | ||
target: ExtensionMessageTarget.EXTENSION, | ||
encryptedPayload: payload, | ||
targetId | ||
}; | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
windowRef.postMessage(msg, windowRef.location.origin); | ||
}); | ||
async sendMessage(message, peer) { | ||
const payload = await this.encryptMessage(peer.publicKey, message); | ||
const targetId = peer?.extensionId; | ||
// if no targetId, we remove peer | ||
const msg = { | ||
target: ExtensionMessageTarget.EXTENSION, | ||
encryptedPayload: payload, | ||
targetId | ||
}; | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
windowRef.postMessage(msg, windowRef.location.origin); | ||
} | ||
listenForChannelOpening(messageCallback) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
const fn = (event) => __awaiter(this, void 0, void 0, function* () { | ||
var _a, _b; | ||
const data = (_a = event === null || event === void 0 ? void 0 : event.data) === null || _a === void 0 ? void 0 : _a.message; | ||
if (data && | ||
data.target === ExtensionMessageTarget.PAGE && | ||
(yield this.isChannelOpenMessage(data))) { | ||
const payload = Buffer.from(data.payload, 'hex'); | ||
if (payload.length >= crypto_secretbox_NONCEBYTES + crypto_secretbox_MACBYTES) { | ||
try { | ||
const pairingResponse = JSON.parse(yield openCryptobox(payload, this.keyPair.publicKey, this.keyPair.privateKey)); | ||
messageCallback(Object.assign(Object.assign({}, pairingResponse), { senderId: yield getSenderId(pairingResponse.publicKey), extensionId: (_b = event === null || event === void 0 ? void 0 : event.data) === null || _b === void 0 ? void 0 : _b.sender.id })); | ||
} | ||
catch (decryptionError) { | ||
/* NO-OP. We try to decode every message, but some might not be addressed to us. */ | ||
} | ||
async listenForChannelOpening(messageCallback) { | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
const fn = async (event) => { | ||
const data = event?.data?.message; | ||
if (data && | ||
data.target === ExtensionMessageTarget.PAGE && | ||
(await this.isChannelOpenMessage(data))) { | ||
const payload = Buffer.from(data.payload, 'hex'); | ||
if (payload.length >= crypto_secretbox_NONCEBYTES + crypto_secretbox_MACBYTES) { | ||
try { | ||
const pairingResponse = JSON.parse(await openCryptobox(payload, this.keyPair.publicKey, this.keyPair.privateKey)); | ||
messageCallback({ | ||
...pairingResponse, | ||
senderId: await getSenderId(pairingResponse.publicKey), | ||
extensionId: event?.data?.sender.id | ||
}); | ||
} | ||
catch (decryptionError) { | ||
/* NO-OP. We try to decode every message, but some might not be addressed to us. */ | ||
} | ||
} | ||
}); | ||
windowRef.addEventListener('message', fn); | ||
}); | ||
} | ||
}; | ||
windowRef.addEventListener('message', fn); | ||
} | ||
sendPairingRequest(id) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const message = { | ||
target: ExtensionMessageTarget.EXTENSION, | ||
payload: yield new Serializer().serialize(yield this.getPairingRequestInfo()), | ||
targetId: id | ||
}; | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
windowRef.postMessage(message, windowRef.location.origin); | ||
}); | ||
async sendPairingRequest(id) { | ||
const message = { | ||
target: ExtensionMessageTarget.EXTENSION, | ||
payload: await new Serializer().serialize(await this.getPairingRequestInfo()), | ||
targetId: id | ||
}; | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
windowRef.postMessage(message, windowRef.location.origin); | ||
} | ||
isChannelOpenMessage(message) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return typeof message === 'object' && message.hasOwnProperty('payload'); | ||
}); | ||
async isChannelOpenMessage(message) { | ||
return typeof message === 'object' && message.hasOwnProperty('payload'); | ||
} | ||
subscribeToMessages() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
windowRef.addEventListener('message', (message) => { | ||
if (typeof message === 'object' && message) { | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
const data = message.data; | ||
if (data.message && data.message.target === ExtensionMessageTarget.PAGE) { | ||
this.activeListeners.forEach((listener) => { | ||
listener(data.message, { | ||
origin: Origin.EXTENSION, | ||
id: data.sender.id || '' | ||
}); | ||
async subscribeToMessages() { | ||
windowRef.addEventListener('message', (message) => { | ||
if (typeof message === 'object' && message) { | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
const data = message.data; | ||
if (data.message && data.message.target === ExtensionMessageTarget.PAGE) { | ||
this.activeListeners.forEach((listener) => { | ||
listener(data.message, { | ||
origin: Origin.EXTENSION, | ||
id: data.sender.id || '' | ||
}); | ||
} | ||
}); | ||
} | ||
}); | ||
} | ||
}); | ||
@@ -121,0 +97,0 @@ } |
@@ -1,10 +0,1 @@ | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
import { TransportType, ExtensionMessageTarget, TransportStatus, Origin } from '@airgap/beacon-types'; | ||
@@ -32,46 +23,42 @@ import { Transport, PeerManager, Logger, windowRef } from '@airgap/beacon-core'; | ||
export class PostMessageTransport extends Transport { | ||
type = TransportType.POST_MESSAGE; | ||
constructor(name, keyPair, storage, storageKey) { | ||
super(name, new PostMessageClient(name, keyPair), new PeerManager(storage, storageKey)); | ||
this.type = TransportType.POST_MESSAGE; | ||
} | ||
static isAvailable() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return new Promise((resolve) => { | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
const fn = (event) => { | ||
const data = event.data; | ||
if (data && data.payload === 'pong') { | ||
resolve(true); | ||
windowRef.removeEventListener('message', fn); | ||
} | ||
}; | ||
windowRef.addEventListener('message', fn); | ||
const message = { | ||
target: ExtensionMessageTarget.EXTENSION, | ||
payload: 'ping' | ||
}; | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
windowRef.postMessage(message, windowRef.location.origin); | ||
}); | ||
static async isAvailable() { | ||
return new Promise((resolve) => { | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
const fn = (event) => { | ||
const data = event.data; | ||
if (data && data.payload === 'pong') { | ||
resolve(true); | ||
windowRef.removeEventListener('message', fn); | ||
} | ||
}; | ||
windowRef.addEventListener('message', fn); | ||
const message = { | ||
target: ExtensionMessageTarget.EXTENSION, | ||
payload: 'ping' | ||
}; | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
windowRef.postMessage(message, windowRef.location.origin); | ||
}); | ||
} | ||
static getAvailableExtensions() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (extensionsPromise) { | ||
return extensionsPromise; | ||
} | ||
if (extensions) { | ||
return extensions; | ||
} | ||
extensions = []; | ||
extensionsPromise = new Promise((resolve) => { | ||
PostMessageTransport.listenForExtensions(); | ||
setTimeout(() => { | ||
resolve(extensions !== null && extensions !== void 0 ? extensions : []); | ||
}, 1000); | ||
}).finally(() => { | ||
extensionsPromise = undefined; | ||
}); | ||
static async getAvailableExtensions() { | ||
if (extensionsPromise) { | ||
return extensionsPromise; | ||
} | ||
if (extensions) { | ||
return extensions; | ||
} | ||
extensions = []; | ||
extensionsPromise = new Promise((resolve) => { | ||
PostMessageTransport.listenForExtensions(); | ||
setTimeout(() => { | ||
resolve(extensions ?? []); | ||
}, 1000); | ||
}).finally(() => { | ||
extensionsPromise = undefined; | ||
}); | ||
return extensionsPromise; | ||
} | ||
@@ -100,48 +87,37 @@ static listenForExtensions() { | ||
} | ||
connect() { | ||
const _super = Object.create(null, { | ||
connect: { get: () => super.connect } | ||
}); | ||
return __awaiter(this, void 0, void 0, function* () { | ||
logger.log('connect'); | ||
if (this._isConnected !== TransportStatus.NOT_CONNECTED) { | ||
return; | ||
} | ||
this._isConnected = TransportStatus.CONNECTING; | ||
const knownPeers = yield this.getPeers(); | ||
if (knownPeers.length > 0) { | ||
logger.log('connect', `connecting to ${knownPeers.length} peers`); | ||
const connectionPromises = knownPeers.map((peer) => __awaiter(this, void 0, void 0, function* () { return this.listen(peer.publicKey); })); | ||
Promise.all(connectionPromises).catch((error) => logger.error('connect', error)); | ||
} | ||
yield this.startOpenChannelListener(); | ||
yield _super.connect.call(this); | ||
}); | ||
async connect() { | ||
logger.log('connect'); | ||
if (this._isConnected !== TransportStatus.NOT_CONNECTED) { | ||
return; | ||
} | ||
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)); | ||
Promise.all(connectionPromises).catch((error) => logger.error('connect', error)); | ||
} | ||
await this.startOpenChannelListener(); | ||
await super.connect(); | ||
} | ||
startOpenChannelListener() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
// | ||
}); | ||
async startOpenChannelListener() { | ||
// | ||
} | ||
getPairingRequestInfo() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return this.client.getPairingRequestInfo(); | ||
}); | ||
async getPairingRequestInfo() { | ||
return this.client.getPairingRequestInfo(); | ||
} | ||
listen(publicKey) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
logger.log('listen', publicKey); | ||
yield this.client | ||
.listenForEncryptedMessage(publicKey, (message, context) => { | ||
const connectionContext = { | ||
origin: Origin.EXTENSION, | ||
id: context.id | ||
}; | ||
this.notifyListeners(message, connectionContext).catch((error) => { | ||
throw error; | ||
}); | ||
}) | ||
.catch((error) => { | ||
async listen(publicKey) { | ||
logger.log('listen', publicKey); | ||
await this.client | ||
.listenForEncryptedMessage(publicKey, (message, context) => { | ||
const connectionContext = { | ||
origin: Origin.EXTENSION, | ||
id: context.id | ||
}; | ||
this.notifyListeners(message, connectionContext).catch((error) => { | ||
throw error; | ||
}); | ||
}) | ||
.catch((error) => { | ||
throw error; | ||
}); | ||
@@ -148,0 +124,0 @@ } |
{ | ||
"name": "@airgap/beacon-transport-postmessage", | ||
"version": "0.0.1-beta.9", | ||
"version": "0.0.1-beta.10", | ||
"description": "> TODO: description", | ||
@@ -40,9 +40,9 @@ "author": "Andreas Gassmann <andreas@andreasgassmann.ch>", | ||
"dependencies": { | ||
"@airgap/beacon-core": "^0.0.1-beta.9", | ||
"@airgap/beacon-types": "^0.0.1-beta.9", | ||
"@airgap/beacon-utils": "^0.0.1-beta.9", | ||
"@airgap/beacon-core": "^0.0.1-beta.10", | ||
"@airgap/beacon-types": "^0.0.1-beta.10", | ||
"@airgap/beacon-utils": "^0.0.1-beta.10", | ||
"@types/libsodium-wrappers": "0.7.9", | ||
"libsodium-wrappers": "0.7.9" | ||
}, | ||
"gitHead": "d23e9fb9724b5cbc82b18a2cd29fe1dd15403ac4" | ||
"gitHead": "dee593d5e9773cfeb53397c1f5824afca2f5d5a4" | ||
} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
55773
783