UNPKG

@bangjelkoski/ledgerhq-hw-transport-webhid

Version:
218 lines 7.59 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.TransportWebHID = void 0; const hw_transport_1 = __importDefault(require("@ledgerhq/hw-transport")); const hid_framing_1 = __importDefault(require("@ledgerhq/devices/hid-framing")); const devices_1 = require("@ledgerhq/devices"); const logs_1 = require("@ledgerhq/logs"); const errors_1 = require("@ledgerhq/errors"); const ledgerDevices = [ { vendorId: devices_1.ledgerUSBVendorId, }, ]; const isSupported = () => Promise.resolve(!!(window.navigator && window.navigator.hid)); const getHID = () => { // $FlowFixMe const { hid } = navigator; if (!hid) throw new errors_1.TransportError("navigator.hid is not supported", "HIDNotSupported"); return hid; }; async function requestLedgerDevices() { const device = await getHID().requestDevice({ filters: ledgerDevices, }); if (Array.isArray(device)) return device; return [device]; } async function getLedgerDevices() { const devices = await getHID().getDevices(); return devices.filter(d => d.vendorId === devices_1.ledgerUSBVendorId); } async function getFirstLedgerDevice() { const existingDevices = await getLedgerDevices(); if (existingDevices.length > 0) return existingDevices[0]; const devices = await requestLedgerDevices(); return devices[0]; } /** * WebHID Transport implementation * @example * import TransportWebHID from "@ledgerhq/hw-transport-webhid"; * ... * TransportWebHID.create().then(transport => ...) */ class TransportWebHID extends hw_transport_1.default { device; deviceModel; channel = Math.floor(Math.random() * 0xffff); packetSize = 64; constructor(device) { super(); this.device = device; this.deviceModel = typeof device.productId === "number" ? (0, devices_1.identifyUSBProductId)(device.productId) : undefined; device.addEventListener("inputreport", this.onInputReport); } inputs = []; inputCallback; read = () => { if (this.inputs.length) { return Promise.resolve(this.inputs.shift()); } return new Promise(success => { this.inputCallback = success; }); }; onInputReport = (e) => { const buffer = Buffer.from(e.data.buffer); if (this.inputCallback) { this.inputCallback(buffer); this.inputCallback = null; } else { this.inputs.push(buffer); } }; /** * Check if WebUSB transport is supported. */ static isSupported = isSupported; /** * List the WebUSB devices that was previously authorized by the user. */ static list = getLedgerDevices; /** * Actively listen to WebUSB devices and emit ONE device * that was either accepted before, if not it will trigger the native permission UI. * * Important: it must be called in the context of a UI click! */ static listen = (observer) => { let unsubscribed = false; getFirstLedgerDevice().then(device => { if (!device) { observer.error(new errors_1.TransportOpenUserCancelled("Access denied to use Ledger device")); } else if (!unsubscribed) { const deviceModel = typeof device.productId === "number" ? (0, devices_1.identifyUSBProductId)(device.productId) : undefined; observer.next({ type: "add", descriptor: device, deviceModel, }); observer.complete(); } }, error => { observer.error(new errors_1.TransportOpenUserCancelled(error.message)); }); function unsubscribe() { unsubscribed = true; } return { unsubscribe, }; }; /** * Similar to create() except it will always display the device permission (even if some devices are already accepted). */ static async request() { const [device] = await requestLedgerDevices(); return TransportWebHID.open(device); } /** * Similar to create() except it will never display the device permission (it returns a Promise<?Transport>, null if it fails to find a device). */ static async openConnected() { const devices = await getLedgerDevices(); if (devices.length === 0) return null; return TransportWebHID.open(devices[0]); } /** * Create a Ledger transport with a HIDDevice */ static async open(device) { await device.open(); const transport = new TransportWebHID(device); const onDisconnect = e => { if (device === e.device) { getHID().removeEventListener("disconnect", onDisconnect); transport._emitDisconnect(new errors_1.DisconnectedDevice()); } }; getHID().addEventListener("disconnect", onDisconnect); return transport; } _disconnectEmitted = false; _emitDisconnect = (e) => { if (this._disconnectEmitted) return; this._disconnectEmitted = true; this.emit("disconnect", e); }; /** * Release the transport device */ async close() { await this.exchangeBusyPromise; this.device.removeEventListener("inputreport", this.onInputReport); await this.device.close(); } /** * Exchange with the device using APDU protocol. * @param apdu * @returns a promise of apdu response */ exchange = async (apdu) => { const b = await this.exchangeAtomicImpl(async () => { const { channel, packetSize } = this; (0, logs_1.log)("apdu", "=> " + apdu.toString("hex")); const framing = (0, hid_framing_1.default)(channel, packetSize); // Write... const blocks = framing.makeBlocks(apdu); for (let i = 0; i < blocks.length; i++) { await this.device.sendReport(0, blocks[i]); } // Read... let result; let acc; while (!(result = framing.getReducedResult(acc))) { try { const buffer = await this.read(); acc = framing.reduceResponse(acc, buffer); } catch (e) { if (e instanceof errors_1.TransportError && e.id === "InvalidChannel") { // this can happen if the device is connected // on a different channel (like another app) // in this case we just filter out the event continue; } throw e; } } (0, logs_1.log)("apdu", "<= " + result.toString("hex")); return result; }).catch(e => { if (e && e.message && e.message.includes("write")) { this._emitDisconnect(e); throw new errors_1.DisconnectedDeviceDuringOperation(e.message); } throw e; }); return b; }; setScrambleKey() { } } exports.TransportWebHID = TransportWebHID; exports.default = TransportWebHID; //# sourceMappingURL=TransportWebHID.js.map