@onekeyfe/hd-transport-web-device 1.2.0-alpha.136 → 1.2.0-alpha.140

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/dist/index.d.ts CHANGED
@@ -20,21 +20,6 @@ declare class WebUsbTransport extends ProtocolV2UsbTransportBase<string> {
20
20
  /** Per-path protocol type detected by active wire-level probe. */
21
21
  private deviceProtocol;
22
22
  private deviceProtocolHints;
23
- /**
24
- * Paths whose cached protocol must be re-probed on the next acquire (a USB
25
- * disconnect was seen, or a transfer-level reconnect happened mid-call).
26
- */
27
- private staleProtocolPaths;
28
- /** Paths currently acquired (between a successful acquire() and its release()). */
29
- private acquiredPaths;
30
- /**
31
- * The exact USBDevice object each cached protocol was probed against. The
32
- * browser returns the same object identity for a device as long as it stays
33
- * connected, and a replug/reboot always yields a new object — so an identity
34
- * mismatch proves the device was re-enumerated since the probe, even when the
35
- * disconnect event itself was delayed or missed.
36
- */
37
- private probedDeviceObjects;
38
23
  /** Per-path USB endpoint / interface numbers (discovered from USB descriptors) */
39
24
  private deviceEndpoints;
40
25
  name: string;
@@ -55,17 +40,6 @@ declare class WebUsbTransport extends ProtocolV2UsbTransportBase<string> {
55
40
  * Initialize WebUSB transport
56
41
  */
57
42
  init(logger: any): void;
58
- /**
59
- * Protocol type is a property of the physical device keyed by USB serial number.
60
- * It can only change across a device reboot (e.g. normal ↔ bootloader mode), and
61
- * a reboot always surfaces as a USB disconnect. Disconnects (and transfer-level
62
- * reconnects, which cover a missed disconnect event) only MARK the cached probe
63
- * result stale instead of deleting it: an in-flight session keeps using the old
64
- * value so the transfer-level reconnect retries can absorb a transient
65
- * re-enumeration exactly as they did before the cache existed, while the next
66
- * acquire re-probes from scratch.
67
- */
68
- markProtocolStale(path: string): void;
69
43
  /**
70
44
  * Configure Protocol V1 protobuf schema (legacy chunked 0x3F framing).
71
45
  */
@@ -123,14 +97,6 @@ declare class WebUsbTransport extends ProtocolV2UsbTransportBase<string> {
123
97
  connectToDevice(path: string, first: boolean): Promise<void>;
124
98
  private closeOpenDevice;
125
99
  private clearEndpointHalt;
126
- /**
127
- * With the protocol cache surviving release(), deviceProtocol presence no
128
- * longer implies an active session. Guard call()/post() explicitly so a
129
- * post-release straggler fails fast instead of silently reopening the device
130
- * and driving it outside any session (pre-cache behavior: the deleted
131
- * protocol entry produced the same fail-fast).
132
- */
133
- private assertAcquired;
134
100
  post(session: string, name: string, data: Record<string, unknown>): Promise<void>;
135
101
  private getErrorMessage;
136
102
  private isRetryablePacketIoError;
package/dist/index.js CHANGED
@@ -57,21 +57,6 @@ const EXPECTED_PROTOCOL_V2_PROBE_ATTEMPTS = 2;
57
57
  function inferProtocolHintFromDeviceName$1(name) {
58
58
  return /\bpro\s*2\b/i.test(name !== null && name !== void 0 ? name : '') ? 'V2' : undefined;
59
59
  }
60
- let activeWebUsbTransport;
61
- let usbDisconnectListenerAttached = false;
62
- function registerActiveWebUsbTransport(instance, usb) {
63
- activeWebUsbTransport = instance;
64
- if (usbDisconnectListenerAttached)
65
- return;
66
- usbDisconnectListenerAttached = true;
67
- usb.addEventListener('disconnect', event => {
68
- var _a;
69
- const serial = (_a = event.device) === null || _a === void 0 ? void 0 : _a.serialNumber;
70
- if (typeof serial !== 'string' || serial.length === 0)
71
- return;
72
- activeWebUsbTransport === null || activeWebUsbTransport === void 0 ? void 0 : activeWebUsbTransport.markProtocolStale(serial);
73
- });
74
- }
75
60
  class WebUsbTransport extends transport.ProtocolV2UsbTransportBase {
76
61
  constructor() {
77
62
  super({
@@ -81,9 +66,6 @@ class WebUsbTransport extends transport.ProtocolV2UsbTransportBase {
81
66
  });
82
67
  this.deviceProtocol = new Map();
83
68
  this.deviceProtocolHints = new Map();
84
- this.staleProtocolPaths = new Set();
85
- this.acquiredPaths = new Set();
86
- this.probedDeviceObjects = new Map();
87
69
  this.deviceEndpoints = new Map();
88
70
  this.name = 'WebUsbTransport';
89
71
  this.stopped = false;
@@ -100,11 +82,6 @@ class WebUsbTransport extends transport.ProtocolV2UsbTransportBase {
100
82
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'WebUSB is not supported by current browsers');
101
83
  }
102
84
  this.usb = usb;
103
- registerActiveWebUsbTransport(this, usb);
104
- }
105
- markProtocolStale(path) {
106
- this.staleProtocolPaths.add(path);
107
- this.probedDeviceObjects.delete(path);
108
85
  }
109
86
  configure(signedData) {
110
87
  const messages = parseConfigure$1(signedData);
@@ -171,7 +148,7 @@ class WebUsbTransport extends transport.ProtocolV2UsbTransportBase {
171
148
  });
172
149
  }
173
150
  acquire(input) {
174
- var _a, _b, _c, _d, _e, _f;
151
+ var _a, _b, _c, _d;
175
152
  return __awaiter(this, void 0, void 0, function* () {
176
153
  if (!input.path)
177
154
  return;
@@ -179,40 +156,18 @@ class WebUsbTransport extends transport.ProtocolV2UsbTransportBase {
179
156
  yield this.rotateProtocolV2UsbGeneration(input.path, 'WebUSB transport acquired');
180
157
  yield this.closeOpenDevice(input.path);
181
158
  yield this.connect((_a = input.path) !== null && _a !== void 0 ? _a : '', true);
182
- if (this.staleProtocolPaths.has(input.path)) {
183
- this.staleProtocolPaths.delete(input.path);
184
- this.deviceProtocol.delete(input.path);
185
- }
186
- if (this.deviceProtocol.has(input.path)) {
187
- const currentDevice = (_b = this.deviceList.find(d => d.path === input.path)) === null || _b === void 0 ? void 0 : _b.device;
188
- if (!currentDevice || currentDevice !== this.probedDeviceObjects.get(input.path)) {
189
- this.deviceProtocol.delete(input.path);
190
- }
191
- }
192
- const cachedProtocol = this.deviceProtocol.get(input.path);
193
- if (cachedProtocol && input.expectedProtocol && cachedProtocol !== input.expectedProtocol) {
194
- this.deviceProtocol.delete(input.path);
195
- }
196
- if (!this.deviceProtocol.has(input.path)) {
197
- const deviceName = (_c = this.deviceList.find(device => device.path === input.path)) === null || _c === void 0 ? void 0 : _c.device.productName;
198
- const protocolHint = input.expectedProtocol
199
- ? undefined
200
- : (_e = (_d = input.protocolHint) !== null && _d !== void 0 ? _d : this.deviceProtocolHints.get(input.path)) !== null && _e !== void 0 ? _e : inferProtocolHintFromDeviceName$1(deviceName);
201
- if (protocolHint) {
202
- this.deviceProtocolHints.set(input.path, protocolHint);
203
- }
204
- yield this.detectProtocol(input.path, input.expectedProtocol, protocolHint);
205
- const probedDevice = (_f = this.deviceList.find(d => d.path === input.path)) === null || _f === void 0 ? void 0 : _f.device;
206
- if (probedDevice) {
207
- this.probedDeviceObjects.set(input.path, probedDevice);
208
- }
159
+ const deviceName = (_b = this.deviceList.find(device => device.path === input.path)) === null || _b === void 0 ? void 0 : _b.device.productName;
160
+ const protocolHint = input.expectedProtocol
161
+ ? undefined
162
+ : (_d = (_c = input.protocolHint) !== null && _c !== void 0 ? _c : this.deviceProtocolHints.get(input.path)) !== null && _d !== void 0 ? _d : inferProtocolHintFromDeviceName$1(deviceName);
163
+ if (protocolHint) {
164
+ this.deviceProtocolHints.set(input.path, protocolHint);
209
165
  }
210
- this.acquiredPaths.add(input.path);
166
+ yield this.detectProtocol(input.path, input.expectedProtocol, protocolHint);
211
167
  return yield Promise.resolve(input.path);
212
168
  }
213
169
  catch (e) {
214
170
  this.Log.debug('acquire error: ', e instanceof Error ? `${e.name}: ${e.message}` : String(e));
215
- this.acquiredPaths.delete(input.path);
216
171
  yield this.closeOpenDevice(input.path);
217
172
  throw e;
218
173
  }
@@ -396,14 +351,8 @@ class WebUsbTransport extends transport.ProtocolV2UsbTransportBase {
396
351
  }
397
352
  });
398
353
  }
399
- assertAcquired(path) {
400
- if (!this.acquiredPaths.has(path)) {
401
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `Device is not acquired for ${path}`);
402
- }
403
- }
404
354
  post(session, name, data) {
405
355
  return __awaiter(this, void 0, void 0, function* () {
406
- this.assertAcquired(session);
407
356
  if (this.deviceProtocol.get(session) === 'V2') {
408
357
  yield this.sendProtocolV2UsbFlowControl(session, name, data);
409
358
  return;
@@ -436,7 +385,6 @@ class WebUsbTransport extends transport.ProtocolV2UsbTransportBase {
436
385
  var _a;
437
386
  return __awaiter(this, void 0, void 0, function* () {
438
387
  this.Log.debug(`[WebUsbTransport] transfer${direction} failed, retry ${attempt}/${PACKET_IO_MAX_RETRIES}: ${this.getErrorMessage(error)}`);
439
- this.staleProtocolPaths.add(path);
440
388
  yield hdShared.wait(attempt * PACKET_IO_RETRY_DELAY);
441
389
  try {
442
390
  const currentDevice = yield this.findDevice(path);
@@ -651,7 +599,6 @@ class WebUsbTransport extends transport.ProtocolV2UsbTransportBase {
651
599
  if (this.messages == null) {
652
600
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotConfigured);
653
601
  }
654
- this.assertAcquired(path);
655
602
  const device = yield this.findDevice(path);
656
603
  if (!device) {
657
604
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceNotFound);
@@ -731,9 +678,10 @@ class WebUsbTransport extends transport.ProtocolV2UsbTransportBase {
731
678
  }
732
679
  release(path) {
733
680
  return __awaiter(this, void 0, void 0, function* () {
734
- this.acquiredPaths.delete(path);
735
681
  yield this.invalidateProtocolV2UsbLink(path, 'WebUSB transport released');
736
682
  yield this.closeOpenDevice(path);
683
+ this.deviceProtocol.delete(path);
684
+ this.deviceProtocolHints.delete(path);
737
685
  this.deviceEndpoints.delete(path);
738
686
  });
739
687
  }
package/dist/webusb.d.ts CHANGED
@@ -12,9 +12,6 @@ export default class WebUsbTransport extends ProtocolV2UsbTransportBase<string>
12
12
  private protocolV2SchemaSource;
13
13
  private deviceProtocol;
14
14
  private deviceProtocolHints;
15
- private staleProtocolPaths;
16
- private acquiredPaths;
17
- private probedDeviceObjects;
18
15
  private deviceEndpoints;
19
16
  name: string;
20
17
  stopped: boolean;
@@ -27,7 +24,6 @@ export default class WebUsbTransport extends ProtocolV2UsbTransportBase<string>
27
24
  interfaceId: number;
28
25
  constructor();
29
26
  init(logger: any): void;
30
- markProtocolStale(path: string): void;
31
27
  configure(signedData: any): void;
32
28
  configureProtocolV2(signedData: any): void;
33
29
  promptDeviceAccess(): Promise<USBDevice | null>;
@@ -44,7 +40,6 @@ export default class WebUsbTransport extends ProtocolV2UsbTransportBase<string>
44
40
  connectToDevice(path: string, first: boolean): Promise<void>;
45
41
  private closeOpenDevice;
46
42
  private clearEndpointHalt;
47
- private assertAcquired;
48
43
  post(session: string, name: string, data: Record<string, unknown>): Promise<void>;
49
44
  private getErrorMessage;
50
45
  private isRetryablePacketIoError;
@@ -1 +1 @@
1
- {"version":3,"file":"webusb.d.ts","sourceRoot":"","sources":["../src/webusb.ts"],"names":[],"mappings":";AACA,OAAO,SAAS,EAAE,EAQhB,0BAA0B,EAE3B,MAAM,wBAAwB,CAAC;AAUhC,OAAO,KAAK,EACV,YAAY,EACZ,oBAAoB,EACpB,YAAY,EACZ,qBAAqB,EACrB,iBAAiB,EACjB,oBAAoB,EACrB,MAAM,wBAAwB,CAAC;AA0BhC,MAAM,WAAW,UAAW,SAAQ,oBAAoB;IACtD,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,SAAS,CAAC;IAClB,YAAY,CAAC,EAAE,YAAY,CAAC;CAC7B;AAkCD,MAAM,CAAC,OAAO,OAAO,eAAgB,SAAQ,0BAA0B,CAAC,MAAM,CAAC;IAC7E,QAAQ,EAAE,UAAU,CAAC,OAAO,SAAS,CAAC,cAAc,CAAC,GAAG,SAAS,CAAC;IAGlE,UAAU,EAAE,UAAU,CAAC,OAAO,SAAS,CAAC,cAAc,CAAC,GAAG,SAAS,CAAC;IAEpE,OAAO,CAAC,sBAAsB,CAAqB;IAGnD,OAAO,CAAC,cAAc,CAAwC;IAE9D,OAAO,CAAC,mBAAmB,CAAwC;IAMnE,OAAO,CAAC,kBAAkB,CAA0B;IAGpD,OAAO,CAAC,aAAa,CAA0B;IAS/C,OAAO,CAAC,mBAAmB,CAAqC;IAGhE,OAAO,CAAC,eAAe,CAA2C;IAElE,IAAI,SAAqB;IAEzB,OAAO,UAAS;IAEhB,UAAU,UA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",
3
+ "version": "1.2.0-alpha.140",
4
4
  "author": "OneKey",
5
5
  "homepage": "https://github.com/OneKeyHQ/hardware-js-sdk#readme",
6
6
  "license": "MIT",
@@ -21,13 +21,13 @@
21
21
  "lint:fix": "eslint . --fix"
22
22
  },
23
23
  "dependencies": {
24
- "@onekeyfe/hd-shared": "1.2.0-alpha.136",
25
- "@onekeyfe/hd-transport": "1.2.0-alpha.136"
24
+ "@onekeyfe/hd-shared": "1.2.0-alpha.140",
25
+ "@onekeyfe/hd-transport": "1.2.0-alpha.140"
26
26
  },
27
27
  "devDependencies": {
28
- "@onekeyfe/hd-transport-electron": "1.2.0-alpha.136",
28
+ "@onekeyfe/hd-transport-electron": "1.2.0-alpha.140",
29
29
  "@types/w3c-web-usb": "^1.0.6",
30
30
  "@types/web-bluetooth": "^0.0.17"
31
31
  },
32
- "gitHead": "92945bc4aae3d6602dd44c2e028e902e6bce7b55"
32
+ "gitHead": "15e3f0dc6c543c83a96e63b5d19aad70cdd6efb1"
33
33
  }
package/src/webusb.ts CHANGED
@@ -69,27 +69,6 @@ interface TransferCancelToken {
69
69
  cancelled: boolean;
70
70
  }
71
71
 
72
- /**
73
- * The navigator.usb disconnect listener is module-scoped and attached at most
74
- * once: listeners on navigator.usb are global and never garbage collected, so a
75
- * per-instance listener would retain every transport instance created across
76
- * SDK re-initializations. Events are routed to the most recently initialized
77
- * transport instance instead.
78
- */
79
- let activeWebUsbTransport: WebUsbTransport | undefined;
80
- let usbDisconnectListenerAttached = false;
81
-
82
- function registerActiveWebUsbTransport(instance: WebUsbTransport, usb: USB) {
83
- activeWebUsbTransport = instance;
84
- if (usbDisconnectListenerAttached) return;
85
- usbDisconnectListenerAttached = true;
86
- usb.addEventListener('disconnect', event => {
87
- const serial = event.device?.serialNumber;
88
- if (typeof serial !== 'string' || serial.length === 0) return;
89
- activeWebUsbTransport?.markProtocolStale(serial);
90
- });
91
- }
92
-
93
72
  export default class WebUsbTransport extends ProtocolV2UsbTransportBase<string> {
94
73
  messages: ReturnType<typeof transport.parseConfigure> | undefined;
95
74
 
@@ -103,24 +82,6 @@ export default class WebUsbTransport extends ProtocolV2UsbTransportBase<string>
103
82
 
104
83
  private deviceProtocolHints: Map<string, ProtocolType> = new Map();
105
84
 
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();
111
-
112
- /** Paths currently acquired (between a successful acquire() and its release()). */
113
- private acquiredPaths: Set<string> = new Set();
114
-
115
- /**
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.
121
- */
122
- private probedDeviceObjects: Map<string, USBDevice> = new Map();
123
-
124
85
  /** Per-path USB endpoint / interface numbers (discovered from USB descriptors) */
125
86
  private deviceEndpoints: Map<string, DeviceEndpoints> = new Map();
126
87
 
@@ -168,22 +129,6 @@ export default class WebUsbTransport extends ProtocolV2UsbTransportBase<string>
168
129
  );
169
130
  }
170
131
  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);
187
132
  }
188
133
 
189
134
  /**
@@ -286,49 +231,20 @@ export default class WebUsbTransport extends ProtocolV2UsbTransportBase<string>
286
231
  await this.rotateProtocolV2UsbGeneration(input.path, 'WebUSB transport acquired');
287
232
  await this.closeOpenDevice(input.path);
288
233
  await this.connect(input.path ?? '', true);
289
- if (this.staleProtocolPaths.has(input.path)) {
290
- // The device disconnected (possibly rebooting into another mode) since
291
- // the protocol was probed — drop the cache so it is re-probed below.
292
- this.staleProtocolPaths.delete(input.path);
293
- this.deviceProtocol.delete(input.path);
294
- }
295
- if (this.deviceProtocol.has(input.path)) {
296
- const currentDevice = this.deviceList.find(d => d.path === input.path)?.device;
297
- if (!currentDevice || currentDevice !== this.probedDeviceObjects.get(input.path)) {
298
- // The OS re-enumerated the device since the probe (a replug/reboot we
299
- // may not have seen a disconnect event for) — the cached protocol can
300
- // no longer be trusted; re-probe on the wire below.
301
- this.deviceProtocol.delete(input.path);
302
- }
303
- }
304
- const cachedProtocol = this.deviceProtocol.get(input.path);
305
- if (cachedProtocol && input.expectedProtocol && cachedProtocol !== input.expectedProtocol) {
306
- // The caller expects a different protocol than the cached probe result;
307
- // the cache is stale — drop it and re-probe on the wire below.
308
- this.deviceProtocol.delete(input.path);
309
- }
310
- if (!this.deviceProtocol.has(input.path)) {
311
- const deviceName = this.deviceList.find(device => device.path === input.path)?.device
312
- .productName;
313
- const protocolHint = input.expectedProtocol
314
- ? undefined
315
- : input.protocolHint ??
316
- this.deviceProtocolHints.get(input.path) ??
317
- inferProtocolHintFromDeviceName(deviceName);
318
- if (protocolHint) {
319
- this.deviceProtocolHints.set(input.path, protocolHint);
320
- }
321
- await this.detectProtocol(input.path, input.expectedProtocol, protocolHint);
322
- const probedDevice = this.deviceList.find(d => d.path === input.path)?.device;
323
- if (probedDevice) {
324
- this.probedDeviceObjects.set(input.path, probedDevice);
325
- }
234
+ const deviceName = this.deviceList.find(device => device.path === input.path)?.device
235
+ .productName;
236
+ const protocolHint = input.expectedProtocol
237
+ ? undefined
238
+ : input.protocolHint ??
239
+ this.deviceProtocolHints.get(input.path) ??
240
+ inferProtocolHintFromDeviceName(deviceName);
241
+ if (protocolHint) {
242
+ this.deviceProtocolHints.set(input.path, protocolHint);
326
243
  }
327
- this.acquiredPaths.add(input.path);
244
+ await this.detectProtocol(input.path, input.expectedProtocol, protocolHint);
328
245
  return await Promise.resolve(input.path);
329
246
  } catch (e) {
330
247
  this.Log.debug('acquire error: ', e instanceof Error ? `${e.name}: ${e.message}` : String(e));
331
- this.acquiredPaths.delete(input.path);
332
248
  await this.closeOpenDevice(input.path);
333
249
  throw e;
334
250
  }
@@ -564,21 +480,7 @@ export default class WebUsbTransport extends ProtocolV2UsbTransportBase<string>
564
480
  }
565
481
  }
566
482
 
567
- /**
568
- * With the protocol cache surviving release(), deviceProtocol presence no
569
- * longer implies an active session. Guard call()/post() explicitly so a
570
- * post-release straggler fails fast instead of silently reopening the device
571
- * and driving it outside any session (pre-cache behavior: the deleted
572
- * protocol entry produced the same fail-fast).
573
- */
574
- private assertAcquired(path: string) {
575
- if (!this.acquiredPaths.has(path)) {
576
- throw ERRORS.TypedError(HardwareErrorCode.RuntimeError, `Device is not acquired for ${path}`);
577
- }
578
- }
579
-
580
483
  async post(session: string, name: string, data: Record<string, unknown>) {
581
- this.assertAcquired(session);
582
484
  if (this.deviceProtocol.get(session) === 'V2') {
583
485
  await this.sendProtocolV2UsbFlowControl(session, name, data);
584
486
  return;
@@ -620,11 +522,6 @@ export default class WebUsbTransport extends ProtocolV2UsbTransportBase<string>
620
522
  error
621
523
  )}`
622
524
  );
623
- // The device dropped off the bus mid-call and may have rebooted into a
624
- // different mode. The in-flight retry keeps the known protocol, but the
625
- // next acquire must re-probe — this also self-heals a stale cache when the
626
- // USB disconnect event itself was missed.
627
- this.staleProtocolPaths.add(path);
628
525
  await wait(attempt * PACKET_IO_RETRY_DELAY);
629
526
 
630
527
  try {
@@ -858,7 +755,6 @@ export default class WebUsbTransport extends ProtocolV2UsbTransportBase<string>
858
755
  if (this.messages == null) {
859
756
  throw ERRORS.TypedError(HardwareErrorCode.TransportNotConfigured);
860
757
  }
861
- this.assertAcquired(path);
862
758
 
863
759
  const device = await this.findDevice(path);
864
760
  if (!device) {
@@ -975,14 +871,10 @@ export default class WebUsbTransport extends ProtocolV2UsbTransportBase<string>
975
871
  * Release device
976
872
  */
977
873
  async release(path: string) {
978
- this.acquiredPaths.delete(path);
979
874
  await this.invalidateProtocolV2UsbLink(path, 'WebUSB transport released');
980
875
  await this.closeOpenDevice(path);
981
- // Keep deviceProtocol/deviceProtocolHints across release: the probe result is a
982
- // physical-device property, so the next acquire can skip the wire-level probe.
983
- // V2 entries are still dropped by onProtocolV2UsbLinkInvalidated via the link
984
- // invalidation above, and any entry is re-probed after a USB disconnect or a
985
- // transfer-level reconnect (see markProtocolStale).
876
+ this.deviceProtocol.delete(path);
877
+ this.deviceProtocolHints.delete(path);
986
878
  this.deviceEndpoints.delete(path);
987
879
  }
988
880
 
@@ -1,228 +0,0 @@
1
- import transport from '@onekeyfe/hd-transport';
2
- import { HardwareErrorCode } from '@onekeyfe/hd-shared';
3
-
4
- import WebUsbTransport from '../src/webusb';
5
-
6
- const schema = {
7
- nested: {
8
- Ping: { fields: { message: { type: 'string', id: 1 } } },
9
- Success: { fields: { message: { type: 'string', id: 1 } } },
10
- MessageType: {
11
- values: {
12
- MessageType_Ping: 60206,
13
- MessageType_Success: 60207,
14
- },
15
- },
16
- },
17
- };
18
-
19
- function buildAcquirableTransport(path = 'pro-webusb') {
20
- const webusb = new WebUsbTransport() as any;
21
- webusb.Log = { debug: jest.fn() };
22
- webusb.rotateProtocolV2UsbGeneration = jest.fn().mockResolvedValue(undefined);
23
- webusb.closeOpenDevice = jest.fn().mockResolvedValue(undefined);
24
- webusb.connect = jest.fn().mockResolvedValue(undefined);
25
- // Simulate a device that stayed connected since the probe: same USBDevice
26
- // object present in the device list and recorded as the probed object.
27
- const deviceObject = { serialNumber: path } as unknown as USBDevice;
28
- webusb.deviceList = [{ path, device: deviceObject, commType: 'webusb' }];
29
- webusb.probedDeviceObjects.set(path, deviceObject);
30
- return webusb;
31
- }
32
-
33
- describe('WebUsbTransport protocol probe cache', () => {
34
- test('acquire skips the wire probe when the protocol is already cached', async () => {
35
- const webusb = buildAcquirableTransport();
36
- const path = 'pro-webusb';
37
- webusb.deviceProtocol.set(path, 'V1');
38
- webusb.detectProtocol = jest.fn();
39
-
40
- await expect(webusb.acquire({ path, expectedProtocol: 'V1' })).resolves.toBe(path);
41
-
42
- expect(webusb.detectProtocol).not.toHaveBeenCalled();
43
- expect(webusb.deviceProtocol.get(path)).toBe('V1');
44
- expect(webusb.acquiredPaths.has(path)).toBe(true);
45
- });
46
-
47
- test('acquire re-probes when the caller expects a different protocol than cached', async () => {
48
- const webusb = buildAcquirableTransport();
49
- const path = 'pro-webusb';
50
- webusb.deviceProtocol.set(path, 'V1');
51
- webusb.detectProtocol = jest.fn().mockImplementation((p: string) => {
52
- webusb.deviceProtocol.set(p, 'V2');
53
- return Promise.resolve('V2');
54
- });
55
-
56
- await expect(webusb.acquire({ path, expectedProtocol: 'V2' })).resolves.toBe(path);
57
-
58
- expect(webusb.detectProtocol).toHaveBeenCalledWith(path, 'V2', undefined);
59
- expect(webusb.deviceProtocol.get(path)).toBe('V2');
60
- });
61
-
62
- test('acquire probes when nothing is cached for the path', async () => {
63
- const webusb = buildAcquirableTransport();
64
- const path = 'pro-webusb';
65
- webusb.detectProtocol = jest.fn().mockResolvedValue('V1');
66
-
67
- await expect(webusb.acquire({ path, expectedProtocol: 'V1' })).resolves.toBe(path);
68
-
69
- expect(webusb.detectProtocol).toHaveBeenCalledWith(path, 'V1', undefined);
70
- });
71
-
72
- test('acquire re-probes when the USBDevice object identity changed since the probe', async () => {
73
- const webusb = buildAcquirableTransport();
74
- const path = 'pro-webusb';
75
- webusb.deviceProtocol.set(path, 'V1');
76
- // Simulate a replug the transport never saw a disconnect event for: the OS
77
- // re-enumerated the device, so the list now holds a NEW USBDevice object.
78
- webusb.deviceList = [
79
- { path, device: { serialNumber: path } as unknown as USBDevice, commType: 'webusb' },
80
- ];
81
- webusb.detectProtocol = jest.fn().mockImplementation((p: string) => {
82
- webusb.deviceProtocol.set(p, 'V1');
83
- return Promise.resolve('V1');
84
- });
85
-
86
- await expect(webusb.acquire({ path, expectedProtocol: 'V1' })).resolves.toBe(path);
87
-
88
- expect(webusb.detectProtocol).toHaveBeenCalledTimes(1);
89
- });
90
-
91
- test('acquire re-probes a stale-marked path even when a protocol is cached', async () => {
92
- const webusb = buildAcquirableTransport();
93
- const path = 'pro-webusb';
94
- webusb.deviceProtocol.set(path, 'V1');
95
- webusb.markProtocolStale(path);
96
- webusb.detectProtocol = jest.fn().mockImplementation((p: string) => {
97
- webusb.deviceProtocol.set(p, 'V1');
98
- return Promise.resolve('V1');
99
- });
100
-
101
- await expect(webusb.acquire({ path, expectedProtocol: 'V1' })).resolves.toBe(path);
102
-
103
- expect(webusb.detectProtocol).toHaveBeenCalledTimes(1);
104
- expect(webusb.staleProtocolPaths.has(path)).toBe(false);
105
- });
106
-
107
- test('release keeps the cached V1 protocol so the next acquire can reuse it', async () => {
108
- const webusb = new WebUsbTransport() as any;
109
- const path = 'pro-webusb';
110
- webusb.deviceProtocol.set(path, 'V1');
111
- webusb.deviceProtocolHints.set(path, 'V2');
112
- webusb.deviceEndpoints.set(path, { interfaceNumber: 0, endpointIn: 1, endpointOut: 1 });
113
- webusb.acquiredPaths.add(path);
114
- webusb.closeOpenDevice = jest.fn().mockResolvedValue(undefined);
115
-
116
- await webusb.release(path);
117
-
118
- expect(webusb.deviceProtocol.get(path)).toBe('V1');
119
- expect(webusb.deviceProtocolHints.get(path)).toBe('V2');
120
- expect(webusb.deviceEndpoints.has(path)).toBe(false);
121
- expect(webusb.acquiredPaths.has(path)).toBe(false);
122
- });
123
-
124
- test('release still drops a cached V2 protocol through link invalidation', async () => {
125
- const webusb = new WebUsbTransport() as any;
126
- const path = 'pro2-webusb';
127
- webusb.Log = { debug: jest.fn() };
128
- webusb.messages = transport.parseConfigure(schema);
129
- webusb.messagesV2 = transport.parseConfigure(schema);
130
- webusb.writeProtocolV2UsbPacket = jest.fn().mockResolvedValue(undefined);
131
- let markReadStarted: () => void = () => undefined;
132
- const readStarted = new Promise<void>(resolve => {
133
- markReadStarted = resolve;
134
- });
135
- webusb.readProtocolV2UsbPacket = jest.fn().mockImplementation(() => {
136
- markReadStarted();
137
- return new Promise<void>(() => {});
138
- });
139
- webusb.closeOpenDevice = jest.fn().mockResolvedValue(undefined);
140
- webusb.deviceProtocol.set(path, 'V2');
141
- await webusb.rotateProtocolV2UsbGeneration(path, 'test connection');
142
-
143
- const call = webusb.callProtocolV2(path, 'Ping', { message: 'release' });
144
- await readStarted;
145
- await webusb.release(path);
146
-
147
- await expect(call).rejects.toThrow('WebUSB transport released');
148
- expect(webusb.deviceProtocol.has(path)).toBe(false);
149
- });
150
-
151
- test('call and post fail fast for a path that is not acquired', async () => {
152
- const webusb = new WebUsbTransport() as any;
153
- const path = 'pro-webusb';
154
- webusb.Log = { debug: jest.fn() };
155
- webusb.messages = transport.parseConfigure(schema);
156
- webusb.messagesV2 = transport.parseConfigure(schema);
157
- // A surviving protocol cache entry must NOT act as a session token.
158
- webusb.deviceProtocol.set(path, 'V1');
159
-
160
- await expect(webusb.call(path, 'Ping', {})).rejects.toMatchObject({
161
- errorCode: HardwareErrorCode.RuntimeError,
162
- message: expect.stringContaining('not acquired'),
163
- });
164
- await expect(webusb.post(path, 'Ping', {})).rejects.toMatchObject({
165
- errorCode: HardwareErrorCode.RuntimeError,
166
- message: expect.stringContaining('not acquired'),
167
- });
168
- });
169
-
170
- test('a transfer-level reconnect marks the protocol stale for the next acquire', async () => {
171
- const webusb = new WebUsbTransport() as any;
172
- const path = 'pro-webusb';
173
- webusb.Log = { debug: jest.fn() };
174
- webusb.deviceProtocol.set(path, 'V1');
175
- webusb.findDevice = jest.fn().mockResolvedValue({ opened: false });
176
- webusb.getConnectedDevices = jest.fn().mockResolvedValue([]);
177
- webusb.connect = jest.fn().mockResolvedValue(undefined);
178
-
179
- await webusb.reconnectForPacketIoRetry(path, 'in', 0, new Error('transferIn failed'));
180
-
181
- // The in-flight call keeps the cached protocol; only the next acquire re-probes.
182
- expect(webusb.deviceProtocol.get(path)).toBe('V1');
183
- expect(webusb.staleProtocolPaths.has(path)).toBe(true);
184
- });
185
-
186
- test('USB disconnect marks the serial stale and the listener attaches only once', () => {
187
- const addEventListener = jest.fn();
188
- const usb = { addEventListener } as unknown as USB;
189
- const originalNavigator = (globalThis as any).navigator;
190
- Object.defineProperty(globalThis, 'navigator', {
191
- value: { usb },
192
- configurable: true,
193
- });
194
- try {
195
- const first = new WebUsbTransport() as any;
196
- first.init({ debug: jest.fn() });
197
- const second = new WebUsbTransport() as any;
198
- second.init({ debug: jest.fn() });
199
-
200
- // Module-level listener: one registration across instances.
201
- expect(addEventListener).toHaveBeenCalledTimes(1);
202
- const handler = addEventListener.mock.calls[0][1] as (event: {
203
- device?: { serialNumber?: string | null };
204
- }) => void;
205
-
206
- const path = 'pro-webusb';
207
- first.deviceProtocol.set(path, 'V1');
208
- second.deviceProtocol.set(path, 'V1');
209
- handler({ device: { serialNumber: path } });
210
-
211
- // Routed to the most recently initialized instance; the cached value is
212
- // retained (in-flight sessions keep working) but marked stale.
213
- expect(second.staleProtocolPaths.has(path)).toBe(true);
214
- expect(second.deviceProtocol.get(path)).toBe('V1');
215
- expect(first.staleProtocolPaths.has(path)).toBe(false);
216
-
217
- // Events without a usable serial are ignored.
218
- handler({ device: { serialNumber: null } });
219
- handler({});
220
- expect(second.staleProtocolPaths.size).toBe(1);
221
- } finally {
222
- Object.defineProperty(globalThis, 'navigator', {
223
- value: originalNavigator,
224
- configurable: true,
225
- });
226
- }
227
- });
228
- });