-
Notifications
You must be signed in to change notification settings - Fork 353
/
TransportWebHID.ts
249 lines (217 loc) · 6.48 KB
/
TransportWebHID.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
import Transport from "@ledgerhq/hw-transport";
import type {
Observer,
DescriptorEvent,
Subscription,
} from "@ledgerhq/hw-transport";
import hidFraming from "@ledgerhq/devices/hid-framing";
import { identifyUSBProductId, ledgerUSBVendorId } from "@ledgerhq/devices";
import type { DeviceModel } from "@ledgerhq/devices";
import { log } from "@ledgerhq/logs";
import {
TransportOpenUserCancelled,
DisconnectedDeviceDuringOperation,
DisconnectedDevice,
TransportError,
} from "@ledgerhq/errors";
const ledgerDevices = [
{
vendorId: ledgerUSBVendorId,
},
];
const isSupported = () =>
Promise.resolve(!!(window.navigator && window.navigator.hid));
const getHID = (): HID => {
// $FlowFixMe
const { hid } = navigator;
if (!hid)
throw new TransportError(
"navigator.hid is not supported",
"HIDNotSupported"
);
return hid;
};
async function requestLedgerDevices(): Promise<HIDDevice[]> {
const device = await getHID().requestDevice({
filters: ledgerDevices,
});
if (Array.isArray(device)) return device;
return [device];
}
async function getLedgerDevices(): Promise<HIDDevice[]> {
const devices = await getHID().getDevices();
return devices.filter((d) => d.vendorId === ledgerUSBVendorId);
}
async function getFirstLedgerDevice(): Promise<HIDDevice> {
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 => ...)
*/
export default class TransportWebHID extends Transport {
device: HIDDevice;
deviceModel: DeviceModel | null | undefined;
channel = Math.floor(Math.random() * 0xffff);
packetSize = 64;
constructor(device: HIDDevice) {
super();
this.device = device;
this.deviceModel =
typeof device.productId === "number"
? identifyUSBProductId(device.productId)
: undefined;
device.addEventListener("inputreport", this.onInputReport);
}
inputs: Buffer[] = [];
inputCallback: ((arg0: Buffer) => void) | null | undefined;
read = (): Promise<Buffer> => {
if (this.inputs.length) {
return Promise.resolve(this.inputs.shift() as unknown as Buffer);
}
return new Promise((success) => {
this.inputCallback = success;
});
};
onInputReport = (e: HIDInputReportEvent) => {
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: Observer<DescriptorEvent<HIDDevice>>
): Subscription => {
let unsubscribed = false;
getFirstLedgerDevice().then(
(device) => {
if (!device) {
observer.error(
new TransportOpenUserCancelled("Access denied to use Ledger device")
);
} else if (!unsubscribed) {
const deviceModel =
typeof device.productId === "number"
? identifyUSBProductId(device.productId)
: undefined;
observer.next({
type: "add",
descriptor: device,
deviceModel,
});
observer.complete();
}
},
(error) => {
observer.error(new 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: HIDDevice) {
await device.open();
const transport = new TransportWebHID(device);
const onDisconnect = (e) => {
if (device === e.device) {
getHID().removeEventListener("disconnect", onDisconnect);
transport._emitDisconnect(new DisconnectedDevice());
}
};
getHID().addEventListener("disconnect", onDisconnect);
return transport;
}
_disconnectEmitted = false;
_emitDisconnect = (e: Error) => {
if (this._disconnectEmitted) return;
this._disconnectEmitted = true;
this.emit("disconnect", e);
};
/**
* Release the transport device
*/
async close(): Promise<void> {
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: Buffer): Promise<Buffer> => {
const b = await this.exchangeAtomicImpl(async () => {
const { channel, packetSize } = this;
log("apdu", "=> " + apdu.toString("hex"));
const framing = hidFraming(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))) {
const buffer = await this.read();
acc = framing.reduceResponse(acc, buffer);
}
log("apdu", "<= " + result.toString("hex"));
return result;
}).catch((e) => {
if (e && e.message && e.message.includes("write")) {
this._emitDisconnect(e);
throw new DisconnectedDeviceDuringOperation(e.message);
}
throw e;
});
return b as Buffer;
};
setScrambleKey() {}
}