Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@airgap/beacon-transport-postmessage

Package Overview
Dependencies
Maintainers
1
Versions
118
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@airgap/beacon-transport-postmessage - npm Package Compare versions

Comparing version 4.0.10 to 4.0.11-icp-icrc25-beta.0

326

dist/cjs/PostMessageClient.js
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
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);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -37,34 +11,7 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }

};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PostMessageClient = void 0;
var beacon_core_1 = require("@airgap/beacon-core");
var beacon_utils_1 = require("@airgap/beacon-utils");
var beacon_types_1 = require("@airgap/beacon-types");
const beacon_core_1 = require("@airgap/beacon-core");
const beacon_utils_1 = require("@airgap/beacon-utils");
const beacon_types_1 = require("@airgap/beacon-types");
/**

@@ -75,189 +22,114 @@ * @internalapi

*/
var PostMessageClient = /** @class */ (function (_super) {
__extends(PostMessageClient, _super);
function PostMessageClient() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.activeListeners = new Map();
return _this;
class PostMessageClient extends beacon_core_1.MessageBasedClient {
constructor() {
super(...arguments);
this.activeListeners = new Map();
}
PostMessageClient.prototype.init = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
this.subscribeToMessages().catch(console.error);
return [2 /*return*/];
});
init() {
return __awaiter(this, void 0, void 0, function* () {
this.subscribeToMessages().catch(console.error);
});
};
PostMessageClient.prototype.listenForEncryptedMessage = function (senderPublicKey, messageCallback) {
return __awaiter(this, void 0, void 0, function () {
var callbackFunction;
var _this = this;
return __generator(this, function (_a) {
if (this.activeListeners.has(senderPublicKey)) {
return [2 /*return*/];
}
listenForEncryptedMessage(senderPublicKey, messageCallback) {
return __awaiter(this, void 0, void 0, function* () {
if (this.activeListeners.has(senderPublicKey)) {
return;
}
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);
}
callbackFunction = function (message, context) { return __awaiter(_this, void 0, void 0, function () {
var decryptedMessage, decryptionError_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, this.decryptMessage(senderPublicKey, message.encryptedPayload)
// console.log('calculated sender ID', await getSenderId(senderPublicKey))
// TODO: Add check for correct decryption key / sender ID
];
case 1:
decryptedMessage = _a.sent();
// console.log('calculated sender ID', await getSenderId(senderPublicKey))
// TODO: Add check for correct decryption key / sender ID
messageCallback(decryptedMessage, context);
return [3 /*break*/, 3];
case 2:
decryptionError_1 = _a.sent();
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
}); };
this.activeListeners.set(senderPublicKey, callbackFunction);
return [2 /*return*/];
});
});
};
PostMessageClient.prototype.sendMessage = function (message, peer) {
return __awaiter(this, void 0, void 0, function () {
var payload, targetId, msg;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.encryptMessage(peer.publicKey, message)];
case 1:
payload = _a.sent();
targetId = peer === null || peer === void 0 ? void 0 : peer.extensionId;
msg = {
target: beacon_types_1.ExtensionMessageTarget.EXTENSION,
encryptedPayload: payload,
targetId: targetId
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
beacon_core_1.windowRef.postMessage(msg, beacon_core_1.windowRef.location.origin);
return [2 /*return*/];
catch (decryptionError) {
/* NO-OP. We try to decode every message, but some might not be addressed to us. */
}
});
this.activeListeners.set(senderPublicKey, callbackFunction);
});
};
PostMessageClient.prototype.listenForChannelOpening = function (messageCallback) {
return __awaiter(this, void 0, void 0, function () {
var fn;
var _this = this;
return __generator(this, function (_a) {
fn = function (event) { return __awaiter(_this, void 0, void 0, function () {
var data, _a, payload, pairingResponse, _b, _c, _d, _e, decryptionError_2;
var _f;
var _g, _h;
return __generator(this, function (_j) {
switch (_j.label) {
case 0:
if (event.source !== beacon_core_1.windowRef || event.origin !== beacon_core_1.windowRef.location.origin) {
// TODO: Add to error handler: console.debug('[Beacon]: Event received from untrusted origin')
return [2 /*return*/];
}
data = (_g = event === null || event === void 0 ? void 0 : event.data) === null || _g === void 0 ? void 0 : _g.message;
_a = data &&
data.target === beacon_types_1.ExtensionMessageTarget.PAGE;
if (!_a) return [3 /*break*/, 2];
return [4 /*yield*/, this.isChannelOpenMessage(data)];
case 1:
_a = (_j.sent());
_j.label = 2;
case 2:
if (!_a) return [3 /*break*/, 7];
payload = Buffer.from(data.payload, 'hex');
if (!(payload.length >= beacon_utils_1.secretbox_NONCEBYTES + beacon_utils_1.secretbox_MACBYTES)) return [3 /*break*/, 7];
_j.label = 3;
case 3:
_j.trys.push([3, 6, , 7]);
_c = (_b = JSON).parse;
return [4 /*yield*/, (0, beacon_utils_1.openCryptobox)(payload, this.keyPair.publicKey, this.keyPair.secretKey)];
case 4:
pairingResponse = _c.apply(_b, [_j.sent()]);
_d = messageCallback;
_e = [__assign({}, pairingResponse)];
_f = {};
return [4 /*yield*/, (0, beacon_core_1.getSenderId)(pairingResponse.publicKey)];
case 5:
_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 [3 /*break*/, 7];
case 6:
decryptionError_2 = _j.sent();
return [3 /*break*/, 7];
case 7: return [2 /*return*/];
}
});
}); };
beacon_core_1.windowRef.addEventListener('message', fn);
return [2 /*return*/];
});
}
sendMessage(message, peer) {
return __awaiter(this, void 0, void 0, function* () {
const payload = yield this.encryptMessage(peer.publicKey, message);
const targetId = peer === null || peer === void 0 ? void 0 : peer.extensionId;
// if no targetId, we remove peer
const msg = {
target: beacon_types_1.ExtensionMessageTarget.EXTENSION,
encryptedPayload: payload,
targetId
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
beacon_core_1.windowRef.postMessage(msg, beacon_core_1.windowRef.location.origin);
});
};
PostMessageClient.prototype.sendPairingRequest = function (id) {
return __awaiter(this, void 0, void 0, function () {
var message, _a, _b;
var _c;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
_c = {
target: beacon_types_1.ExtensionMessageTarget.EXTENSION
};
_b = (_a = new beacon_core_1.Serializer()).serialize;
return [4 /*yield*/, this.getPairingRequestInfo()];
case 1: return [4 /*yield*/, _b.apply(_a, [_d.sent()])];
case 2:
message = (_c.payload = _d.sent(),
_c.targetId = id,
_c);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
beacon_core_1.windowRef.postMessage(message, beacon_core_1.windowRef.location.origin);
return [2 /*return*/];
}
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;
if (event.source !== beacon_core_1.windowRef || event.origin !== beacon_core_1.windowRef.location.origin) {
// TODO: Add to error handler: console.debug('[Beacon]: Event received from untrusted origin')
return;
}
const data = (_a = event === null || event === void 0 ? void 0 : event.data) === null || _a === void 0 ? void 0 : _a.message;
if (data &&
data.target === beacon_types_1.ExtensionMessageTarget.PAGE &&
(yield this.isChannelOpenMessage(data))) {
const payload = Buffer.from(data.payload, 'hex');
if (payload.length >= beacon_utils_1.secretbox_NONCEBYTES + beacon_utils_1.secretbox_MACBYTES) {
try {
const pairingResponse = JSON.parse(yield (0, beacon_utils_1.openCryptobox)(payload, this.keyPair.publicKey, this.keyPair.secretKey));
messageCallback(new beacon_types_1.ExtendedPostMessagePairingResponse(pairingResponse.id, pairingResponse.name, pairingResponse.publicKey, pairingResponse.version, yield (0, beacon_core_1.getSenderId)(pairingResponse.publicKey), (_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. */
}
}
}
});
beacon_core_1.windowRef.addEventListener('message', fn);
});
};
PostMessageClient.prototype.isChannelOpenMessage = function (message) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, typeof message === 'object' && message.hasOwnProperty('payload')];
});
}
sendPairingRequest(id) {
return __awaiter(this, void 0, void 0, function* () {
const message = {
target: beacon_types_1.ExtensionMessageTarget.EXTENSION,
payload: yield new beacon_core_1.Serializer().serialize(yield this.getPairingRequestInfo()),
targetId: id
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
beacon_core_1.windowRef.postMessage(message, beacon_core_1.windowRef.location.origin);
});
};
PostMessageClient.prototype.subscribeToMessages = function () {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
beacon_core_1.windowRef.addEventListener('message', function (message) {
if (message.source !== beacon_core_1.windowRef ||
message.origin !== beacon_core_1.windowRef.location.origin) {
// TODO: Add to error handler: console.debug('[Beacon]: Event received from untrusted origin')
return;
}
if (typeof message === 'object' && message) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var data_1 = message.data;
if (data_1.message && data_1.message.target === beacon_types_1.ExtensionMessageTarget.PAGE) {
_this.activeListeners.forEach(function (listener) {
listener(data_1.message, {
origin: beacon_types_1.Origin.EXTENSION,
id: data_1.sender.id || ''
});
}
isChannelOpenMessage(message) {
return __awaiter(this, void 0, void 0, function* () {
return typeof message === 'object' && message.hasOwnProperty('payload');
});
}
subscribeToMessages() {
return __awaiter(this, void 0, void 0, function* () {
beacon_core_1.windowRef.addEventListener('message', (message) => {
if (message.source !== beacon_core_1.windowRef ||
message.origin !== beacon_core_1.windowRef.location.origin) {
// TODO: Add to error handler: console.debug('[Beacon]: Event received from untrusted origin')
return;
}
if (typeof message === 'object' && message) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const data = message.data;
if (data.message && data.message.target === beacon_types_1.ExtensionMessageTarget.PAGE) {
this.activeListeners.forEach((listener) => {
listener(data.message, {
origin: beacon_types_1.Origin.EXTENSION,
id: data.sender.id || ''
});
}
});
}
});
return [2 /*return*/];
}
});
});
};
return PostMessageClient;
}(beacon_core_1.MessageBasedClient));
}
}
exports.PostMessageClient = PostMessageClient;
//# sourceMappingURL=PostMessageClient.js.map
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
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);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -26,43 +11,16 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }

};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PostMessageTransport = void 0;
var beacon_types_1 = require("@airgap/beacon-types");
var beacon_core_1 = require("@airgap/beacon-core");
var PostMessageClient_1 = require("./PostMessageClient");
var logger = new beacon_core_1.Logger('PostMessageTransport');
var listeningForExtensions = false;
var extensionsPromise;
var extensions;
var addExtension = function (extension) {
const beacon_types_1 = require("@airgap/beacon-types");
const beacon_core_1 = require("@airgap/beacon-core");
const PostMessageClient_1 = require("./PostMessageClient");
const logger = new beacon_core_1.Logger('PostMessageTransport');
let listeningForExtensions = false;
let extensionsPromise;
let extensions;
const addExtension = (extension) => {
if (!extensions) {
extensions = [];
}
if (!extensions.some(function (ext) { return ext.id === extension.id; })) {
if (!extensions.some((ext) => ext.id === extension.id)) {
extensions.push(extension);

@@ -77,55 +35,49 @@ beacon_core_1.windowRef.postMessage('extensionsUpdated', beacon_core_1.windowRef.location.origin);

*/
var PostMessageTransport = /** @class */ (function (_super) {
__extends(PostMessageTransport, _super);
function PostMessageTransport(name, keyPair, storage, storageKey) {
var _this = _super.call(this, name, new PostMessageClient_1.PostMessageClient(name, keyPair), new beacon_core_1.PeerManager(storage, storageKey)) || this;
_this.type = beacon_types_1.TransportType.POST_MESSAGE;
return _this;
class PostMessageTransport extends beacon_core_1.Transport {
constructor(name, keyPair, storage, storageKey) {
super(name, new PostMessageClient_1.PostMessageClient(name, keyPair), new beacon_core_1.PeerManager(storage, storageKey));
this.type = beacon_types_1.TransportType.POST_MESSAGE;
}
PostMessageTransport.isAvailable = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, new Promise(function (resolve) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var fn = function (event) {
var data = event.data;
if (data && data.payload === 'pong') {
resolve(true);
beacon_core_1.windowRef.removeEventListener('message', fn);
}
};
beacon_core_1.windowRef.addEventListener('message', fn);
var message = {
target: beacon_types_1.ExtensionMessageTarget.EXTENSION,
payload: 'ping'
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
beacon_core_1.windowRef.postMessage(message, beacon_core_1.windowRef.location.origin);
})];
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);
beacon_core_1.windowRef.removeEventListener('message', fn);
}
};
beacon_core_1.windowRef.addEventListener('message', fn);
const message = {
target: beacon_types_1.ExtensionMessageTarget.EXTENSION,
payload: 'ping'
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
beacon_core_1.windowRef.postMessage(message, beacon_core_1.windowRef.location.origin);
});
});
};
PostMessageTransport.getAvailableExtensions = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
if (extensionsPromise) {
return [2 /*return*/, extensionsPromise];
}
if (extensions) {
return [2 /*return*/, extensions];
}
extensions = [];
extensionsPromise = new Promise(function (resolve) {
PostMessageTransport.listenForExtensions();
setTimeout(function () {
resolve(extensions !== null && extensions !== void 0 ? extensions : []);
}, 1000);
}).finally(function () {
extensionsPromise = undefined;
});
return [2 /*return*/, extensionsPromise];
}
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;
});
return extensionsPromise;
});
};
PostMessageTransport.listenForExtensions = function () {
}
static listenForExtensions() {
if (listeningForExtensions) {

@@ -135,3 +87,3 @@ return;

// eslint-disable-next-line @typescript-eslint/no-explicit-any
var fn = function (event) {
const fn = (event) => {
if (event.source !== beacon_core_1.windowRef || event.origin !== beacon_core_1.windowRef.location.origin) {

@@ -141,6 +93,6 @@ // TODO: Add to error handler: console.debug('[Beacon]: Event received from untrusted origin')

}
var data = event.data;
var sender = data.sender;
const data = event.data;
const sender = data.sender;
if (data && data.payload === 'pong' && sender) {
logger.log('getAvailableExtensions', "extension \"".concat(sender.name, "\" is available"), sender);
logger.log('getAvailableExtensions', `extension "${sender.name}" is available`, sender);
addExtension(sender);

@@ -150,3 +102,3 @@ }

beacon_core_1.windowRef.addEventListener('message', fn);
var message = {
const message = {
target: beacon_types_1.ExtensionMessageTarget.EXTENSION,

@@ -158,79 +110,52 @@ payload: 'ping'

listeningForExtensions = true;
};
PostMessageTransport.prototype.connect = function () {
return __awaiter(this, void 0, void 0, function () {
var knownPeers, connectionPromises;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
logger.log('connect');
if (this._isConnected !== beacon_types_1.TransportStatus.NOT_CONNECTED) {
return [2 /*return*/];
}
this._isConnected = beacon_types_1.TransportStatus.CONNECTING;
return [4 /*yield*/, this.getPeers()];
case 1:
knownPeers = _a.sent();
if (knownPeers.length > 0) {
logger.log('connect', "connecting to ".concat(knownPeers.length, " peers"));
connectionPromises = knownPeers.map(function (peer) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/, this.listen(peer.publicKey)];
}); }); });
Promise.all(connectionPromises).catch(function (error) { return logger.error('connect', error); });
}
return [4 /*yield*/, this.startOpenChannelListener()];
case 2:
_a.sent();
return [4 /*yield*/, _super.prototype.connect.call(this)];
case 3:
_a.sent();
return [2 /*return*/];
}
});
}
connect() {
const _super = Object.create(null, {
connect: { get: () => super.connect }
});
};
PostMessageTransport.prototype.startOpenChannelListener = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/];
});
return __awaiter(this, void 0, void 0, function* () {
logger.log('connect');
if (this._isConnected !== beacon_types_1.TransportStatus.NOT_CONNECTED) {
return;
}
this._isConnected = beacon_types_1.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);
});
};
PostMessageTransport.prototype.getPairingRequestInfo = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.client.getPairingRequestInfo()];
});
}
startOpenChannelListener() {
return __awaiter(this, void 0, void 0, function* () {
//
});
};
PostMessageTransport.prototype.listen = function (publicKey) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
logger.log('listen', publicKey);
return [4 /*yield*/, this.client
.listenForEncryptedMessage(publicKey, function (message, context) {
var connectionContext = {
origin: beacon_types_1.Origin.EXTENSION,
id: context.id
};
_this.notifyListeners(message, connectionContext).catch(function (error) {
throw error;
});
})
.catch(function (error) {
throw error;
})];
case 1:
_a.sent();
return [2 /*return*/];
}
}
getPairingRequestInfo() {
return __awaiter(this, void 0, void 0, function* () {
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: beacon_types_1.Origin.EXTENSION,
id: context.id
};
this.notifyListeners(message, connectionContext).catch((error) => {
throw error;
});
})
.catch((error) => {
throw error;
});
});
};
return PostMessageTransport;
}(beacon_core_1.Transport));
}
}
exports.PostMessageTransport = PostMessageTransport;

@@ -237,0 +162,0 @@ // Start loading wallets async so they will be ready when the modal is opened

@@ -1,13 +0,4 @@

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 { windowRef, Serializer, getSenderId, MessageBasedClient } from '@airgap/beacon-core';
import { openCryptobox, secretbox_NONCEBYTES, secretbox_MACBYTES } from '@airgap/beacon-utils';
import { ExtensionMessageTarget, Origin } from '@airgap/beacon-types';
import { ExtensionMessageTarget, Origin, ExtendedPostMessagePairingResponse } from '@airgap/beacon-types';
/**

@@ -19,109 +10,91 @@ * @internalapi

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);
});
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);
}
catch (decryptionError) {
/* NO-OP. We try to decode every message, but some might not be addressed to us. */
}
};
this.activeListeners.set(senderPublicKey, callbackFunction);
}
listenForEncryptedMessage(senderPublicKey, messageCallback) {
return __awaiter(this, void 0, void 0, function* () {
if (this.activeListeners.has(senderPublicKey)) {
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);
}
async listenForChannelOpening(messageCallback) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const fn = async (event) => {
if (event.source !== windowRef || event.origin !== windowRef.location.origin) {
// TODO: Add to error handler: console.debug('[Beacon]: Event received from untrusted origin')
return;
}
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);
});
}
sendMessage(message, peer) {
return __awaiter(this, void 0, void 0, function* () {
const payload = yield this.encryptMessage(peer.publicKey, message);
const targetId = peer === null || peer === void 0 ? void 0 : 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;
if (event.source !== windowRef || event.origin !== windowRef.location.origin) {
// TODO: Add to error handler: console.debug('[Beacon]: Event received from untrusted origin')
return;
}
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 >= secretbox_NONCEBYTES + secretbox_MACBYTES) {
try {
const pairingResponse = JSON.parse(yield openCryptobox(payload, this.keyPair.publicKey, this.keyPair.secretKey));
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. */
}
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 >= secretbox_NONCEBYTES + secretbox_MACBYTES) {
try {
const pairingResponse = JSON.parse(await openCryptobox(payload, this.keyPair.publicKey, this.keyPair.secretKey));
messageCallback(new ExtendedPostMessagePairingResponse(pairingResponse.id, pairingResponse.name, pairingResponse.publicKey, pairingResponse.version, await getSenderId(pairingResponse.publicKey), 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 (message.source !== windowRef ||
message.origin !== windowRef.location.origin) {
// TODO: Add to error handler: console.debug('[Beacon]: Event received from untrusted origin')
return;
}
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 (message.source !== windowRef ||
message.origin !== windowRef.location.origin) {
// TODO: Add to error handler: console.debug('[Beacon]: Event received from untrusted origin')
return;
}
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 || ''
});
}
});
}
});
}
});

@@ -128,0 +101,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;
}

@@ -104,48 +91,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;
});

@@ -152,0 +128,0 @@ }

{
"name": "@airgap/beacon-transport-postmessage",
"version": "4.0.10",
"version": "4.0.11-icp-icrc25-beta.0",
"description": "This package contains methods to facilitate communication over the postmessage interface of the browser to talk to browser extensions.",

@@ -37,7 +37,7 @@ "author": "Andreas Gassmann <a.gassmann@papers.ch>",

"dependencies": {
"@airgap/beacon-core": "4.0.10",
"@airgap/beacon-types": "4.0.10",
"@airgap/beacon-utils": "4.0.10"
"@airgap/beacon-core": "4.0.11-icp-icrc25-beta.0",
"@airgap/beacon-types": "4.0.11-icp-icrc25-beta.0",
"@airgap/beacon-utils": "4.0.11-icp-icrc25-beta.0"
},
"gitHead": "b32a028d4d9036f561a97bc6ada75af792a6d6ee"
"gitHead": "d85c387cfeb2c0b2cb365871ff0c4c9be4bc61e4"
}

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

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc