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

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