@onekeyfe/hd-transport-web-device 1.2.11-alpha.1 → 1.2.11-alpha.11

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.
@@ -1372,4 +1372,81 @@ describe('ElectronBleTransport protocol detection', () => {
1372
1372
  await bleTransport.release(device.id);
1373
1373
  }
1374
1374
  });
1375
+
1376
+ test('stop() unsubscribes host disconnect listener and releases owned links idempotently', async () => {
1377
+ const device = { id: 'stop-cleanup-pro2-id', name: 'OneKey Pro 2' };
1378
+ const nobleBle = createNobleBle(device);
1379
+ const emitter = new EventEmitter();
1380
+ const hostDisconnectCleanup = jest.fn();
1381
+ const notifyCleanup = jest.fn();
1382
+ const mtuCleanup = jest.fn();
1383
+ let disconnectHandler:
1384
+ | ((d: { id: string; name: string; reason?: EBleDisconnectReason }) => void)
1385
+ | undefined;
1386
+
1387
+ nobleBle.onDeviceDisconnected.mockImplementation(handler => {
1388
+ disconnectHandler = handler;
1389
+ return () => {
1390
+ hostDisconnectCleanup();
1391
+ disconnectHandler = undefined;
1392
+ };
1393
+ });
1394
+ echoProtocolV2(nobleBle, device.id);
1395
+ const echoOnNotification = nobleBle.onNotification.getMockImplementation();
1396
+ nobleBle.onNotification.mockImplementation(handler => {
1397
+ echoOnNotification?.(handler);
1398
+ return notifyCleanup;
1399
+ });
1400
+ nobleBle.onMtuChanged.mockImplementation(() => mtuCleanup);
1401
+
1402
+ const transportDisconnect = jest.fn();
1403
+ emitter.on('transport-device-disconnect', transportDisconnect);
1404
+ const bleTransport = configureTransport(nobleBle, emitter);
1405
+
1406
+ await bleTransport.acquire({ uuid: device.id, expectedProtocol: 'V2' });
1407
+ expect(bleTransport.getProtocolType(device.id)).toBe('V2');
1408
+
1409
+ await bleTransport.stop();
1410
+
1411
+ expect(hostDisconnectCleanup).toHaveBeenCalledTimes(1);
1412
+ expect(notifyCleanup).toHaveBeenCalledTimes(1);
1413
+ expect(mtuCleanup).toHaveBeenCalledTimes(1);
1414
+ expect(nobleBle.unsubscribe).toHaveBeenCalledWith(device.id);
1415
+ expect(nobleBle.disconnect).toHaveBeenCalledWith(device.id);
1416
+ expect(bleTransport.getProtocolType(device.id)).toBeUndefined();
1417
+
1418
+ // Calling stop() again is a safe no-op.
1419
+ await bleTransport.stop();
1420
+ expect(hostDisconnectCleanup).toHaveBeenCalledTimes(1);
1421
+ expect(nobleBle.disconnect).toHaveBeenCalledTimes(1);
1422
+
1423
+ // Late host disconnect events are no longer delivered to the stopped transport.
1424
+ disconnectHandler?.({ ...device, reason: EBleDisconnectReason.DeviceDisconnected });
1425
+ expect(transportDisconnect).not.toHaveBeenCalled();
1426
+ });
1427
+
1428
+ test('stop() during getDevice() does not let retired acquire disconnect a replacement link', async () => {
1429
+ const device = { id: 'lookup-stop-pro2-id', name: 'OneKey Pro 2' };
1430
+ const nobleBle = createNobleBle(device);
1431
+ let resolveGetDevice: ((value: typeof device) => void) | undefined;
1432
+ nobleBle.getDevice.mockImplementation(
1433
+ () =>
1434
+ new Promise(resolve => {
1435
+ resolveGetDevice = resolve;
1436
+ })
1437
+ );
1438
+ const bleTransport = configureTransport(nobleBle);
1439
+
1440
+ const acquiring = bleTransport.acquire({ uuid: device.id, expectedProtocol: 'V2' });
1441
+ const stopping = bleTransport.stop();
1442
+ await stopping;
1443
+ // Clear disconnect count recorded during stopResources() so we verify the late
1444
+ // retired acquire does not issue another disconnect against a replacement link.
1445
+ nobleBle.disconnect.mockClear();
1446
+
1447
+ resolveGetDevice?.(device);
1448
+ await expect(acquiring).rejects.toThrow(/Electron BLE transport is stopped/);
1449
+ expect(nobleBle.connect).not.toHaveBeenCalled();
1450
+ expect(nobleBle.disconnect).not.toHaveBeenCalled();
1451
+ });
1375
1452
  });
@@ -16,6 +16,37 @@ const schema = {
16
16
  },
17
17
  };
18
18
 
19
+ test('reads a multi-packet V1 response without a global Buffer', async () => {
20
+ const webusb = new WebUsbTransport();
21
+ const messages = transport.parseConfigure(schema);
22
+ const response = { message: 'v1 response '.repeat(9) };
23
+ const expected = transport.ProtocolV1.encodeEnvelope(messages, 'Success', response).toString(
24
+ 'hex'
25
+ );
26
+ const packets = transport.ProtocolV1.encodeTransportPackets(messages, 'Success', response);
27
+ expect(packets.length).toBeGreaterThan(1);
28
+ const reader = webusb as unknown as {
29
+ transferInWithRetry: () => Promise<Uint8Array>;
30
+ };
31
+ const transferIn = jest.spyOn(reader, 'transferInWithRetry');
32
+ packets.forEach(packet => {
33
+ transferIn.mockResolvedValueOnce(new Uint8Array(packet.toBuffer()));
34
+ });
35
+ const buffer = globalThis.Buffer;
36
+ try {
37
+ Object.defineProperty(globalThis, 'Buffer', { value: undefined });
38
+ const received = await webusb.receiveData('synthetic-usb');
39
+ expect(received).toBe(expected);
40
+ expect(transport.ProtocolV1.decodeMessage(messages, received)).toMatchObject({
41
+ type: 'Success',
42
+ message: response,
43
+ });
44
+ } finally {
45
+ Object.defineProperty(globalThis, 'Buffer', { value: buffer });
46
+ transferIn.mockRestore();
47
+ }
48
+ });
49
+
19
50
  function buildAcquirableTransport(path = 'pro-webusb') {
20
51
  const webusb = new WebUsbTransport() as any;
21
52
  webusb.Log = { debug: jest.fn() };
@@ -28,6 +28,8 @@ export default class ElectronBleTransport {
28
28
  private retainedDevices;
29
29
  private protocolV2CallCounts;
30
30
  private acquiringDevices;
31
+ private stopped;
32
+ private stopPromise?;
31
33
  private deviceProtocol;
32
34
  private deviceProtocolHints;
33
35
  private deviceMtus;
@@ -47,6 +49,9 @@ export default class ElectronBleTransport {
47
49
  private handleBluetoothError;
48
50
  private cleanupDeviceState;
49
51
  init(logger: any, emitter?: EventEmitter): void;
52
+ private assertRunning;
53
+ stop(): Promise<void>;
54
+ private stopResources;
50
55
  private subscribeHostDisconnects;
51
56
  configure(signedData: any): void;
52
57
  configureProtocolV2(signedData: any): void;
@@ -1 +1 @@
1
- {"version":3,"file":"electron-ble-transport.d.ts","sourceRoot":"","sources":["../src/electron-ble-transport.ts"],"names":[],"mappings":";AAyBA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BAA6B;IA4CrC,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,YAAY,GAAG,SAAS;CAGxD"}
package/dist/index.d.ts CHANGED
@@ -22,9 +22,9 @@ declare class WebUsbTransport extends ProtocolV2UsbTransportBase<string> {
22
22
  private handleOperationSequence;
23
23
  private deviceLogSequence;
24
24
  private deviceLogIds;
25
- messages: ReturnType<typeof _onekeyfe_hd_transport__default.parseConfigure> | undefined;
25
+ messages: ReturnType<typeof _onekeyfe_hd_transport__default.parseTransportConfigure> | undefined;
26
26
  /** Protobuf schema for Protocol V2 transports. */
27
- messagesV2: ReturnType<typeof _onekeyfe_hd_transport__default.parseConfigure> | undefined;
27
+ messagesV2: ReturnType<typeof _onekeyfe_hd_transport__default.parseTransportConfigure> | undefined;
28
28
  private protocolV2SchemaSource;
29
29
  /** Per-path protocol type detected by active wire-level probe. */
30
30
  private deviceProtocol;
@@ -265,6 +265,8 @@ declare class ElectronBleTransport {
265
265
  * the link; `releaseNative()` needs it to cancel that pending connect.
266
266
  */
267
267
  private acquiringDevices;
268
+ private stopped;
269
+ private stopPromise?;
268
270
  private deviceProtocol;
269
271
  private deviceProtocolHints;
270
272
  private deviceMtus;
@@ -293,6 +295,9 @@ declare class ElectronBleTransport {
293
295
  private handleBluetoothError;
294
296
  private cleanupDeviceState;
295
297
  init(logger: any, emitter?: EventEmitter): void;
298
+ private assertRunning;
299
+ stop(): Promise<void>;
300
+ private stopResources;
296
301
  /**
297
302
  * One host subscription for the whole transport lifetime. init() can run
298
303
  * again after an SDK reset, so drop the previous listener first rather than
package/dist/index.js CHANGED
@@ -41,7 +41,7 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
41
41
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
42
42
  };
43
43
 
44
- const { parseConfigure: parseConfigure$1, check: check$1, ProtocolV1: ProtocolV1$1 } = transport__default["default"];
44
+ const { parseTransportConfigure: parseTransportConfigure$1, check: check$1, ProtocolV1: ProtocolV1$1 } = transport__default["default"];
45
45
  const CONFIGURATION_ID = 1;
46
46
  const INTERFACE_ID = 0;
47
47
  const ENDPOINT_ID = 1;
@@ -320,7 +320,7 @@ class WebUsbTransport extends transport.ProtocolV2UsbTransportBase {
320
320
  this.probedDeviceObjects.delete(path);
321
321
  }
322
322
  configure(signedData) {
323
- const messages = parseConfigure$1(signedData);
323
+ const messages = parseTransportConfigure$1(signedData);
324
324
  this.configured = true;
325
325
  this.messages = messages;
326
326
  }
@@ -332,7 +332,7 @@ class WebUsbTransport extends transport.ProtocolV2UsbTransportBase {
332
332
  if (schemaSource === this.protocolV2SchemaSource)
333
333
  return;
334
334
  const hadProtocolV2Schema = this.protocolV2SchemaSource !== undefined;
335
- this.messagesV2 = parseConfigure$1(signedData);
335
+ this.messagesV2 = parseTransportConfigure$1(signedData);
336
336
  this.protocolV2SchemaSource = schemaSource;
337
337
  if (!hadProtocolV2Schema)
338
338
  return;
@@ -1428,8 +1428,7 @@ class WebUsbTransport extends transport.ProtocolV2UsbTransportBase {
1428
1428
  }
1429
1429
  }
1430
1430
  decoded.reset();
1431
- const result = decoded.toBuffer();
1432
- return Buffer.from(result).toString('hex');
1431
+ return decoded.toString('hex');
1433
1432
  });
1434
1433
  }
1435
1434
  release(path) {
@@ -1505,7 +1504,7 @@ function resolveBlePacketCapacity(mtu, maximumPacketCapacity, fallbackPacketCapa
1505
1504
  return Math.min(maximumPacketCapacity, Math.floor(mtu) - BLE_ATT_HEADER_BYTES);
1506
1505
  }
1507
1506
 
1508
- const { parseConfigure, ProtocolV1, check } = transport__default["default"];
1507
+ const { parseTransportConfigure, ProtocolV1, check } = transport__default["default"];
1509
1508
  const toBleDescriptor = (device, protocolType) => (Object.assign(Object.assign({ id: device.id, name: device.name, path: device.id, debug: false, commType: 'electron-ble' }, (device.bleColorCode ? { bleColorCode: device.bleColorCode } : {})), (protocolType ? { protocolType } : {})));
1510
1509
  const invokeNobleBle = (request) => __awaiter(void 0, void 0, void 0, function* () {
1511
1510
  const response = yield request;
@@ -1535,6 +1534,7 @@ class ElectronBleTransport {
1535
1534
  this.retainedDevices = new Set();
1536
1535
  this.protocolV2CallCounts = new Map();
1537
1536
  this.acquiringDevices = new Set();
1537
+ this.stopped = false;
1538
1538
  this.deviceProtocol = new Map();
1539
1539
  this.deviceProtocolHints = new Map();
1540
1540
  this.deviceMtus = new Map();
@@ -1559,7 +1559,7 @@ class ElectronBleTransport {
1559
1559
  (_a = this.v2Assemblers.get(uuid)) === null || _a === void 0 ? void 0 : _a.reset();
1560
1560
  this.rejectProtocolV2Frames(uuid, new Error(reason));
1561
1561
  (_b = this.Log) === null || _b === void 0 ? void 0 : _b.debug('[Electron BLE] Protocol V2 link invalidated:', uuid, reason);
1562
- if (reason.startsWith('Protocol V2 link-fatal error:')) {
1562
+ if (!this.stopped && reason.startsWith('Protocol V2 link-fatal error:')) {
1563
1563
  yield this.releaseNative(uuid, { forceNative: true });
1564
1564
  }
1565
1565
  }),
@@ -1639,6 +1639,8 @@ class ElectronBleTransport {
1639
1639
  }
1640
1640
  init(logger, emitter) {
1641
1641
  var _a, _b;
1642
+ this.stopped = false;
1643
+ this.stopPromise = undefined;
1642
1644
  this.Log = logger;
1643
1645
  this.emitter = emitter;
1644
1646
  if (!((_a = window.desktopApi) === null || _a === void 0 ? void 0 : _a.nobleBle)) {
@@ -1647,6 +1649,41 @@ class ElectronBleTransport {
1647
1649
  this.subscribeHostDisconnects();
1648
1650
  (_b = this.Log) === null || _b === void 0 ? void 0 : _b.debug('[Electron BLE] Transport initialized');
1649
1651
  }
1652
+ assertRunning() {
1653
+ if (this.stopped) {
1654
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'Electron BLE transport is stopped');
1655
+ }
1656
+ }
1657
+ stop() {
1658
+ var _a;
1659
+ this.stopped = true;
1660
+ (_a = this.hostDisconnectCleanup) === null || _a === void 0 ? void 0 : _a.call(this);
1661
+ this.hostDisconnectCleanup = undefined;
1662
+ if (!this.stopPromise) {
1663
+ this.stopPromise = this.stopResources();
1664
+ }
1665
+ return this.stopPromise;
1666
+ }
1667
+ stopResources() {
1668
+ return __awaiter(this, void 0, void 0, function* () {
1669
+ const trackedDeviceIds = new Set([
1670
+ ...this.connectedDevices,
1671
+ ...this.retainedDevices,
1672
+ ...this.acquiringDevices,
1673
+ ...this.notificationCleanups.keys(),
1674
+ ...this.mtuCleanups.keys(),
1675
+ ...this.deviceProtocol.keys(),
1676
+ ...this.v1Buffers.keys(),
1677
+ ...this.v2Assemblers.keys(),
1678
+ ]);
1679
+ yield Promise.all(Array.from(trackedDeviceIds, deviceId => this.releaseNative(deviceId)));
1680
+ this.acquiringDevices.clear();
1681
+ this.protocolV2CallCounts.clear();
1682
+ yield this.protocolV2Links
1683
+ .dispose('Electron BLE transport stopped')
1684
+ .catch(error => { var _a; return (_a = this.Log) === null || _a === void 0 ? void 0 : _a.debug('[Electron BLE] link dispose failed:', error); });
1685
+ });
1686
+ }
1650
1687
  subscribeHostDisconnects() {
1651
1688
  var _a, _b, _c;
1652
1689
  (_a = this.hostDisconnectCleanup) === null || _a === void 0 ? void 0 : _a.call(this);
@@ -1665,7 +1702,7 @@ class ElectronBleTransport {
1665
1702
  });
1666
1703
  }
1667
1704
  configure(signedData) {
1668
- this._messages = parseConfigure(signedData);
1705
+ this._messages = parseTransportConfigure(signedData);
1669
1706
  this.configured = true;
1670
1707
  }
1671
1708
  configureProtocolV2(signedData) {
@@ -1674,7 +1711,7 @@ class ElectronBleTransport {
1674
1711
  return;
1675
1712
  }
1676
1713
  const isReconfiguration = this.protocolV2SchemaConfiguration !== undefined;
1677
- this._messagesV2 = parseConfigure(signedData);
1714
+ this._messagesV2 = parseTransportConfigure(signedData);
1678
1715
  this.protocolV2SchemaConfiguration = configuration;
1679
1716
  if (isReconfiguration) {
1680
1717
  this.protocolV2Links
@@ -1730,12 +1767,15 @@ class ElectronBleTransport {
1730
1767
  this.runPromise = null;
1731
1768
  this.runPromiseDeviceId = null;
1732
1769
  }
1770
+ this.assertRunning();
1733
1771
  this.acquiringDevices.add(uuid);
1772
+ let connectAttempted = false;
1734
1773
  try {
1735
1774
  if (!((_a = window.desktopApi) === null || _a === void 0 ? void 0 : _a.nobleBle)) {
1736
1775
  throw new Error('Noble BLE API not available');
1737
1776
  }
1738
1777
  const device = yield invokeNobleBle(window.desktopApi.nobleBle.getDevice(uuid));
1778
+ this.assertRunning();
1739
1779
  if (!device) {
1740
1780
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceNotFound, `Device ${uuid} not found`);
1741
1781
  }
@@ -1752,12 +1792,14 @@ class ElectronBleTransport {
1752
1792
  this.deviceProtocolHints.set(uuid, protocolHint);
1753
1793
  }
1754
1794
  try {
1795
+ connectAttempted = true;
1755
1796
  yield invokeNobleBle(window.desktopApi.nobleBle.connect(uuid));
1756
1797
  this.connectedDevices.add(uuid);
1757
1798
  }
1758
1799
  catch (error) {
1759
1800
  this.handleBluetoothError(error);
1760
1801
  }
1802
+ this.assertRunning();
1761
1803
  const mtuCleanup = this.createMtuSubscription(uuid);
1762
1804
  if (mtuCleanup) {
1763
1805
  this.mtuCleanups.set(uuid, mtuCleanup);
@@ -1771,9 +1813,11 @@ class ElectronBleTransport {
1771
1813
  this.handleBluetoothError(error);
1772
1814
  }
1773
1815
  yield this.refreshBlePacketCapacity(uuid);
1816
+ this.assertRunning();
1774
1817
  const cleanup = this.createNotificationSubscription(uuid);
1775
1818
  this.notificationCleanups.set(uuid, cleanup);
1776
1819
  const protocolType = yield this.detectProtocol(uuid, expectedProtocol, protocolHint);
1820
+ this.assertRunning();
1777
1821
  if (protocolType === 'V2') {
1778
1822
  (_c = this.Log) === null || _c === void 0 ? void 0 : _c.debug('[Electron BLE] Protocol V2 write configured', {
1779
1823
  writeMode: 'withoutResponse',
@@ -1787,7 +1831,7 @@ class ElectronBleTransport {
1787
1831
  (_e = this.Log) === null || _e === void 0 ? void 0 : _e.error('[Electron BLE] acquire failed:', error);
1788
1832
  try {
1789
1833
  const nobleBle = (_f = window.desktopApi) === null || _f === void 0 ? void 0 : _f.nobleBle;
1790
- if (nobleBle) {
1834
+ if (nobleBle && !this.stopped && (connectAttempted || this.connectedDevices.has(uuid))) {
1791
1835
  if (this.connectedDevices.has(uuid)) {
1792
1836
  yield invokeNobleBle(nobleBle.unsubscribe(uuid)).catch(cleanupError => {
1793
1837
  var _a;
@@ -1917,11 +1961,14 @@ class ElectronBleTransport {
1917
1961
  }
1918
1962
  const probeOrder = protocolHint === 'V2' || this.deviceProtocol.get(uuid) === 'V2' ? ['V2', 'V1'] : ['V1', 'V2'];
1919
1963
  for (let i = 0; i < probeOrder.length; i += 1) {
1964
+ this.assertRunning();
1920
1965
  const protocol = probeOrder[i];
1921
1966
  if (i > 0) {
1922
1967
  yield this.resetProbeStateAfterProtocolProbe(uuid, probeOrder[i - 1]);
1968
+ this.assertRunning();
1923
1969
  }
1924
1970
  const detected = protocol === 'V1' ? yield this.probeProtocolV1(uuid) : yield this.probeProtocolV2(uuid);
1971
+ this.assertRunning();
1925
1972
  if (detected) {
1926
1973
  this.deviceProtocol.set(uuid, protocol);
1927
1974
  (_c = this.Log) === null || _c === void 0 ? void 0 : _c.debug(`[Electron BLE] detectProtocol: uuid=${uuid} -> ${protocol}`);
@@ -2015,12 +2062,14 @@ class ElectronBleTransport {
2015
2062
  writeOnce(uuid, hexData) {
2016
2063
  var _a;
2017
2064
  return __awaiter(this, void 0, void 0, function* () {
2065
+ this.assertRunning();
2018
2066
  const nobleBle = (_a = window.desktopApi) === null || _a === void 0 ? void 0 : _a.nobleBle;
2019
2067
  if (!nobleBle) {
2020
2068
  throw new Error('Noble BLE API not available');
2021
2069
  }
2022
2070
  try {
2023
2071
  yield invokeNobleBle(nobleBle.write(uuid, hexData, { pacingDelayMs: 0 }));
2072
+ this.assertRunning();
2024
2073
  }
2025
2074
  catch (error) {
2026
2075
  this.handleBluetoothError(error);
package/dist/webusb.d.ts CHANGED
@@ -18,8 +18,8 @@ export default class WebUsbTransport extends ProtocolV2UsbTransportBase<string>
18
18
  private handleOperationSequence;
19
19
  private deviceLogSequence;
20
20
  private deviceLogIds;
21
- messages: ReturnType<typeof transport.parseConfigure> | undefined;
22
- messagesV2: ReturnType<typeof transport.parseConfigure> | undefined;
21
+ messages: ReturnType<typeof transport.parseTransportConfigure> | undefined;
22
+ messagesV2: ReturnType<typeof transport.parseTransportConfigure> | undefined;
23
23
  private protocolV2SchemaSource;
24
24
  private deviceProtocol;
25
25
  private confirmedDeviceProtocols;
@@ -1 +1 @@
1
- {"version":3,"file":"webusb.d.ts","sourceRoot":"","sources":["../src/webusb.ts"],"names":[],"mappings":";;AACA,OAAO,SAAS,EAAE,EAQhB,0BAA0B,EAG3B,MAAM,wBAAwB,CAAC;AAahC,OAAO,KAAK,YAAY,MAAM,QAAQ,CAAC;AACvC,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;AA2BD,UAAU,oBAAoB;IAC5B,gBAAgB,CAAC,EAAE,YAAY,CAAC;IAChC,sBAAsB,CAAC,EAAE,OAAO,CAAC;CAClC;AAmCD,MAAM,CAAC,OAAO,OAAO,eAAgB,SAAQ,0BAA0B,CAAC,MAAM,CAAC;IA+EjE,OAAO,CAAC,QAAQ,CAAC,aAAa;IA9E1C,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAmC;IAEvE,OAAO,CAAC,uBAAuB,CAAK;IAEpC,OAAO,CAAC,iBAAiB,CAAK;IAE9B,OAAO,CAAC,YAAY,CAAoC;IAExD,QAAQ,EAAE,UAAU,CAAC,OAAO,SAAS,CAAC,cAAc,CAAC,GAAG,SAAS,CAAC;IAGlE,UAAU,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AAE,qBAAqB,GAC9B,OAAO,CAAC,UAAU,CAAC;cASN,4BAA4B,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAI1F,SAAS,CAAC,8BAA8B,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAKrE,SAAS,CAAC,+BAA+B,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,KAAK;IAWjF,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,YAAY,GAAG,SAAS;CAGxD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onekeyfe/hd-transport-web-device",
3
- "version": "1.2.11-alpha.1",
3
+ "version": "1.2.11-alpha.11",
4
4
  "author": "OneKey",
5
5
  "homepage": "https://github.com/OneKeyHQ/hardware-js-sdk#readme",
6
6
  "license": "MIT",
@@ -21,13 +21,14 @@
21
21
  "lint:fix": "eslint . --fix"
22
22
  },
23
23
  "dependencies": {
24
- "@onekeyfe/hd-shared": "1.2.11-alpha.1",
25
- "@onekeyfe/hd-transport": "1.2.11-alpha.1"
24
+ "@onekeyfe/hd-shared": "1.2.11-alpha.11",
25
+ "@onekeyfe/hd-transport": "1.2.11-alpha.11",
26
+ "bytebuffer": "^5.0.1"
26
27
  },
27
28
  "devDependencies": {
28
- "@onekeyfe/hd-transport-electron": "1.2.11-alpha.1",
29
+ "@onekeyfe/hd-transport-electron": "1.2.11-alpha.11",
29
30
  "@types/w3c-web-usb": "^1.0.6",
30
31
  "@types/web-bluetooth": "^0.0.17"
31
32
  },
32
- "gitHead": "2d32b0985ac1ea5956fa7edf9d43b29c77450f6c"
33
+ "gitHead": "83d4bbc36cf5473a807b94f703067f7ea096c8c4"
33
34
  }
@@ -34,7 +34,7 @@ import type {
34
34
  } from '@onekeyfe/hd-transport';
35
35
  import type EventEmitter from 'events';
36
36
 
37
- const { parseConfigure, ProtocolV1, check } = transport;
37
+ const { parseTransportConfigure, ProtocolV1, check } = transport;
38
38
 
39
39
  declare global {
40
40
  interface Window {
@@ -98,9 +98,9 @@ const PROTOCOL_V2_PROBE_TIMEOUT_MS = 5000;
98
98
  * after a Protocol V1 GetFeatures timeout by probing Protocol V2 Ping.
99
99
  */
100
100
  export default class ElectronBleTransport {
101
- private _messages: ReturnType<typeof transport.parseConfigure> | undefined;
101
+ private _messages: ReturnType<typeof transport.parseTransportConfigure> | undefined;
102
102
 
103
- private _messagesV2: ReturnType<typeof transport.parseConfigure> | undefined;
103
+ private _messagesV2: ReturnType<typeof transport.parseTransportConfigure> | undefined;
104
104
 
105
105
  private protocolV2SchemaConfiguration: string | undefined;
106
106
 
@@ -131,6 +131,10 @@ export default class ElectronBleTransport {
131
131
  */
132
132
  private acquiringDevices: Set<string> = new Set();
133
133
 
134
+ private stopped = false;
135
+
136
+ private stopPromise?: Promise<void>;
137
+
134
138
  private deviceProtocol: Map<string, ProtocolType> = new Map();
135
139
 
136
140
  private deviceProtocolHints: Map<string, ProtocolType> = new Map();
@@ -162,7 +166,7 @@ export default class ElectronBleTransport {
162
166
  this.v2Assemblers.get(uuid)?.reset();
163
167
  this.rejectProtocolV2Frames(uuid, new Error(reason));
164
168
  this.Log?.debug('[Electron BLE] Protocol V2 link invalidated:', uuid, reason);
165
- if (reason.startsWith('Protocol V2 link-fatal error:')) {
169
+ if (!this.stopped && reason.startsWith('Protocol V2 link-fatal error:')) {
166
170
  await this.releaseNative(uuid, { forceNative: true });
167
171
  }
168
172
  },
@@ -269,6 +273,8 @@ export default class ElectronBleTransport {
269
273
  }
270
274
 
271
275
  init(logger: any, emitter?: EventEmitter) {
276
+ this.stopped = false;
277
+ this.stopPromise = undefined;
272
278
  this.Log = logger;
273
279
  this.emitter = emitter;
274
280
 
@@ -284,6 +290,43 @@ export default class ElectronBleTransport {
284
290
  this.Log?.debug('[Electron BLE] Transport initialized');
285
291
  }
286
292
 
293
+ private assertRunning() {
294
+ if (this.stopped) {
295
+ throw ERRORS.TypedError(HardwareErrorCode.RuntimeError, 'Electron BLE transport is stopped');
296
+ }
297
+ }
298
+
299
+ stop(): Promise<void> {
300
+ this.stopped = true;
301
+ this.hostDisconnectCleanup?.();
302
+ this.hostDisconnectCleanup = undefined;
303
+
304
+ if (!this.stopPromise) {
305
+ this.stopPromise = this.stopResources();
306
+ }
307
+ return this.stopPromise;
308
+ }
309
+
310
+ private async stopResources(): Promise<void> {
311
+ const trackedDeviceIds = new Set<string>([
312
+ ...this.connectedDevices,
313
+ ...this.retainedDevices,
314
+ ...this.acquiringDevices,
315
+ ...this.notificationCleanups.keys(),
316
+ ...this.mtuCleanups.keys(),
317
+ ...this.deviceProtocol.keys(),
318
+ ...this.v1Buffers.keys(),
319
+ ...this.v2Assemblers.keys(),
320
+ ]);
321
+
322
+ await Promise.all(Array.from(trackedDeviceIds, deviceId => this.releaseNative(deviceId)));
323
+ this.acquiringDevices.clear();
324
+ this.protocolV2CallCounts.clear();
325
+ await this.protocolV2Links
326
+ .dispose('Electron BLE transport stopped')
327
+ .catch(error => this.Log?.debug('[Electron BLE] link dispose failed:', error));
328
+ }
329
+
287
330
  /**
288
331
  * One host subscription for the whole transport lifetime. init() can run
289
332
  * again after an SDK reset, so drop the previous listener first rather than
@@ -322,7 +365,7 @@ export default class ElectronBleTransport {
322
365
  }
323
366
 
324
367
  configure(signedData: any) {
325
- this._messages = parseConfigure(signedData);
368
+ this._messages = parseTransportConfigure(signedData);
326
369
  this.configured = true;
327
370
  }
328
371
 
@@ -333,7 +376,7 @@ export default class ElectronBleTransport {
333
376
  }
334
377
 
335
378
  const isReconfiguration = this.protocolV2SchemaConfiguration !== undefined;
336
- this._messagesV2 = parseConfigure(signedData);
379
+ this._messagesV2 = parseTransportConfigure(signedData);
337
380
  this.protocolV2SchemaConfiguration = configuration;
338
381
  if (isReconfiguration) {
339
382
  this.protocolV2Links
@@ -390,13 +433,16 @@ export default class ElectronBleTransport {
390
433
  this.runPromiseDeviceId = null;
391
434
  }
392
435
 
436
+ this.assertRunning();
393
437
  this.acquiringDevices.add(uuid);
438
+ let connectAttempted = false;
394
439
  try {
395
440
  if (!window.desktopApi?.nobleBle) {
396
441
  throw new Error('Noble BLE API not available');
397
442
  }
398
443
 
399
444
  const device = await invokeNobleBle(window.desktopApi.nobleBle.getDevice(uuid));
445
+ this.assertRunning();
400
446
  if (!device) {
401
447
  throw ERRORS.TypedError(HardwareErrorCode.DeviceNotFound, `Device ${uuid} not found`);
402
448
  }
@@ -420,11 +466,13 @@ export default class ElectronBleTransport {
420
466
  }
421
467
 
422
468
  try {
469
+ connectAttempted = true;
423
470
  await invokeNobleBle(window.desktopApi.nobleBle.connect(uuid));
424
471
  this.connectedDevices.add(uuid);
425
472
  } catch (error) {
426
473
  this.handleBluetoothError(error);
427
474
  }
475
+ this.assertRunning();
428
476
 
429
477
  const mtuCleanup = this.createMtuSubscription(uuid);
430
478
  if (mtuCleanup) {
@@ -440,11 +488,13 @@ export default class ElectronBleTransport {
440
488
  this.handleBluetoothError(error);
441
489
  }
442
490
  await this.refreshBlePacketCapacity(uuid);
491
+ this.assertRunning();
443
492
 
444
493
  const cleanup = this.createNotificationSubscription(uuid);
445
494
  this.notificationCleanups.set(uuid, cleanup);
446
495
 
447
496
  const protocolType = await this.detectProtocol(uuid, expectedProtocol, protocolHint);
497
+ this.assertRunning();
448
498
  if (protocolType === 'V2') {
449
499
  this.Log?.debug('[Electron BLE] Protocol V2 write configured', {
450
500
  writeMode: 'withoutResponse',
@@ -461,7 +511,7 @@ export default class ElectronBleTransport {
461
511
  this.Log?.error('[Electron BLE] acquire failed:', error);
462
512
  try {
463
513
  const nobleBle = window.desktopApi?.nobleBle;
464
- if (nobleBle) {
514
+ if (nobleBle && !this.stopped && (connectAttempted || this.connectedDevices.has(uuid))) {
465
515
  if (this.connectedDevices.has(uuid)) {
466
516
  await invokeNobleBle(nobleBle.unsubscribe(uuid)).catch(cleanupError => {
467
517
  this.Log?.debug('[Electron BLE] acquire unsubscribe failed:', cleanupError);
@@ -616,14 +666,17 @@ export default class ElectronBleTransport {
616
666
  protocolHint === 'V2' || this.deviceProtocol.get(uuid) === 'V2' ? ['V2', 'V1'] : ['V1', 'V2'];
617
667
 
618
668
  for (let i = 0; i < probeOrder.length; i += 1) {
669
+ this.assertRunning();
619
670
  const protocol = probeOrder[i];
620
671
  if (i > 0) {
621
672
  // Keep the physical BLE link while switching probes. Reconnecting here can
622
673
  // summon a second OS pairing prompt for a device that is still onboarding.
623
674
  await this.resetProbeStateAfterProtocolProbe(uuid, probeOrder[i - 1]);
675
+ this.assertRunning();
624
676
  }
625
677
  const detected =
626
678
  protocol === 'V1' ? await this.probeProtocolV1(uuid) : await this.probeProtocolV2(uuid);
679
+ this.assertRunning();
627
680
  if (detected) {
628
681
  this.deviceProtocol.set(uuid, protocol);
629
682
  this.Log?.debug(`[Electron BLE] detectProtocol: uuid=${uuid} -> ${protocol}`);
@@ -722,6 +775,7 @@ export default class ElectronBleTransport {
722
775
  }
723
776
 
724
777
  private async writeOnce(uuid: string, hexData: string): Promise<void> {
778
+ this.assertRunning();
725
779
  const nobleBle = window.desktopApi?.nobleBle;
726
780
  if (!nobleBle) {
727
781
  throw new Error('Noble BLE API not available');
@@ -729,6 +783,7 @@ export default class ElectronBleTransport {
729
783
 
730
784
  try {
731
785
  await invokeNobleBle(nobleBle.write(uuid, hexData, { pacingDelayMs: 0 }));
786
+ this.assertRunning();
732
787
  } catch (error) {
733
788
  this.handleBluetoothError(error);
734
789
  }
package/src/webusb.ts CHANGED
@@ -33,7 +33,7 @@ import type {
33
33
  TransportCallOptions,
34
34
  } from '@onekeyfe/hd-transport';
35
35
 
36
- const { parseConfigure, check, ProtocolV1 } = transport;
36
+ const { parseTransportConfigure, check, ProtocolV1 } = transport;
37
37
 
38
38
  const CONFIGURATION_ID = 1;
39
39
  const INTERFACE_ID = 0;
@@ -135,10 +135,10 @@ export default class WebUsbTransport extends ProtocolV2UsbTransportBase<string>
135
135
 
136
136
  private deviceLogIds = new WeakMap<USBDevice, number>();
137
137
 
138
- messages: ReturnType<typeof transport.parseConfigure> | undefined;
138
+ messages: ReturnType<typeof transport.parseTransportConfigure> | undefined;
139
139
 
140
140
  /** Protobuf schema for Protocol V2 transports. */
141
- messagesV2: ReturnType<typeof transport.parseConfigure> | undefined;
141
+ messagesV2: ReturnType<typeof transport.parseTransportConfigure> | undefined;
142
142
 
143
143
  private protocolV2SchemaSource: string | undefined;
144
144
 
@@ -505,7 +505,7 @@ export default class WebUsbTransport extends ProtocolV2UsbTransportBase<string>
505
505
  * Configure Protocol V1 protobuf schema (legacy chunked 0x3F framing).
506
506
  */
507
507
  configure(signedData: any) {
508
- const messages = parseConfigure(signedData);
508
+ const messages = parseTransportConfigure(signedData);
509
509
  this.configured = true;
510
510
  this.messages = messages;
511
511
  }
@@ -521,7 +521,7 @@ export default class WebUsbTransport extends ProtocolV2UsbTransportBase<string>
521
521
  if (schemaSource === this.protocolV2SchemaSource) return;
522
522
 
523
523
  const hadProtocolV2Schema = this.protocolV2SchemaSource !== undefined;
524
- this.messagesV2 = parseConfigure(signedData);
524
+ this.messagesV2 = parseTransportConfigure(signedData);
525
525
  this.protocolV2SchemaSource = schemaSource;
526
526
  if (!hadProtocolV2Schema) return;
527
527
 
@@ -1828,8 +1828,7 @@ export default class WebUsbTransport extends ProtocolV2UsbTransportBase<string>
1828
1828
  }
1829
1829
  }
1830
1830
  decoded.reset();
1831
- const result = decoded.toBuffer();
1832
- return Buffer.from(result as unknown as ArrayBuffer).toString('hex');
1831
+ return decoded.toString('hex');
1833
1832
  }
1834
1833
 
1835
1834
  /**