@onekeyfe/hd-transport-web-device 1.2.11-alpha.19 → 1.2.11-alpha.20

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.
@@ -19,23 +19,19 @@ import {
19
19
  HardwareErrorCodeMessage,
20
20
  createDeferred,
21
21
  isHeaderChunk,
22
- isLegacyProtocolV1BleName,
23
22
  } from '@onekeyfe/hd-shared';
24
23
 
25
24
  import { resolveBlePacketCapacity } from './ble-packet-capacity';
26
25
 
27
26
  import type { Deferred } from '@onekeyfe/hd-shared';
28
- import type {
29
- DesktopAPI,
30
- NobleBleIpcErrorResponse,
31
- NobleBleWriteOptions,
32
- } from '@onekeyfe/hd-transport-electron';
27
+ import type { DesktopAPI, NobleBleIpcErrorResponse } from '@onekeyfe/hd-transport-electron';
33
28
  import type {
34
29
  AcquireInput,
35
30
  OneKeyDeviceInfo,
36
31
  ProtocolType,
37
32
  ProtocolV2CallContext,
38
33
  TransportCallOptions,
34
+ TransportReleaseOptions,
39
35
  } from '@onekeyfe/hd-transport';
40
36
  import type EventEmitter from 'events';
41
37
 
@@ -52,8 +48,6 @@ export type BleAcquireInput = {
52
48
  forceCleanRunPromise?: boolean;
53
49
  expectedProtocol?: ProtocolType;
54
50
  protocolHint?: ProtocolType;
55
- onlyConnectBleDevice?: boolean;
56
- abortSignal?: AbortSignal;
57
51
  };
58
52
 
59
53
  interface PacketProcessResult {
@@ -98,43 +92,6 @@ const BLE_WRITE_DELAY_MS = 5;
98
92
  const PROTOCOL_PROBE_TIMEOUT_MS = 3000;
99
93
  const PROTOCOL_V2_PROBE_TIMEOUT_MS = 5000;
100
94
 
101
- const shouldRethrowElectronProtocolProbeError = (error: unknown): boolean => {
102
- if (isProtocolV2LinkDisabledError(error)) {
103
- return true;
104
- }
105
- const code = (error as { errorCode?: unknown })?.errorCode;
106
- // Pairing rejections, disconnects, and missing GATT state are link failures rather than
107
- // evidence of a protocol mismatch. Rethrow them instead of entering wake or probing V2.
108
- return (
109
- code === HardwareErrorCode.TransportCallInProgress ||
110
- code === HardwareErrorCode.BleConnectedError ||
111
- code === HardwareErrorCode.BleDeviceNotBonded ||
112
- code === HardwareErrorCode.BleDeviceBondedCanceled ||
113
- code === HardwareErrorCode.BleDeviceDisconnected ||
114
- code === HardwareErrorCode.BleCharacteristicNotFound ||
115
- code === HardwareErrorCode.BleCharacteristicNotifyError ||
116
- code === HardwareErrorCode.BleCharacteristicNotifyChangeFailure ||
117
- code === HardwareErrorCode.BleServiceNotFound ||
118
- code === HardwareErrorCode.BlePoweredOff ||
119
- code === HardwareErrorCode.BleUnsupported ||
120
- code === HardwareErrorCode.BleLocationError
121
- );
122
- };
123
-
124
- const isUnstartedElectronWakeError = (error: unknown): boolean => {
125
- const candidate = error as { errorCode?: unknown; params?: { writeRejected?: unknown } };
126
- const code = candidate?.errorCode;
127
- // Errors returned before a GATT write is submitted or explicitly rejected by the host
128
- // (e.g. Windows pairing rejection with status: 3) leave the peripheral untouched.
129
- return (
130
- candidate?.params?.writeRejected === true ||
131
- code === HardwareErrorCode.BleCharacteristicNotFound ||
132
- code === HardwareErrorCode.BlePoweredOff ||
133
- code === HardwareErrorCode.BleUnsupported ||
134
- code === HardwareErrorCode.BleLocationError
135
- );
136
- };
137
-
138
95
  /**
139
96
  * Desktop Electron BLE transport with automatic Protocol V1/V2 detection.
140
97
  *
@@ -183,16 +140,6 @@ export default class ElectronBleTransport {
183
140
 
184
141
  private deviceProtocolHints: Map<string, ProtocolType> = new Map();
185
142
 
186
- private silentDetections = new Map<string, 'silent' | 'woken'>();
187
-
188
- private probeResponseTimeoutErrors = new WeakSet<Error>();
189
-
190
- private lastV1ProbeFailedWithoutTimeout: Set<string> = new Set();
191
-
192
- private acquireGenerations: Map<string, number> = new Map();
193
-
194
- private nextAcquireGeneration = 1;
195
-
196
143
  private deviceMtus: Map<string, number> = new Map();
197
144
 
198
145
  private devicePacketCapacities: Map<string, number> = new Map();
@@ -305,7 +252,6 @@ export default class ElectronBleTransport {
305
252
  // and doesn't depend on connection state. Preserving it avoids redundant V1 probe on reconnect.
306
253
  this.v1Buffers.delete(deviceId);
307
254
  this.v2Assemblers.delete(deviceId);
308
- this.lastV1ProbeFailedWithoutTimeout.delete(deviceId);
309
255
  this.resetProtocolV2Frames(deviceId);
310
256
  this.notificationTokens.delete(deviceId);
311
257
  if (this.runPromise && this.runPromiseDeviceId === deviceId) {
@@ -376,10 +322,7 @@ export default class ElectronBleTransport {
376
322
 
377
323
  await Promise.all(Array.from(trackedDeviceIds, deviceId => this.releaseNative(deviceId)));
378
324
  this.acquiringDevices.clear();
379
- this.acquireGenerations.clear();
380
- this.lastV1ProbeFailedWithoutTimeout.clear();
381
325
  this.protocolV2CallCounts.clear();
382
- this.silentDetections.clear();
383
326
  await this.protocolV2Links
384
327
  .dispose('Electron BLE transport stopped')
385
328
  .catch(error => this.Log?.debug('[Electron BLE] link dispose failed:', error));
@@ -471,20 +414,6 @@ export default class ElectronBleTransport {
471
414
  if (!uuid) {
472
415
  throw ERRORS.TypedError(HardwareErrorCode.BleRequiredUUID);
473
416
  }
474
- if (input.abortSignal?.aborted) {
475
- throw ERRORS.TypedError(HardwareErrorCode.DeviceInterruptedFromUser);
476
- }
477
-
478
- const acquireGeneration = this.nextAcquireGeneration;
479
- this.nextAcquireGeneration += 1;
480
- this.acquireGenerations.set(uuid, acquireGeneration);
481
- const isCurrentAcquire = () => this.acquireGenerations.get(uuid) === acquireGeneration;
482
- const assertAcquireActive = () => {
483
- this.assertRunning();
484
- if (input.abortSignal?.aborted || !isCurrentAcquire()) {
485
- throw ERRORS.TypedError(HardwareErrorCode.DeviceInterruptedFromUser);
486
- }
487
- };
488
417
 
489
418
  const retainedToken =
490
419
  this.retainedDevices.has(uuid) &&
@@ -498,8 +427,6 @@ export default class ElectronBleTransport {
498
427
  await this.release(uuid);
499
428
  }
500
429
 
501
- assertAcquireActive();
502
-
503
430
  if (forceCleanRunPromise && this.runPromise) {
504
431
  const error = ERRORS.TypedError(HardwareErrorCode.BleForceCleanRunPromise);
505
432
  this.runPromise.reject(error);
@@ -507,6 +434,7 @@ export default class ElectronBleTransport {
507
434
  this.runPromiseDeviceId = null;
508
435
  }
509
436
 
437
+ this.assertRunning();
510
438
  this.acquiringDevices.add(uuid);
511
439
  let connectAttempted = false;
512
440
  try {
@@ -515,7 +443,7 @@ export default class ElectronBleTransport {
515
443
  }
516
444
 
517
445
  const device = await invokeNobleBle(window.desktopApi.nobleBle.getDevice(uuid));
518
- assertAcquireActive();
446
+ this.assertRunning();
519
447
  if (!device) {
520
448
  throw ERRORS.TypedError(HardwareErrorCode.DeviceNotFound, `Device ${uuid} not found`);
521
449
  }
@@ -541,12 +469,11 @@ export default class ElectronBleTransport {
541
469
  try {
542
470
  connectAttempted = true;
543
471
  await invokeNobleBle(window.desktopApi.nobleBle.connect(uuid));
544
- assertAcquireActive();
545
472
  this.connectedDevices.add(uuid);
546
473
  } catch (error) {
547
474
  this.handleBluetoothError(error);
548
475
  }
549
- assertAcquireActive();
476
+ this.assertRunning();
550
477
 
551
478
  const mtuCleanup = this.createMtuSubscription(uuid);
552
479
  if (mtuCleanup) {
@@ -561,20 +488,14 @@ export default class ElectronBleTransport {
561
488
  } catch (error) {
562
489
  this.handleBluetoothError(error);
563
490
  }
564
- assertAcquireActive();
565
- const connectedDevice = await this.refreshBlePacketCapacity(uuid);
566
- assertAcquireActive();
567
- const resolvedDeviceName = connectedDevice?.name || device.name;
491
+ await this.refreshBlePacketCapacity(uuid);
492
+ this.assertRunning();
568
493
 
569
494
  const cleanup = this.createNotificationSubscription(uuid);
570
495
  this.notificationCleanups.set(uuid, cleanup);
571
496
 
572
- const protocolType = await this.detectProtocol(uuid, expectedProtocol, protocolHint, {
573
- isKnownLegacyV1Device: isLegacyProtocolV1BleName(resolvedDeviceName),
574
- onlyConnectBleDevice: input.onlyConnectBleDevice,
575
- abortSignal: input.abortSignal,
576
- });
577
- assertAcquireActive();
497
+ const protocolType = await this.detectProtocol(uuid, expectedProtocol, protocolHint);
498
+ this.assertRunning();
578
499
  if (protocolType === 'V2') {
579
500
  this.Log?.debug('[Electron BLE] Protocol V2 write configured', {
580
501
  writeMode: 'withoutResponse',
@@ -584,39 +505,40 @@ export default class ElectronBleTransport {
584
505
  }
585
506
 
586
507
  return {
587
- ...toBleDescriptor({ id: device.id, name: resolvedDeviceName }, protocolType),
508
+ ...toBleDescriptor({ id: device.id, name: device.name }, protocolType),
588
509
  uuid,
589
510
  };
590
511
  } catch (error) {
591
512
  this.Log?.error('[Electron BLE] acquire failed:', error);
592
- if (isCurrentAcquire()) {
593
- try {
594
- const nobleBle = window.desktopApi?.nobleBle;
595
- if (nobleBle && !this.stopped && (connectAttempted || this.connectedDevices.has(uuid))) {
596
- if (this.connectedDevices.has(uuid)) {
597
- await invokeNobleBle(nobleBle.unsubscribe(uuid)).catch(cleanupError => {
598
- this.Log?.debug('[Electron BLE] acquire unsubscribe failed:', cleanupError);
599
- });
600
- }
601
- await invokeNobleBle(nobleBle.disconnect(uuid));
513
+ try {
514
+ const nobleBle = window.desktopApi?.nobleBle;
515
+ if (nobleBle && !this.stopped && (connectAttempted || this.connectedDevices.has(uuid))) {
516
+ if (this.connectedDevices.has(uuid)) {
517
+ await invokeNobleBle(nobleBle.unsubscribe(uuid)).catch(cleanupError => {
518
+ this.Log?.debug('[Electron BLE] acquire unsubscribe failed:', cleanupError);
519
+ });
602
520
  }
603
- } catch (cleanupError) {
604
- this.Log?.debug('[Electron BLE] acquire cleanup failed:', cleanupError);
521
+ await invokeNobleBle(nobleBle.disconnect(uuid));
605
522
  }
606
- this.cleanupDeviceState(uuid);
523
+ } catch (cleanupError) {
524
+ this.Log?.debug('[Electron BLE] acquire cleanup failed:', cleanupError);
607
525
  }
608
- throw this.normalizeBluetoothError(error);
526
+ this.cleanupDeviceState(uuid);
527
+ this.handleBluetoothError(error);
609
528
  } finally {
610
- if (isCurrentAcquire()) {
611
- this.acquiringDevices.delete(uuid);
612
- }
529
+ this.acquiringDevices.delete(uuid);
613
530
  }
614
531
  }
615
532
 
616
- async release(id: string, onclose?: boolean, keepSession?: boolean) {
533
+ async release(
534
+ id: string,
535
+ onclose?: boolean,
536
+ keepSession?: boolean,
537
+ options?: TransportReleaseOptions
538
+ ) {
617
539
  try {
618
540
  const retainLink =
619
- keepSession === true &&
541
+ (keepSession === true || options?.retainLink === true) &&
620
542
  !onclose &&
621
543
  this.connectedDevices.has(id) &&
622
544
  this.deviceProtocol.get(id) === 'V2' &&
@@ -717,17 +639,8 @@ export default class ElectronBleTransport {
717
639
  private async detectProtocol(
718
640
  uuid: string,
719
641
  expectedProtocol?: ProtocolType,
720
- protocolHint?: ProtocolType,
721
- options: {
722
- isKnownLegacyV1Device?: boolean;
723
- onlyConnectBleDevice?: boolean;
724
- abortSignal?: AbortSignal;
725
- } = {}
642
+ protocolHint?: ProtocolType
726
643
  ): Promise<ProtocolType> {
727
- if (options.abortSignal?.aborted) {
728
- throw ERRORS.TypedError(HardwareErrorCode.DeviceInterruptedFromUser);
729
- }
730
-
731
644
  // A declared V1 is taken at face value, as the React Native transport
732
645
  // already does on iOS: the caller reads the protocol off its own device
733
646
  // record, so probing re-asks a question that is already answered and adds a
@@ -767,104 +680,20 @@ export default class ElectronBleTransport {
767
680
  await this.resetProbeStateAfterProtocolProbe(uuid, probeOrder[i - 1]);
768
681
  this.assertRunning();
769
682
  }
770
- this.lastV1ProbeFailedWithoutTimeout.delete(uuid);
771
- let detected =
683
+ const detected =
772
684
  protocol === 'V1' ? await this.probeProtocolV1(uuid) : await this.probeProtocolV2(uuid);
773
- if (!detected && protocol === 'V1' && !this.lastV1ProbeFailedWithoutTimeout.has(uuid)) {
774
- detected = await this.wakeSilentProtocolV1Device(uuid, probeOrder, options);
775
- }
776
685
  this.assertRunning();
777
686
  if (detected) {
778
687
  this.deviceProtocol.set(uuid, protocol);
779
- this.silentDetections.delete(uuid);
780
688
  this.Log?.debug(`[Electron BLE] detectProtocol: uuid=${uuid} -> ${protocol}`);
781
689
  return protocol;
782
690
  }
783
691
  }
784
692
 
785
- if (!this.silentDetections.has(uuid)) {
786
- this.silentDetections.set(uuid, 'silent');
787
- }
788
693
  this.deviceProtocol.delete(uuid);
789
694
  throw this.createProtocolDetectionError();
790
695
  }
791
696
 
792
- private async wakeSilentProtocolV1Device(
793
- uuid: string,
794
- probeOrder: ProtocolType[],
795
- options: {
796
- isKnownLegacyV1Device?: boolean;
797
- onlyConnectBleDevice?: boolean;
798
- abortSignal?: AbortSignal;
799
- } = {}
800
- ): Promise<boolean> {
801
- if (
802
- options.onlyConnectBleDevice ||
803
- probeOrder[0] !== 'V1' ||
804
- this.silentDetections.get(uuid) === 'woken' ||
805
- (!options.isKnownLegacyV1Device && this.silentDetections.get(uuid) !== 'silent')
806
- ) {
807
- return false;
808
- }
809
- if (options.abortSignal?.aborted) {
810
- throw ERRORS.TypedError(HardwareErrorCode.DeviceInterruptedFromUser);
811
- }
812
- this.assertRunning();
813
-
814
- // A timed-out GetFeatures probe retires the renderer notification listener;
815
- // re-attach it on the live physical link before sending Initialize.
816
- await this.resetProbeStateAfterProtocolProbe(uuid, 'V1');
817
- if (options.abortSignal?.aborted) {
818
- throw ERRORS.TypedError(HardwareErrorCode.DeviceInterruptedFromUser);
819
- }
820
- this.assertRunning();
821
-
822
- const previousSilentState = this.silentDetections.get(uuid);
823
- this.silentDetections.set(uuid, 'woken');
824
- this.Log?.debug('[Electron BLE] sending Protocol V1 Initialize wake', {
825
- connectIdSuffix: uuid.slice(-8),
826
- source: options.isKnownLegacyV1Device ? 'legacy-v1-name' : 'silent-retry',
827
- });
828
-
829
- let answeredV1 = false;
830
- try {
831
- this.deviceProtocol.set(uuid, 'V1');
832
- const response = await this.callProtocolV1(
833
- uuid,
834
- 'Initialize',
835
- {},
836
- { timeoutMs: PROTOCOL_PROBE_TIMEOUT_MS },
837
- { oneShot: true },
838
- true
839
- );
840
- answeredV1 = typeof response?.type === 'string';
841
- } catch (error) {
842
- this.clearProbeProtocol(uuid, 'V1');
843
- if (isUnstartedElectronWakeError(error)) {
844
- if (previousSilentState) {
845
- this.silentDetections.set(uuid, previousSilentState);
846
- } else {
847
- this.silentDetections.delete(uuid);
848
- }
849
- }
850
- this.Log?.debug('[Electron BLE] Protocol V1 Initialize wake failed:', error);
851
- if (shouldRethrowElectronProtocolProbeError(error)) {
852
- throw error;
853
- }
854
- }
855
-
856
- if (answeredV1) {
857
- return true;
858
- }
859
- if (options.abortSignal?.aborted) {
860
- throw ERRORS.TypedError(HardwareErrorCode.DeviceInterruptedFromUser);
861
- }
862
- this.assertRunning();
863
- await this.resetProbeStateAfterProtocolProbe(uuid, 'V1');
864
- this.assertRunning();
865
- return this.probeProtocolV1(uuid);
866
- }
867
-
868
697
  private createNotificationSubscription(uuid: string) {
869
698
  if (!window.desktopApi?.nobleBle) {
870
699
  throw new Error('Noble BLE API not available');
@@ -913,28 +742,15 @@ export default class ElectronBleTransport {
913
742
  try {
914
743
  this.deviceProtocol.set(uuid, 'V1');
915
744
  // GetFeatures identifies Protocol V1 without resetting an existing wallet
916
- // session before Core has a chance to restore a hidden wallet. Use a one-shot
917
- // native write so a fresh Windows link does not stall 28s in the 15-attempt
918
- // pairing retry loop when a sleeping Classic silently ignores GetFeatures.
919
- this.lastV1ProbeFailedWithoutTimeout.delete(uuid);
920
- await this.callProtocolV1(
921
- uuid,
922
- 'GetFeatures',
923
- {},
924
- { timeoutMs: PROTOCOL_PROBE_TIMEOUT_MS },
925
- { oneShot: true },
926
- true
927
- );
745
+ // session before Core has a chance to restore a hidden wallet.
746
+ await this.callProtocolV1(uuid, 'GetFeatures', {}, { timeoutMs: PROTOCOL_PROBE_TIMEOUT_MS });
928
747
  return true;
929
748
  } catch (error) {
930
749
  this.clearProbeProtocol(uuid, 'V1');
931
750
  this.Log?.debug('[Electron BLE] Protocol V1 GetFeatures probe failed:', error);
932
- if (shouldRethrowElectronProtocolProbeError(error)) {
751
+ if (isProtocolV2LinkDisabledError(error)) {
933
752
  throw error;
934
753
  }
935
- if (!(error instanceof Error && this.probeResponseTimeoutErrors.has(error))) {
936
- this.lastV1ProbeFailedWithoutTimeout.add(uuid);
937
- }
938
754
  return false;
939
755
  }
940
756
  }
@@ -979,11 +795,10 @@ export default class ElectronBleTransport {
979
795
  }
980
796
  }
981
797
 
982
- private async refreshBlePacketCapacity(uuid: string) {
798
+ private async refreshBlePacketCapacity(uuid: string): Promise<void> {
983
799
  const nobleBle = window.desktopApi?.nobleBle;
984
800
  const device = nobleBle ? await invokeNobleBle(nobleBle.getDevice(uuid)) : undefined;
985
801
  this.updateBlePacketCapacity(uuid, device?.mtu);
986
- return device;
987
802
  }
988
803
 
989
804
  private updateBlePacketCapacity(uuid: string, mtu?: number): void {
@@ -1207,9 +1022,7 @@ export default class ElectronBleTransport {
1207
1022
  uuid: string,
1208
1023
  name: string,
1209
1024
  data: Record<string, unknown>,
1210
- options?: TransportCallOptions,
1211
- writeOptions?: NobleBleWriteOptions,
1212
- isProtocolProbe = false
1025
+ options?: TransportCallOptions
1213
1026
  ) {
1214
1027
  if (!this._messages) {
1215
1028
  throw ERRORS.TypedError(HardwareErrorCode.TransportNotConfigured);
@@ -1227,7 +1040,6 @@ export default class ElectronBleTransport {
1227
1040
  const messages = this._messages;
1228
1041
  const buffers = ProtocolV1.encodeTransportPackets(messages, name, data);
1229
1042
  let timeout: ReturnType<typeof setTimeout> | undefined;
1230
- let responseTimedOut = false;
1231
1043
 
1232
1044
  try {
1233
1045
  if (!window.desktopApi?.nobleBle) {
@@ -1243,11 +1055,7 @@ export default class ElectronBleTransport {
1243
1055
  if (hexString.length === 0) {
1244
1056
  throw new Error(`Buffer ${i + 1} is empty`);
1245
1057
  }
1246
- await invokeNobleBle(
1247
- writeOptions
1248
- ? window.desktopApi.nobleBle.write(uuid, hexString, writeOptions)
1249
- : window.desktopApi.nobleBle.write(uuid, hexString)
1250
- );
1058
+ await invokeNobleBle(window.desktopApi.nobleBle.write(uuid, hexString));
1251
1059
  }
1252
1060
 
1253
1061
  const response = await Promise.race([
@@ -1255,7 +1063,6 @@ export default class ElectronBleTransport {
1255
1063
  new Promise<never>((_, reject) => {
1256
1064
  if (options?.timeoutMs) {
1257
1065
  timeout = setTimeout(() => {
1258
- responseTimedOut = true;
1259
1066
  const error = ERRORS.TypedError(
1260
1067
  HardwareErrorCode.BleTimeoutError,
1261
1068
  `BLE response timeout after ${options.timeoutMs}ms for ${name}`
@@ -1274,21 +1081,19 @@ export default class ElectronBleTransport {
1274
1081
  return check.call(jsonData);
1275
1082
  } catch (e) {
1276
1083
  this.Log?.error('[Electron BLE] Protocol V1 call error:', e);
1084
+ const isProbeTimeout =
1085
+ name === 'GetFeatures' && options?.timeoutMs === PROTOCOL_PROBE_TIMEOUT_MS;
1277
1086
  if ((e as { errorCode?: unknown })?.errorCode === HardwareErrorCode.BleTimeoutError) {
1278
1087
  this.v1Buffers.set(uuid, { buffer: [], bufferLength: 0 });
1279
1088
  const notifyCleanup = this.notificationCleanups.get(uuid);
1280
1089
  notifyCleanup?.();
1281
1090
  this.notificationCleanups.delete(uuid);
1282
1091
  this.notificationTokens.delete(uuid);
1283
- if (!isProtocolProbe) {
1092
+ if (!isProbeTimeout) {
1284
1093
  await this.releaseNative(uuid, { forceNative: true });
1285
1094
  }
1286
1095
  }
1287
- const normalized = this.normalizeBluetoothError(e);
1288
- if (isProtocolProbe && responseTimedOut && normalized instanceof Error) {
1289
- this.probeResponseTimeoutErrors.add(normalized);
1290
- }
1291
- throw normalized;
1096
+ throw this.normalizeBluetoothError(e);
1292
1097
  } finally {
1293
1098
  if (timeout) clearTimeout(timeout);
1294
1099
  if (this.runPromise === runPromise) {