@onekeyfe/hd-transport-web-device 1.2.0-alpha.15 → 1.2.0-alpha.151
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/__tests__/electron-ble-transport.test.ts +439 -27
- package/__tests__/webusb-protocol-cache.test.ts +244 -0
- package/__tests__/webusb-protocol-v2-timeout.test.ts +363 -11
- package/dist/ble-packet-capacity.d.ts +2 -0
- package/dist/ble-packet-capacity.d.ts.map +1 -0
- package/dist/electron-ble-transport.d.ts +17 -3
- package/dist/electron-ble-transport.d.ts.map +1 -1
- package/dist/index.d.ts +146 -12
- package/dist/index.js +428 -281
- package/dist/transportLog.d.ts +1 -6
- package/dist/transportLog.d.ts.map +1 -1
- package/dist/webusb.d.ts +20 -10
- package/dist/webusb.d.ts.map +1 -1
- package/jest.config.js +5 -0
- package/package.json +6 -5
- package/src/ble-packet-capacity.ts +13 -0
- package/src/electron-ble-transport.ts +252 -115
- package/src/transportLog.ts +1 -11
- package/src/webusb.ts +305 -204
package/src/webusb.ts
CHANGED
|
@@ -6,25 +6,27 @@ import transport, {
|
|
|
6
6
|
PROTOCOL_V1_USB_PACKET_SIZE,
|
|
7
7
|
PROTOCOL_V2_CHANNEL_USB,
|
|
8
8
|
PROTOCOL_V2_FRAME_MAX_BYTES,
|
|
9
|
-
|
|
10
|
-
|
|
9
|
+
ProtocolV2LinkError,
|
|
10
|
+
ProtocolV2UsbTransportBase,
|
|
11
11
|
probeProtocolV2 as probeProtocolV2Helper,
|
|
12
12
|
} from '@onekeyfe/hd-transport';
|
|
13
13
|
import {
|
|
14
14
|
ERRORS,
|
|
15
15
|
HardwareErrorCode,
|
|
16
16
|
ONEKEY_WEBUSB_FILTER,
|
|
17
|
+
inferProtocolHintFromUsbId,
|
|
17
18
|
isKnownTrezorWebUsbDevice,
|
|
19
|
+
resolveOneKeyUsbDevicePath,
|
|
18
20
|
wait,
|
|
19
21
|
} from '@onekeyfe/hd-shared';
|
|
20
22
|
import ByteBuffer from 'bytebuffer';
|
|
21
23
|
|
|
22
|
-
import { createTransportCallLog, shouldSuppressHighVolumeCallLog } from './transportLog';
|
|
23
|
-
|
|
24
24
|
import type {
|
|
25
25
|
AcquireInput,
|
|
26
26
|
OneKeyDeviceInfoBase,
|
|
27
27
|
ProtocolType,
|
|
28
|
+
ProtocolV2CallContext,
|
|
29
|
+
ProtocolV2Schemas,
|
|
28
30
|
TransportCallOptions,
|
|
29
31
|
} from '@onekeyfe/hd-transport';
|
|
30
32
|
|
|
@@ -39,10 +41,12 @@ const REPORT_ID = PROTOCOL_V1_REPORT_ID;
|
|
|
39
41
|
const HEADER_LENGTH = PROTOCOL_V1_MESSAGE_HEADER_SIZE;
|
|
40
42
|
const PACKET_IO_MAX_RETRIES = 3;
|
|
41
43
|
const PACKET_IO_RETRY_DELAY = 300;
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
44
|
+
// Legacy devices can take longer to answer Initialize after a WebUSB reset.
|
|
45
|
+
// Keep this aligned with Node USB so a slow Protocol V1 response is not
|
|
46
|
+
// misreported as a protocol mismatch during acquire.
|
|
47
|
+
const PROTOCOL_V1_PROBE_TIMEOUT = 5000;
|
|
48
|
+
const PROTOCOL_V2_PROBE_TIMEOUT = 1000;
|
|
49
|
+
const EXPECTED_PROTOCOL_V2_PROBE_ATTEMPTS = 2;
|
|
46
50
|
|
|
47
51
|
/**
|
|
48
52
|
* Device information with path and WebUSB device instance
|
|
@@ -64,37 +68,61 @@ interface TransferCancelToken {
|
|
|
64
68
|
cancelled: boolean;
|
|
65
69
|
}
|
|
66
70
|
|
|
67
|
-
|
|
71
|
+
/**
|
|
72
|
+
* The navigator.usb disconnect listener is module-scoped and attached at most
|
|
73
|
+
* once: listeners on navigator.usb are global and never garbage collected, so a
|
|
74
|
+
* per-instance listener would retain every transport instance created across
|
|
75
|
+
* SDK re-initializations. Events are routed to the most recently initialized
|
|
76
|
+
* transport instance instead.
|
|
77
|
+
*/
|
|
78
|
+
let activeWebUsbTransport: WebUsbTransport | undefined;
|
|
79
|
+
let usbDisconnectListenerAttached = false;
|
|
80
|
+
|
|
81
|
+
function registerActiveWebUsbTransport(instance: WebUsbTransport, usb: USB) {
|
|
82
|
+
activeWebUsbTransport = instance;
|
|
83
|
+
if (usbDisconnectListenerAttached) return;
|
|
84
|
+
usbDisconnectListenerAttached = true;
|
|
85
|
+
usb.addEventListener('disconnect', event => {
|
|
86
|
+
if (!event.device) return;
|
|
87
|
+
const path = resolveOneKeyUsbDevicePath(event.device);
|
|
88
|
+
if (!path) return;
|
|
89
|
+
activeWebUsbTransport?.markProtocolStale(path);
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export default class WebUsbTransport extends ProtocolV2UsbTransportBase<string> {
|
|
68
94
|
messages: ReturnType<typeof transport.parseConfigure> | undefined;
|
|
69
95
|
|
|
70
96
|
/** Protobuf schema for Protocol V2 transports. */
|
|
71
97
|
messagesV2: ReturnType<typeof transport.parseConfigure> | undefined;
|
|
72
98
|
|
|
99
|
+
private protocolV2SchemaSource: string | undefined;
|
|
100
|
+
|
|
73
101
|
/** Per-path protocol type detected by active wire-level probe. */
|
|
74
102
|
private deviceProtocol: Map<string, ProtocolType> = new Map();
|
|
75
103
|
|
|
76
104
|
private deviceProtocolHints: Map<string, ProtocolType> = new Map();
|
|
77
105
|
|
|
78
|
-
/**
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
private
|
|
83
|
-
|
|
84
|
-
/** 当前 Protocol V2 调用的读取超时,由缓存 session 的 readFrame 闭包读取。 */
|
|
85
|
-
private protocolV2ReadTimeouts: Map<string, number | undefined> = new Map();
|
|
106
|
+
/**
|
|
107
|
+
* Paths whose cached protocol must be re-probed on the next acquire (a USB
|
|
108
|
+
* disconnect was seen, or a transfer-level reconnect happened mid-call).
|
|
109
|
+
*/
|
|
110
|
+
private staleProtocolPaths: Set<string> = new Set();
|
|
86
111
|
|
|
87
|
-
/**
|
|
88
|
-
private
|
|
112
|
+
/** Paths currently acquired (between a successful acquire() and its release()). */
|
|
113
|
+
private acquiredPaths: Set<string> = new Set();
|
|
89
114
|
|
|
90
115
|
/**
|
|
91
|
-
*
|
|
92
|
-
*
|
|
93
|
-
*
|
|
116
|
+
* The exact USBDevice object each cached protocol was probed against. The
|
|
117
|
+
* browser returns the same object identity for a device as long as it stays
|
|
118
|
+
* connected, and a replug/reboot always yields a new object — so an identity
|
|
119
|
+
* mismatch proves the device was re-enumerated since the probe, even when the
|
|
120
|
+
* disconnect event itself was delayed or missed.
|
|
94
121
|
*/
|
|
95
|
-
private
|
|
122
|
+
private probedDeviceObjects: Map<string, USBDevice> = new Map();
|
|
96
123
|
|
|
97
|
-
|
|
124
|
+
/** Per-path USB endpoint / interface numbers (discovered from USB descriptors) */
|
|
125
|
+
private deviceEndpoints: Map<string, DeviceEndpoints> = new Map();
|
|
98
126
|
|
|
99
127
|
name = 'WebUsbTransport';
|
|
100
128
|
|
|
@@ -118,6 +146,14 @@ export default class WebUsbTransport {
|
|
|
118
146
|
|
|
119
147
|
interfaceId = INTERFACE_ID;
|
|
120
148
|
|
|
149
|
+
constructor() {
|
|
150
|
+
super({
|
|
151
|
+
router: PROTOCOL_V2_CHANNEL_USB,
|
|
152
|
+
maxFrameBytes: PROTOCOL_V2_FRAME_MAX_BYTES,
|
|
153
|
+
logPrefix: 'ProtocolV2 WebUSB',
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
|
|
121
157
|
/**
|
|
122
158
|
* Initialize WebUSB transport
|
|
123
159
|
*/
|
|
@@ -132,6 +168,22 @@ export default class WebUsbTransport {
|
|
|
132
168
|
);
|
|
133
169
|
}
|
|
134
170
|
this.usb = usb;
|
|
171
|
+
registerActiveWebUsbTransport(this, usb);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Protocol type is a property of the physical device keyed by USB serial number.
|
|
176
|
+
* It can only change across a device reboot (e.g. normal ↔ bootloader mode), and
|
|
177
|
+
* a reboot always surfaces as a USB disconnect. Disconnects (and transfer-level
|
|
178
|
+
* reconnects, which cover a missed disconnect event) only MARK the cached probe
|
|
179
|
+
* result stale instead of deleting it: an in-flight session keeps using the old
|
|
180
|
+
* value so the transfer-level reconnect retries can absorb a transient
|
|
181
|
+
* re-enumeration exactly as they did before the cache existed, while the next
|
|
182
|
+
* acquire re-probes from scratch.
|
|
183
|
+
*/
|
|
184
|
+
markProtocolStale(path: string) {
|
|
185
|
+
this.staleProtocolPaths.add(path);
|
|
186
|
+
this.probedDeviceObjects.delete(path);
|
|
135
187
|
}
|
|
136
188
|
|
|
137
189
|
/**
|
|
@@ -147,9 +199,20 @@ export default class WebUsbTransport {
|
|
|
147
199
|
* Cache the Protocol V2 protobuf schema.
|
|
148
200
|
*/
|
|
149
201
|
configureProtocolV2(signedData: any) {
|
|
202
|
+
const schemaSource =
|
|
203
|
+
typeof signedData === 'string'
|
|
204
|
+
? signedData
|
|
205
|
+
: JSON.stringify(signedData) ?? String(signedData);
|
|
206
|
+
if (schemaSource === this.protocolV2SchemaSource) return;
|
|
207
|
+
|
|
208
|
+
const hadProtocolV2Schema = this.protocolV2SchemaSource !== undefined;
|
|
150
209
|
this.messagesV2 = parseConfigure(signedData);
|
|
151
|
-
this.
|
|
152
|
-
|
|
210
|
+
this.protocolV2SchemaSource = schemaSource;
|
|
211
|
+
if (!hadProtocolV2Schema) return;
|
|
212
|
+
|
|
213
|
+
this.invalidateAllProtocolV2UsbLinks('Protocol V2 schema reconfigured').catch(error =>
|
|
214
|
+
this.Log?.debug('[WebUsbTransport] schema link cleanup failed:', error)
|
|
215
|
+
);
|
|
153
216
|
}
|
|
154
217
|
|
|
155
218
|
/**
|
|
@@ -181,26 +244,6 @@ export default class WebUsbTransport {
|
|
|
181
244
|
return this.deviceList;
|
|
182
245
|
}
|
|
183
246
|
|
|
184
|
-
/**
|
|
185
|
-
* 设备 path:正常设备直接用 USB serial number;
|
|
186
|
-
* 空 serial(早期工程板)回退到会话内稳定的 mock path。
|
|
187
|
-
*/
|
|
188
|
-
private getDevicePath(device: USBDevice): string {
|
|
189
|
-
if (typeof device.serialNumber === 'string' && device.serialNumber.length > 0) {
|
|
190
|
-
return device.serialNumber;
|
|
191
|
-
}
|
|
192
|
-
let path = this.mockSerialPaths.get(device);
|
|
193
|
-
if (!path) {
|
|
194
|
-
this.mockSerialCounter += 1;
|
|
195
|
-
path = `mock-serial:${device.vendorId.toString(16)}:${device.productId.toString(16)}:${
|
|
196
|
-
this.mockSerialCounter
|
|
197
|
-
}`;
|
|
198
|
-
this.mockSerialPaths.set(device, path);
|
|
199
|
-
this.Log?.debug(`[WebUSB] device has no serial number, using mock path: ${path}`);
|
|
200
|
-
}
|
|
201
|
-
return path;
|
|
202
|
-
}
|
|
203
|
-
|
|
204
247
|
/**
|
|
205
248
|
* Get list of connected devices
|
|
206
249
|
*/
|
|
@@ -216,18 +259,21 @@ export default class WebUsbTransport {
|
|
|
216
259
|
return isOneKey && !isKnownTrezorWebUsbDevice(dev);
|
|
217
260
|
});
|
|
218
261
|
|
|
219
|
-
this.deviceList = onekeyDevices.
|
|
220
|
-
const path =
|
|
221
|
-
|
|
262
|
+
this.deviceList = onekeyDevices.flatMap(device => {
|
|
263
|
+
const path = resolveOneKeyUsbDevicePath(device);
|
|
264
|
+
if (!path) return [];
|
|
265
|
+
const protocolHint = inferProtocolHintFromUsbId(device.vendorId, device.productId);
|
|
222
266
|
if (protocolHint) {
|
|
223
267
|
this.deviceProtocolHints.set(path, protocolHint);
|
|
224
268
|
}
|
|
225
269
|
|
|
226
|
-
return
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
270
|
+
return [
|
|
271
|
+
{
|
|
272
|
+
path,
|
|
273
|
+
device,
|
|
274
|
+
commType: 'webusb',
|
|
275
|
+
},
|
|
276
|
+
];
|
|
231
277
|
});
|
|
232
278
|
|
|
233
279
|
return this.deviceList;
|
|
@@ -239,20 +285,60 @@ export default class WebUsbTransport {
|
|
|
239
285
|
async acquire(input: AcquireInput) {
|
|
240
286
|
if (!input.path) return;
|
|
241
287
|
try {
|
|
288
|
+
await this.rotateProtocolV2UsbGeneration(input.path, 'WebUSB transport acquired');
|
|
242
289
|
await this.closeOpenDevice(input.path);
|
|
243
290
|
await this.connect(input.path ?? '', true);
|
|
244
|
-
|
|
245
|
-
.
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
this.deviceProtocolHints.
|
|
291
|
+
if (input.forceProtocolDetection) {
|
|
292
|
+
// Explicit recovery/discovery (e.g. detectDeviceConnectProtocol) must
|
|
293
|
+
// probe on the wire regardless of any cached result — the cached
|
|
294
|
+
// binding may be exactly what the caller is trying to recover from.
|
|
295
|
+
this.staleProtocolPaths.delete(input.path);
|
|
296
|
+
this.deviceProtocol.delete(input.path);
|
|
297
|
+
this.deviceProtocolHints.delete(input.path);
|
|
298
|
+
}
|
|
299
|
+
if (this.staleProtocolPaths.has(input.path)) {
|
|
300
|
+
// The device disconnected (possibly rebooting into another mode) since
|
|
301
|
+
// the protocol was probed — drop the cache so it is re-probed below.
|
|
302
|
+
this.staleProtocolPaths.delete(input.path);
|
|
303
|
+
this.deviceProtocol.delete(input.path);
|
|
304
|
+
}
|
|
305
|
+
if (this.deviceProtocol.has(input.path)) {
|
|
306
|
+
const currentDevice = this.deviceList.find(d => d.path === input.path)?.device;
|
|
307
|
+
if (!currentDevice || currentDevice !== this.probedDeviceObjects.get(input.path)) {
|
|
308
|
+
// The OS re-enumerated the device since the probe (a replug/reboot we
|
|
309
|
+
// may not have seen a disconnect event for) — the cached protocol can
|
|
310
|
+
// no longer be trusted; re-probe on the wire below.
|
|
311
|
+
this.deviceProtocol.delete(input.path);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
const cachedProtocol = this.deviceProtocol.get(input.path);
|
|
315
|
+
if (cachedProtocol && input.expectedProtocol && cachedProtocol !== input.expectedProtocol) {
|
|
316
|
+
// The caller expects a different protocol than the cached probe result;
|
|
317
|
+
// the cache is stale — drop it and re-probe on the wire below.
|
|
318
|
+
this.deviceProtocol.delete(input.path);
|
|
319
|
+
}
|
|
320
|
+
if (!this.deviceProtocol.has(input.path)) {
|
|
321
|
+
const usbDevice = this.deviceList.find(device => device.path === input.path)?.device;
|
|
322
|
+
const protocolHint = input.expectedProtocol
|
|
323
|
+
? undefined
|
|
324
|
+
: input.protocolHint ??
|
|
325
|
+
this.deviceProtocolHints.get(input.path) ??
|
|
326
|
+
inferProtocolHintFromUsbId(usbDevice?.vendorId, usbDevice?.productId);
|
|
327
|
+
if (protocolHint) {
|
|
328
|
+
this.deviceProtocolHints.set(input.path, protocolHint);
|
|
329
|
+
}
|
|
330
|
+
await this.detectProtocol(input.path, input.expectedProtocol, protocolHint);
|
|
331
|
+
const probedDevice = this.deviceList.find(d => d.path === input.path)?.device;
|
|
332
|
+
if (probedDevice) {
|
|
333
|
+
this.probedDeviceObjects.set(input.path, probedDevice);
|
|
334
|
+
}
|
|
251
335
|
}
|
|
252
|
-
|
|
336
|
+
this.acquiredPaths.add(input.path);
|
|
253
337
|
return await Promise.resolve(input.path);
|
|
254
338
|
} catch (e) {
|
|
255
339
|
this.Log.debug('acquire error: ', e instanceof Error ? `${e.name}: ${e.message}` : String(e));
|
|
340
|
+
this.acquiredPaths.delete(input.path);
|
|
341
|
+
await this.closeOpenDevice(input.path);
|
|
256
342
|
throw e;
|
|
257
343
|
}
|
|
258
344
|
}
|
|
@@ -269,13 +355,17 @@ export default class WebUsbTransport {
|
|
|
269
355
|
);
|
|
270
356
|
}
|
|
271
357
|
|
|
272
|
-
private
|
|
358
|
+
private createProtocolProbeTimeoutError(expected: ProtocolType, attempts: number) {
|
|
273
359
|
return ERRORS.TypedError(
|
|
274
|
-
HardwareErrorCode.
|
|
275
|
-
|
|
360
|
+
HardwareErrorCode.DeviceInitializeFailed,
|
|
361
|
+
`Protocol ${expected} probe timeout after ${attempts} attempts`
|
|
276
362
|
);
|
|
277
363
|
}
|
|
278
364
|
|
|
365
|
+
private createProtocolDetectionError() {
|
|
366
|
+
return ERRORS.TypedError(HardwareErrorCode.DeviceNotFound);
|
|
367
|
+
}
|
|
368
|
+
|
|
279
369
|
private async detectProtocol(
|
|
280
370
|
path: string,
|
|
281
371
|
expectedProtocol?: ProtocolType,
|
|
@@ -286,29 +376,54 @@ export default class WebUsbTransport {
|
|
|
286
376
|
this.deviceProtocol.set(path, 'V1');
|
|
287
377
|
return 'V1';
|
|
288
378
|
}
|
|
379
|
+
await this.closeConnectionAfterProbe(path);
|
|
289
380
|
throw this.createProtocolMismatchError(expectedProtocol);
|
|
290
381
|
}
|
|
291
382
|
|
|
292
383
|
if (expectedProtocol === 'V2') {
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
384
|
+
for (let attempt = 1; attempt <= EXPECTED_PROTOCOL_V2_PROBE_ATTEMPTS; attempt += 1) {
|
|
385
|
+
if (await this.probeProtocolV2(path)) {
|
|
386
|
+
this.deviceProtocol.set(path, 'V2');
|
|
387
|
+
return 'V2';
|
|
388
|
+
}
|
|
389
|
+
if (attempt < EXPECTED_PROTOCOL_V2_PROBE_ATTEMPTS) {
|
|
390
|
+
await this.resetConnectionAfterProbe(path);
|
|
391
|
+
this.Log?.debug(
|
|
392
|
+
`[WebUsbTransport] Protocol V2 probe timed out, retrying ${
|
|
393
|
+
attempt + 1
|
|
394
|
+
}/${EXPECTED_PROTOCOL_V2_PROBE_ATTEMPTS}`
|
|
395
|
+
);
|
|
396
|
+
} else {
|
|
397
|
+
await this.closeConnectionAfterProbe(path);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
this.deviceProtocol.delete(path);
|
|
401
|
+
throw this.createProtocolProbeTimeoutError(
|
|
402
|
+
expectedProtocol,
|
|
403
|
+
EXPECTED_PROTOCOL_V2_PROBE_ATTEMPTS
|
|
404
|
+
);
|
|
297
405
|
}
|
|
298
406
|
|
|
299
|
-
//
|
|
300
|
-
//
|
|
301
|
-
// 不能作为最终结论。
|
|
407
|
+
// Protocol must be actively probed after connection. Name, PID, and descriptors only
|
|
408
|
+
// influence probe order; a V2 hint probes V2 first and falls back to V1.
|
|
302
409
|
const probeOrder: ProtocolType[] =
|
|
303
410
|
protocolHint === 'V2' || this.deviceProtocol.get(path) === 'V2' ? ['V2', 'V1'] : ['V1', 'V2'];
|
|
304
411
|
|
|
305
|
-
for (const protocol of probeOrder) {
|
|
412
|
+
for (const [index, protocol] of probeOrder.entries()) {
|
|
306
413
|
const detected =
|
|
307
414
|
protocol === 'V1' ? await this.probeProtocolV1(path) : await this.probeProtocolV2(path);
|
|
308
415
|
if (detected) {
|
|
309
416
|
this.deviceProtocol.set(path, protocol);
|
|
310
417
|
return protocol;
|
|
311
418
|
}
|
|
419
|
+
if (index < probeOrder.length - 1) {
|
|
420
|
+
// A timed-out WebUSB transferIn cannot be cancelled in place. Closing and
|
|
421
|
+
// reopening the device guarantees the next protocol probe cannot consume a
|
|
422
|
+
// late response from the previous protocol generation.
|
|
423
|
+
await this.resetConnectionAfterProbe(path);
|
|
424
|
+
} else {
|
|
425
|
+
await this.closeConnectionAfterProbe(path);
|
|
426
|
+
}
|
|
312
427
|
}
|
|
313
428
|
|
|
314
429
|
this.deviceProtocol.delete(path);
|
|
@@ -420,16 +535,12 @@ export default class WebUsbTransport {
|
|
|
420
535
|
// Discover endpoints from USB descriptors; descriptors are not used for protocol selection.
|
|
421
536
|
const endpoints = this.discoverEndpoints(device);
|
|
422
537
|
this.deviceEndpoints.set(path, endpoints);
|
|
423
|
-
this.protocolV2Assemblers.get(path)?.reset();
|
|
424
|
-
this.protocolV2Assemblers.set(path, new ProtocolV2FrameAssembler(PROTOCOL_V2_FRAME_MAX_BYTES));
|
|
425
|
-
|
|
426
538
|
await device.claimInterface(endpoints.interfaceNumber);
|
|
427
539
|
await this.clearEndpointHalt(device, 'in', endpoints.endpointIn);
|
|
428
540
|
await this.clearEndpointHalt(device, 'out', endpoints.endpointOut);
|
|
429
541
|
}
|
|
430
542
|
|
|
431
543
|
private async closeOpenDevice(path: string) {
|
|
432
|
-
this.protocolV2Assemblers.get(path)?.reset();
|
|
433
544
|
const current = this.deviceList.find(device => device.path === path)?.device;
|
|
434
545
|
if (!current?.opened) return;
|
|
435
546
|
|
|
@@ -462,7 +573,25 @@ export default class WebUsbTransport {
|
|
|
462
573
|
}
|
|
463
574
|
}
|
|
464
575
|
|
|
576
|
+
/**
|
|
577
|
+
* With the protocol cache surviving release(), deviceProtocol presence no
|
|
578
|
+
* longer implies an active session. Guard call()/post() explicitly so a
|
|
579
|
+
* post-release straggler fails fast instead of silently reopening the device
|
|
580
|
+
* and driving it outside any session (pre-cache behavior: the deleted
|
|
581
|
+
* protocol entry produced the same fail-fast).
|
|
582
|
+
*/
|
|
583
|
+
private assertAcquired(path: string) {
|
|
584
|
+
if (!this.acquiredPaths.has(path)) {
|
|
585
|
+
throw ERRORS.TypedError(HardwareErrorCode.RuntimeError, `Device is not acquired for ${path}`);
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
|
|
465
589
|
async post(session: string, name: string, data: Record<string, unknown>) {
|
|
590
|
+
this.assertAcquired(session);
|
|
591
|
+
if (this.deviceProtocol.get(session) === 'V2') {
|
|
592
|
+
await this.sendProtocolV2UsbFlowControl(session, name, data);
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
466
595
|
await this.call(session, name, data);
|
|
467
596
|
}
|
|
468
597
|
|
|
@@ -500,6 +629,11 @@ export default class WebUsbTransport {
|
|
|
500
629
|
error
|
|
501
630
|
)}`
|
|
502
631
|
);
|
|
632
|
+
// The device dropped off the bus mid-call and may have rebooted into a
|
|
633
|
+
// different mode. The in-flight retry keeps the known protocol, but the
|
|
634
|
+
// next acquire must re-probe — this also self-heals a stale cache when the
|
|
635
|
+
// USB disconnect event itself was missed.
|
|
636
|
+
this.staleProtocolPaths.add(path);
|
|
503
637
|
await wait(attempt * PACKET_IO_RETRY_DELAY);
|
|
504
638
|
|
|
505
639
|
try {
|
|
@@ -624,33 +758,30 @@ export default class WebUsbTransport {
|
|
|
624
758
|
throw lastError;
|
|
625
759
|
}
|
|
626
760
|
|
|
627
|
-
private async
|
|
628
|
-
this.
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
try {
|
|
633
|
-
const device = await this.findDevice(path);
|
|
634
|
-
if (device.opened) {
|
|
635
|
-
const endpoints = this.deviceEndpoints.get(path);
|
|
636
|
-
const ifaceNum = endpoints?.interfaceNumber ?? this.interfaceId;
|
|
637
|
-
try {
|
|
638
|
-
await device.releaseInterface(ifaceNum);
|
|
639
|
-
} catch (error) {
|
|
640
|
-
this.Log.debug('[WebUsbTransport] releaseInterface after protocol probe error:', error);
|
|
641
|
-
}
|
|
642
|
-
await device.close();
|
|
643
|
-
}
|
|
644
|
-
} catch (error) {
|
|
645
|
-
this.Log.debug('[WebUsbTransport] close after protocol probe error:', error);
|
|
761
|
+
private async transferInOnce(path: string, length: number): Promise<DataView> {
|
|
762
|
+
const device = await this.findDevice(path);
|
|
763
|
+
if (!device.opened) {
|
|
764
|
+
throw new Error('USBDevice is not open for transferIn');
|
|
646
765
|
}
|
|
766
|
+
const endpoints = this.deviceEndpoints.get(path);
|
|
767
|
+
const endpointIn = endpoints?.endpointIn ?? this.endpointId;
|
|
768
|
+
const result = await device.transferIn(endpointIn, length);
|
|
769
|
+
return this.getTransferInData(result);
|
|
770
|
+
}
|
|
647
771
|
|
|
772
|
+
private async closeConnectionAfterProbe(path: string) {
|
|
773
|
+
await this.rotateProtocolV2UsbGeneration(path, 'WebUSB protocol probe reset');
|
|
774
|
+
await this.closeOpenDevice(path);
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
private async resetConnectionAfterProbe(path: string) {
|
|
778
|
+
await this.closeConnectionAfterProbe(path);
|
|
648
779
|
await this.getConnectedDevices();
|
|
649
780
|
await this.connect(path, false);
|
|
650
781
|
}
|
|
651
782
|
|
|
652
783
|
private async withProtocolReadTimeout<T>(
|
|
653
|
-
|
|
784
|
+
path: string,
|
|
654
785
|
promise: Promise<T>,
|
|
655
786
|
timeoutMs: number,
|
|
656
787
|
protocol: ProtocolType,
|
|
@@ -672,9 +803,16 @@ export default class WebUsbTransport {
|
|
|
672
803
|
return await Promise.race([
|
|
673
804
|
guardedPromise,
|
|
674
805
|
new Promise<never>((_, reject) => {
|
|
675
|
-
timer = setTimeout(() => {
|
|
806
|
+
timer = setTimeout(async () => {
|
|
676
807
|
timedOut = true;
|
|
677
808
|
onTimeout?.();
|
|
809
|
+
if (protocol === 'V1') {
|
|
810
|
+
try {
|
|
811
|
+
await this.resetConnectionAfterProbe(path);
|
|
812
|
+
} catch (error) {
|
|
813
|
+
this.Log.debug('[WebUsbTransport] reset after Protocol V1 timeout failed:', error);
|
|
814
|
+
}
|
|
815
|
+
}
|
|
678
816
|
reject(new Error(`Protocol ${protocol} read timeout after ${timeoutMs}ms`));
|
|
679
817
|
}, timeoutMs);
|
|
680
818
|
}),
|
|
@@ -690,7 +828,14 @@ export default class WebUsbTransport {
|
|
|
690
828
|
}
|
|
691
829
|
|
|
692
830
|
try {
|
|
693
|
-
await this.callProtocolV1(
|
|
831
|
+
await this.callProtocolV1(
|
|
832
|
+
path,
|
|
833
|
+
'Initialize',
|
|
834
|
+
{},
|
|
835
|
+
{
|
|
836
|
+
timeoutMs: PROTOCOL_V1_PROBE_TIMEOUT,
|
|
837
|
+
}
|
|
838
|
+
);
|
|
694
839
|
return true;
|
|
695
840
|
} catch (_error) {
|
|
696
841
|
return false;
|
|
@@ -704,10 +849,9 @@ export default class WebUsbTransport {
|
|
|
704
849
|
|
|
705
850
|
return probeProtocolV2Helper({
|
|
706
851
|
call: (name, data, options) => this.callProtocolV2(path, name, data, options),
|
|
707
|
-
timeoutMs:
|
|
852
|
+
timeoutMs: PROTOCOL_V2_PROBE_TIMEOUT,
|
|
708
853
|
logger: this.Log,
|
|
709
854
|
logPrefix: 'ProtocolV2 WebUSB',
|
|
710
|
-
onProbeFailed: () => this.resetConnectionAfterProbe(path),
|
|
711
855
|
});
|
|
712
856
|
}
|
|
713
857
|
|
|
@@ -723,6 +867,7 @@ export default class WebUsbTransport {
|
|
|
723
867
|
if (this.messages == null) {
|
|
724
868
|
throw ERRORS.TypedError(HardwareErrorCode.TransportNotConfigured);
|
|
725
869
|
}
|
|
870
|
+
this.assertAcquired(path);
|
|
726
871
|
|
|
727
872
|
const device = await this.findDevice(path);
|
|
728
873
|
if (!device) {
|
|
@@ -737,10 +882,6 @@ export default class WebUsbTransport {
|
|
|
737
882
|
);
|
|
738
883
|
}
|
|
739
884
|
|
|
740
|
-
if (!shouldSuppressHighVolumeCallLog(name)) {
|
|
741
|
-
this.Log.debug('transport call', createTransportCallLog(name, protocol));
|
|
742
|
-
}
|
|
743
|
-
|
|
744
885
|
if (protocol === 'V2') {
|
|
745
886
|
return this.callProtocolV2(path, name, data, options);
|
|
746
887
|
}
|
|
@@ -788,94 +929,7 @@ export default class WebUsbTransport {
|
|
|
788
929
|
data: Record<string, unknown>,
|
|
789
930
|
options?: TransportCallOptions
|
|
790
931
|
) {
|
|
791
|
-
|
|
792
|
-
if (!this.messagesV2) {
|
|
793
|
-
throw ERRORS.TypedError(
|
|
794
|
-
HardwareErrorCode.TransportNotConfigured,
|
|
795
|
-
'Protocol V2 schema not configured'
|
|
796
|
-
);
|
|
797
|
-
}
|
|
798
|
-
if (!protocolV1Messages) {
|
|
799
|
-
throw ERRORS.TypedError(HardwareErrorCode.TransportNotConfigured);
|
|
800
|
-
}
|
|
801
|
-
|
|
802
|
-
let session = this.protocolV2Sessions.get(path);
|
|
803
|
-
if (!session) {
|
|
804
|
-
session = new ProtocolV2Session({
|
|
805
|
-
schemas: {
|
|
806
|
-
protocolV1: protocolV1Messages,
|
|
807
|
-
protocolV2: this.messagesV2,
|
|
808
|
-
},
|
|
809
|
-
router: PROTOCOL_V2_CHANNEL_USB,
|
|
810
|
-
writeFrame: (frame: Uint8Array) => this.transferOutOnce(path, frame),
|
|
811
|
-
readFrame: () => this.receiveProtocolV2Frame(path, this.protocolV2ReadTimeouts.get(path)),
|
|
812
|
-
logger: this.Log,
|
|
813
|
-
logPrefix: 'ProtocolV2 WebUSB',
|
|
814
|
-
createTimeoutError: (messageName: string, timeoutMs: number) =>
|
|
815
|
-
new Error(`Protocol V2 response timeout after ${timeoutMs}ms for ${messageName}`),
|
|
816
|
-
});
|
|
817
|
-
this.protocolV2Sessions.set(path, session);
|
|
818
|
-
}
|
|
819
|
-
|
|
820
|
-
this.protocolV2ReadTimeouts.set(path, options?.timeoutMs);
|
|
821
|
-
this.protocolV2Assemblers.get(path)?.reset();
|
|
822
|
-
try {
|
|
823
|
-
return await session.call(name, data, options);
|
|
824
|
-
} catch (error) {
|
|
825
|
-
const message =
|
|
826
|
-
error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();
|
|
827
|
-
if (message.includes('protocol v2 read timeout') || message.includes('response timeout')) {
|
|
828
|
-
try {
|
|
829
|
-
await this.resetConnectionAfterProbe(path);
|
|
830
|
-
} catch (resetError) {
|
|
831
|
-
this.Log.debug('[WebUsbTransport] Protocol V2 timeout reset failed:', resetError);
|
|
832
|
-
}
|
|
833
|
-
}
|
|
834
|
-
throw error;
|
|
835
|
-
} finally {
|
|
836
|
-
this.protocolV2ReadTimeouts.delete(path);
|
|
837
|
-
}
|
|
838
|
-
}
|
|
839
|
-
|
|
840
|
-
private async receiveProtocolV2Frame(path: string, timeoutMs?: number): Promise<Uint8Array> {
|
|
841
|
-
let assembler = this.protocolV2Assemblers.get(path);
|
|
842
|
-
if (!assembler) {
|
|
843
|
-
assembler = new ProtocolV2FrameAssembler(PROTOCOL_V2_FRAME_MAX_BYTES);
|
|
844
|
-
this.protocolV2Assemblers.set(path, assembler);
|
|
845
|
-
}
|
|
846
|
-
|
|
847
|
-
let frame: Uint8Array | undefined = assembler.push(new Uint8Array(0));
|
|
848
|
-
const deadline = timeoutMs ? Date.now() + timeoutMs : undefined;
|
|
849
|
-
|
|
850
|
-
while (!frame) {
|
|
851
|
-
const cancelToken = { cancelled: false };
|
|
852
|
-
const transferIn = this.transferInWithRetry(path, PROTOCOL_V2_FRAME_MAX_BYTES, cancelToken);
|
|
853
|
-
const dataView = deadline
|
|
854
|
-
? await this.withProtocolReadTimeout(
|
|
855
|
-
path,
|
|
856
|
-
transferIn,
|
|
857
|
-
Math.max(deadline - Date.now(), 1),
|
|
858
|
-
'V2',
|
|
859
|
-
() => {
|
|
860
|
-
cancelToken.cancelled = true;
|
|
861
|
-
}
|
|
862
|
-
)
|
|
863
|
-
: await transferIn;
|
|
864
|
-
const bytes = new Uint8Array(
|
|
865
|
-
this.toArrayBuffer(
|
|
866
|
-
dataView.buffer.slice(dataView.byteOffset, dataView.byteOffset + dataView.byteLength)
|
|
867
|
-
)
|
|
868
|
-
);
|
|
869
|
-
try {
|
|
870
|
-
frame = assembler.push(bytes);
|
|
871
|
-
} catch (error) {
|
|
872
|
-
throw ERRORS.TypedError(
|
|
873
|
-
HardwareErrorCode.NetworkError,
|
|
874
|
-
error instanceof Error ? error.message : String(error)
|
|
875
|
-
);
|
|
876
|
-
}
|
|
877
|
-
}
|
|
878
|
-
return frame;
|
|
932
|
+
return this.callProtocolV2Usb(path, name, data, options);
|
|
879
933
|
}
|
|
880
934
|
|
|
881
935
|
/**
|
|
@@ -930,20 +984,67 @@ export default class WebUsbTransport {
|
|
|
930
984
|
* Release device
|
|
931
985
|
*/
|
|
932
986
|
async release(path: string) {
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
this.protocolV2Assemblers.delete(path);
|
|
942
|
-
this.protocolV2Sessions.delete(path);
|
|
943
|
-
this.protocolV2ReadTimeouts.delete(path);
|
|
987
|
+
this.acquiredPaths.delete(path);
|
|
988
|
+
await this.invalidateProtocolV2UsbLink(path, 'WebUSB transport released');
|
|
989
|
+
await this.closeOpenDevice(path);
|
|
990
|
+
// Keep deviceProtocol/deviceProtocolHints across release: the probe result is a
|
|
991
|
+
// physical-device property, so the next acquire can skip the wire-level probe.
|
|
992
|
+
// V2 entries are still dropped by onProtocolV2UsbLinkInvalidated via the link
|
|
993
|
+
// invalidation above, and any entry is re-probed after a USB disconnect or a
|
|
994
|
+
// transfer-level reconnect (see markProtocolStale).
|
|
944
995
|
this.deviceEndpoints.delete(path);
|
|
945
996
|
}
|
|
946
997
|
|
|
998
|
+
protected getProtocolV2UsbSchemas(): ProtocolV2Schemas {
|
|
999
|
+
if (!this.messages || !this.messagesV2) {
|
|
1000
|
+
throw ERRORS.TypedError(HardwareErrorCode.TransportNotConfigured);
|
|
1001
|
+
}
|
|
1002
|
+
return {
|
|
1003
|
+
protocolV1: this.messages,
|
|
1004
|
+
protocolV2: this.messagesV2,
|
|
1005
|
+
};
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
protected getProtocolV2UsbLogger() {
|
|
1009
|
+
return this.Log;
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
protected async writeProtocolV2UsbPacket(
|
|
1013
|
+
path: string,
|
|
1014
|
+
frame: Uint8Array,
|
|
1015
|
+
_context: ProtocolV2CallContext
|
|
1016
|
+
): Promise<void> {
|
|
1017
|
+
await this.transferOutOnce(path, frame);
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
protected async readProtocolV2UsbPacket(
|
|
1021
|
+
path: string,
|
|
1022
|
+
_context: ProtocolV2CallContext
|
|
1023
|
+
): Promise<Uint8Array> {
|
|
1024
|
+
const dataView = await this.transferInOnce(path, PROTOCOL_V2_FRAME_MAX_BYTES);
|
|
1025
|
+
return new Uint8Array(
|
|
1026
|
+
this.toArrayBuffer(
|
|
1027
|
+
dataView.buffer.slice(dataView.byteOffset, dataView.byteOffset + dataView.byteLength)
|
|
1028
|
+
)
|
|
1029
|
+
);
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
protected async resetProtocolV2UsbNativeLink(path: string, _reason: string): Promise<void> {
|
|
1033
|
+
await this.closeOpenDevice(path);
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
protected onProtocolV2UsbLinkInvalidated(path: string, reason: string) {
|
|
1037
|
+
this.deviceProtocol.delete(path);
|
|
1038
|
+
this.Log?.debug(`[WebUsbTransport] Protocol V2 link invalidated: ${path}`, reason);
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
protected createProtocolV2UsbTimeoutError(name: string, timeoutMs: number): Error {
|
|
1042
|
+
return new ProtocolV2LinkError(
|
|
1043
|
+
'response-timeout',
|
|
1044
|
+
`Protocol V2 response timeout after ${timeoutMs}ms for ${name}`
|
|
1045
|
+
);
|
|
1046
|
+
}
|
|
1047
|
+
|
|
947
1048
|
/**
|
|
948
1049
|
* Expose the detected protocol type for a given device path.
|
|
949
1050
|
* Used by upper layers (e.g. TransportManager) to select the correct schema.
|