@onekeyfe/hd-transport-react-native 1.2.8-alpha.2 → 1.2.8-alpha.4

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/src/index.ts CHANGED
@@ -47,7 +47,25 @@ import {
47
47
  getInfosForServiceUuid,
48
48
  isSameBleUuid,
49
49
  } from './constants';
50
+ import {
51
+ isBleKeyMissingSupported,
52
+ startBleKeyMissingTracking,
53
+ stopBleKeyMissingTracking,
54
+ waitForBleKeyMissing,
55
+ } from './bleKeyMissing';
56
+ import {
57
+ markBleLinkEncrypted,
58
+ startBleEncryptionTracking,
59
+ stopBleEncryptionTracking,
60
+ waitForAndroidLinkEncryption,
61
+ } from './bleEncryption';
62
+ import { IosPeerTerminationTracker } from './bleIosStaleBond';
50
63
  import { isNativeBleDisconnectError, toBleDisconnectHardwareError } from './bleNativeDisconnect';
64
+ import {
65
+ isBleStaleBondHardwareError,
66
+ isNativeBleStaleBondError,
67
+ toBleStaleBondHardwareError,
68
+ } from './bleStaleBond';
51
69
  import { isHeaderChunk } from './utils/validateNotify';
52
70
  import BleTransport from './BleTransport';
53
71
  import timer from './utils/timer';
@@ -57,6 +75,7 @@ import type { Deferred } from '@onekeyfe/hd-shared';
57
75
  import type { Characteristic, Device, Subscription } from 'react-native-ble-plx';
58
76
  import type EventEmitter from 'events';
59
77
  import type { BleAcquireInput, TransportOptions } from './types';
78
+ import type { AndroidLinkEncryption } from './bleEncryption';
60
79
 
61
80
  type FirmwareInstallBleAcquireInput = BleAcquireInput & {
62
81
  /**
@@ -170,9 +189,10 @@ const shouldRethrowProtocolProbeError = (error: unknown): boolean => {
170
189
  const code = (error as { errorCode?: unknown })?.errorCode;
171
190
  // Bonding and GATT failures are not evidence of a protocol mismatch. Preserve
172
191
  // them instead of probing another protocol on an unusable connection.
173
- // Native PLX disconnects (errorCode 201 / iOS 7, or the unstructured
174
- // "was disconnected" fallback) must match before Protocol V2 probing.
192
+ // Native PLX disconnects (errorCode 201 / iOS 7) must match before they are
193
+ // mapped: Protocol V2 writes rethrow them unchanged unless normalized first.
175
194
  return (
195
+ isBleStaleBondHardwareError(error) ||
176
196
  isNativeBleDisconnectError(error) ||
177
197
  code === HardwareErrorCode.BleDeviceNotBonded ||
178
198
  code === HardwareErrorCode.BleDeviceBondedCanceled ||
@@ -182,6 +202,38 @@ const shouldRethrowProtocolProbeError = (error: unknown): boolean => {
182
202
  code === HardwareErrorCode.BleWriteCharacteristicError
183
203
  );
184
204
  };
205
+ /**
206
+ * Android reports a lost bond (ACTION_KEY_MISSING) while it encrypts a new link, so only
207
+ * a failure this soon after the link started can be explained by it. Later disconnects,
208
+ * such as a firmware-update reboot, must keep their own meaning.
209
+ */
210
+ export const ANDROID_KEY_MISSING_LINK_WINDOW_MS = 10_000;
211
+ /** The broadcast and the GATT disconnect it explains travel separately; either can land first. */
212
+ export const ANDROID_KEY_MISSING_GRACE_MS = 500;
213
+ /**
214
+ * Android reports a bonded link's first encryption result within about half a second of
215
+ * connecting. Past this, the result is treated as unknown and the link is used as before.
216
+ */
217
+ export const ANDROID_ENCRYPTION_RESULT_TIMEOUT_MS = 1500;
218
+ /**
219
+ * A system re-pairing needs the user to accept a pairing request and confirm the code on the
220
+ * device. The Bluetooth stack gives up after 30s and then reports key missing.
221
+ */
222
+ export const ANDROID_SYSTEM_REPAIR_TIMEOUT_MS = 35_000;
223
+ /**
224
+ * How a link dropped by a device that refuses a stale bond reaches JS. A wedged write is
225
+ * excluded: the system is still re-pairing then and has not reported key missing yet.
226
+ */
227
+ const isAndroidLinkLossError = (error: unknown): boolean => {
228
+ const code = (error as { errorCode?: unknown })?.errorCode;
229
+ return (
230
+ isNativeBleDisconnectError(error) ||
231
+ code === HardwareErrorCode.BleDeviceNotBonded ||
232
+ code === HardwareErrorCode.BleDeviceDisconnected ||
233
+ code === HardwareErrorCode.BleCharacteristicNotifyError ||
234
+ code === HardwareErrorCode.BleConnectedError
235
+ );
236
+ };
185
237
  /** Consecutive wedged writes on one device before the BLE manager itself is recreated. */
186
238
  export const BLE_WRITE_TIMEOUT_MANAGER_RESET_THRESHOLD = 2;
187
239
  const DEVICE_SCAN_TIMEOUT_MS = 3000;
@@ -442,11 +494,23 @@ const resolveNegotiatedMtu = (
442
494
  type IOBleErrorRemap = Error | BleError | null | undefined;
443
495
 
444
496
  function remapError(error: IOBleErrorRemap) {
445
- if (isNativeBleDisconnectError(error)) {
446
- throw toBleDisconnectHardwareError(error);
497
+ if (error instanceof BleError) {
498
+ if (isNativeBleStaleBondError(error)) {
499
+ throw toBleStaleBondHardwareError(error);
500
+ }
501
+
502
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
503
+ // @ts-ignore It's not documented but seems to match a refusal on Android pairing
504
+ if (error?.attErrorCode === 22) {
505
+ throw ERRORS.TypedError(HardwareErrorCode.BleDeviceBondError);
506
+ }
447
507
  }
448
508
 
449
- if (error instanceof Error && error.message?.includes('not found')) {
509
+ if (
510
+ error instanceof Error &&
511
+ error.message &&
512
+ (error.message.includes('was disconnected') || error.message.includes('not found'))
513
+ ) {
450
514
  throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
451
515
  }
452
516
 
@@ -515,6 +579,22 @@ export default class ReactNativeBleTransport {
515
579
  /** Android endpoints whose cached GATT table is suspect; the next connect refreshes it. */
516
580
  private androidGattCacheRefreshes = new Set<string>();
517
581
 
582
+ /**
583
+ * Native encryption/pairing failures seen before Protocol V2 probe starts.
584
+ * Pro2/Neo GATT connect can succeed on a stale iOS bond; the CCCD write then
585
+ * fails with ATT 5/15. Remember it so detectProtocol fails immediately.
586
+ */
587
+ private staleBondErrors: Map<string, Error> = new Map();
588
+
589
+ /** When the current Android link attempt began; bounds which key-missing signals apply. */
590
+ private androidLinkStartedAt: Map<string, number> = new Map();
591
+
592
+ /** iOS acquire attempts whose new link the peer ended; two in a row mean a stale bond. */
593
+ private iosPeerTermination = new IosPeerTerminationTracker();
594
+
595
+ /** Strict or previously confirmed V2 target while acquire installs notifications. */
596
+ private acquiringProtocolV2 = new Set<string>();
597
+
518
598
  private protocolV2Assemblers: Map<string, ProtocolV2FrameAssembler> = new Map();
519
599
 
520
600
  private protocolV2FrameQueues: Map<string, Uint8Array[]> = new Map();
@@ -576,6 +656,11 @@ export default class ReactNativeBleTransport {
576
656
  init(logger: any, emitter: EventEmitter) {
577
657
  setBleLogger(logger);
578
658
  this.emitter = emitter;
659
+ if (Platform.OS === 'android') {
660
+ // Link security events are only meaningful if they were observed since the link came up.
661
+ startBleKeyMissingTracking();
662
+ startBleEncryptionTracking();
663
+ }
579
664
  }
580
665
 
581
666
  configure(signedData: any) {
@@ -823,6 +908,7 @@ export default class ReactNativeBleTransport {
823
908
  const scanStartedAt = Date.now();
824
909
  let firstDeviceMs: number | undefined;
825
910
  const blePlxManager = await this.getPlxManager();
911
+ await subscribeBleOn(blePlxManager);
826
912
  if (Platform.OS === 'android' && Platform.Version >= 31) {
827
913
  Log?.debug('requesting permissions, please wait...');
828
914
 
@@ -839,7 +925,6 @@ export default class ReactNativeBleTransport {
839
925
  throw ERRORS.TypedError(HardwareErrorCode.BlePermissionError);
840
926
  }
841
927
  }
842
- await subscribeBleOn(blePlxManager);
843
928
 
844
929
  if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
845
930
  return new Promise<IOneKeyDevice[]>((resolve, reject) => {
@@ -882,12 +967,14 @@ export default class ReactNativeBleTransport {
882
967
  (error, device) => {
883
968
  if (error) {
884
969
  Log?.debug('ble scan error: ', error);
885
- if (error.errorCode === BleErrorCode.BluetoothPoweredOff) {
886
- finishScan(ERRORS.TypedError(HardwareErrorCode.BlePoweredOff));
887
- } else if (error.errorCode === BleErrorCode.BluetoothUnsupported) {
888
- finishScan(ERRORS.TypedError(HardwareErrorCode.BleUnsupported));
889
- } else if (error.errorCode === BleErrorCode.BluetoothUnauthorized) {
970
+ if (
971
+ [BleErrorCode.BluetoothPoweredOff, BleErrorCode.BluetoothInUnknownState].includes(
972
+ error.errorCode
973
+ )
974
+ ) {
890
975
  finishScan(ERRORS.TypedError(HardwareErrorCode.BlePermissionError));
976
+ } else if (error.errorCode === BleErrorCode.BluetoothUnauthorized) {
977
+ finishScan(ERRORS.TypedError(HardwareErrorCode.BleLocationError));
891
978
  } else if (error.errorCode === BleErrorCode.LocationServicesDisabled) {
892
979
  finishScan(ERRORS.TypedError(HardwareErrorCode.BleLocationServicesDisabled));
893
980
  } else if (error.errorCode === BleErrorCode.ScanStartFailed) {
@@ -1025,12 +1112,23 @@ export default class ReactNativeBleTransport {
1025
1112
  throw ERRORS.TypedError(HardwareErrorCode.BleRequiredUUID);
1026
1113
  }
1027
1114
 
1028
- return this.runLifecycleOperation(uuid, () => this.acquireUnlocked(input));
1115
+ return this.runLifecycleOperation(uuid, async () => {
1116
+ try {
1117
+ return await this.acquireUnlocked(input);
1118
+ } catch (error) {
1119
+ throw this.resolveIosBondInvalid(input, await this.resolveAndroidBondInvalid(uuid, error));
1120
+ }
1121
+ });
1029
1122
  }
1030
1123
 
1031
1124
  private async acquireUnlocked(input: FirmwareInstallBleAcquireInput) {
1032
1125
  if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1033
1126
  const { uuid, forceCleanRunPromise, expectedProtocol, skipProtocolProbe } = input;
1127
+ this.iosPeerTermination.attemptStarted(uuid);
1128
+ const shouldMapProtocolV2StaleBond = expectedProtocol
1129
+ ? expectedProtocol === 'V2'
1130
+ : this.confirmedProtocolV2.has(uuid);
1131
+
1034
1132
  const cachedTransport = transportCache[uuid];
1035
1133
  if (skipProtocolProbe && !cachedTransport && this.blePlxManager) {
1036
1134
  Log?.debug(
@@ -1101,6 +1199,8 @@ export default class ReactNativeBleTransport {
1101
1199
 
1102
1200
  let device: Device | null = null;
1103
1201
  const isAndroid = Platform.OS === 'android';
1202
+ // Only a bond that existed before this acquire can have been lost by the device.
1203
+ let androidBondedBeforeConnect = false;
1104
1204
  // A firmware-install reconnect always refreshes: the new firmware may expose a different table.
1105
1205
  const refreshAndroidGattCache =
1106
1206
  isAndroid && (!!skipProtocolProbe || this.androidGattCacheRefreshes.has(uuid));
@@ -1132,11 +1232,19 @@ export default class ReactNativeBleTransport {
1132
1232
 
1133
1233
  if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1134
1234
  if (Platform.OS === 'android') {
1235
+ // Subscribe before the link exists: key missing is broadcast while Android encrypts it.
1236
+ startBleKeyMissingTracking();
1237
+ startBleEncryptionTracking();
1238
+ // Failures before the new link starts must not be read against the previous link.
1239
+ this.androidLinkStartedAt.delete(uuid);
1135
1240
  // Initiate bonding locally before GATT can trigger peripheral-initiated pairing.
1136
1241
  try {
1137
1242
  const bondState = await pairDevice(uuid);
1243
+ androidBondedBeforeConnect = !bondState.bonding && bondState.bonded;
1138
1244
  if (bondState.bonding) {
1139
- await onDeviceBondState(uuid, this.bondAbortController.signal);
1245
+ await onDeviceBondState(uuid, this.bondAbortController.signal, {
1246
+ systemInitiated: bondState.initiated === false,
1247
+ });
1140
1248
  } else if (!bondState.bonded) {
1141
1249
  throw ERRORS.TypedError(HardwareErrorCode.BleDeviceNotBonded, 'device is not bonded');
1142
1250
  }
@@ -1148,6 +1256,7 @@ export default class ReactNativeBleTransport {
1148
1256
  });
1149
1257
  throw error;
1150
1258
  }
1259
+ this.androidLinkStartedAt.set(uuid, Date.now());
1151
1260
  }
1152
1261
  if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1153
1262
 
@@ -1331,7 +1440,17 @@ export default class ReactNativeBleTransport {
1331
1440
  this.deviceProtocolHints.set(uuid, protocolHint);
1332
1441
  }
1333
1442
 
1443
+ if (shouldMapProtocolV2StaleBond) {
1444
+ this.acquiringProtocolV2.add(uuid);
1445
+ }
1446
+
1447
+ let linkEncryption: AndroidLinkEncryption | undefined;
1334
1448
  try {
1449
+ // A firmware-install reconnect keeps its existing sequence.
1450
+ if (androidBondedBeforeConnect && !skipProtocolProbe) {
1451
+ linkEncryption = await this.waitForAndroidLinkSecurity(uuid);
1452
+ if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1453
+ }
1335
1454
  await this.installTransportForAcquire(uuid, acquiredDevice, {
1336
1455
  writeCharacteristic,
1337
1456
  notifyCharacteristic,
@@ -1378,17 +1497,25 @@ export default class ReactNativeBleTransport {
1378
1497
  }
1379
1498
  );
1380
1499
  if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1500
+ this.iosPeerTermination.linkProven(uuid);
1381
1501
  const currentTransport = transportCache[uuid];
1382
1502
  if (!currentTransport) {
1383
1503
  throw ERRORS.TypedError(HardwareErrorCode.TransportNotFound);
1384
1504
  }
1385
1505
  this.attachDisconnectSubscription(currentTransport, currentTransport.device, uuid);
1506
+ if (linkEncryption === 'unresolved') {
1507
+ // Notifications and the probe only work on an encrypted link, so the next reuse of this
1508
+ // link needs no result that was reported before tracking started.
1509
+ markBleLinkEncrypted(uuid);
1510
+ }
1386
1511
  return { uuid, protocolType };
1387
1512
  } catch (error) {
1388
1513
  // A failed acquire must retire the physical link before Core retries. Logical
1389
1514
  // release leaves GATT connected even when neither protocol receives a response.
1390
1515
  await this.disconnectUnlocked(uuid);
1391
1516
  throw error;
1517
+ } finally {
1518
+ this.acquiringProtocolV2.delete(uuid);
1392
1519
  }
1393
1520
  }
1394
1521
 
@@ -1403,6 +1530,7 @@ export default class ReactNativeBleTransport {
1403
1530
  const subscription = characteristic.monitor((error, c) => {
1404
1531
  const isCurrentMonitor = this.monitorTokens.get(uuid) === monitorToken;
1405
1532
  if (error) {
1533
+ if (isCurrentMonitor) this.noteIosLinkError(uuid, 'notify', error);
1406
1534
  Log?.debug(
1407
1535
  `error monitor ${characteristic.uuid}, deviceId: ${characteristic.deviceID}: ${
1408
1536
  error as unknown as string
@@ -1416,6 +1544,13 @@ export default class ReactNativeBleTransport {
1416
1544
  Log?.debug('monitor error ignored for stale transport: ', uuid, notifyTransactionId);
1417
1545
  return;
1418
1546
  }
1547
+ if (
1548
+ (this.getActiveProtocol(uuid) === 'V2' || this.acquiringProtocolV2.has(uuid)) &&
1549
+ isNativeBleStaleBondError(error)
1550
+ ) {
1551
+ this.rememberStaleBondError(uuid, toBleStaleBondHardwareError(error));
1552
+ return;
1553
+ }
1419
1554
  if (Platform.OS === 'android' && isStaleGattTableNotifyReason(error.reason)) {
1420
1555
  this.androidGattCacheRefreshes.add(uuid);
1421
1556
  }
@@ -1575,6 +1710,8 @@ export default class ReactNativeBleTransport {
1575
1710
 
1576
1711
  this.deviceProtocol.delete(uuid);
1577
1712
  this.probingProtocols.delete(uuid);
1713
+ this.staleBondErrors.delete(uuid);
1714
+ this.acquiringProtocolV2.delete(uuid);
1578
1715
  // Confirmed protocol and caller hints stay in deviceProtocol / protocolHint.
1579
1716
  this.protocolV2Assemblers.get(uuid)?.reset();
1580
1717
  this.protocolV2Assemblers.delete(uuid);
@@ -1645,9 +1782,122 @@ export default class ReactNativeBleTransport {
1645
1782
  throw ERRORS.TypedError(HardwareErrorCode.TransportCallInProgress);
1646
1783
  }
1647
1784
 
1648
- return protocol === 'V2'
1649
- ? this.callProtocolV2(uuid, name, data, options)
1650
- : this.callProtocolV1(uuid, name, data, options);
1785
+ try {
1786
+ return protocol === 'V2'
1787
+ ? await this.callProtocolV2(uuid, name, data, options)
1788
+ : await this.callProtocolV1(uuid, name, data, options);
1789
+ } catch (error) {
1790
+ // An expected-V1 acquire skips the probe, so the first call is what meets the dropped link.
1791
+ throw await this.resolveAndroidBondInvalid(uuid, error);
1792
+ }
1793
+ }
1794
+
1795
+ /**
1796
+ * Android 16+ keeps a bond the device no longer holds keys for. The device drops the link
1797
+ * and the only structured evidence is ACTION_KEY_MISSING, so a link loss right after
1798
+ * connect is re-read as an invalid bond when that signal belongs to the same attempt.
1799
+ */
1800
+ private async resolveAndroidBondInvalid(uuid: string, error: unknown): Promise<unknown> {
1801
+ if (Platform.OS !== 'android' || !isBleKeyMissingSupported()) return error;
1802
+ if (isBleStaleBondHardwareError(error) || !isAndroidLinkLossError(error)) return error;
1803
+ const linkStartedAt = this.androidLinkStartedAt.get(uuid);
1804
+ if (
1805
+ linkStartedAt === undefined ||
1806
+ Date.now() - linkStartedAt > ANDROID_KEY_MISSING_LINK_WINDOW_MS
1807
+ ) {
1808
+ return error;
1809
+ }
1810
+ if (!(await waitForBleKeyMissing(uuid, linkStartedAt, ANDROID_KEY_MISSING_GRACE_MS))) {
1811
+ return error;
1812
+ }
1813
+ Log?.debug('[ReactNativeBleTransport] Android key missing, bond is invalid:', uuid);
1814
+ return ERRORS.TypedError(HardwareErrorCode.BleBondInvalid, undefined, {
1815
+ phase: 'connect',
1816
+ reason: 'key_missing',
1817
+ });
1818
+ }
1819
+
1820
+ /**
1821
+ * iOS says why a link ended only on the operation it interrupted, so the native codes are read
1822
+ * and logged here. Codes only: the reason text is localized and cannot be matched or searched.
1823
+ */
1824
+ private noteIosLinkError(uuid: string, stage: 'gatt-setup' | 'notify' | 'write', error: unknown) {
1825
+ if (Platform.OS !== 'ios') return;
1826
+ this.iosPeerTermination.note(uuid, error);
1827
+ // Writes and notifications also fail for reasons that say nothing about the link.
1828
+ if (stage !== 'gatt-setup' && !isNativeBleDisconnectError(error)) return;
1829
+ const native = (error ?? {}) as {
1830
+ errorCode?: unknown;
1831
+ iosErrorCode?: unknown;
1832
+ attErrorCode?: unknown;
1833
+ };
1834
+ const code = (value: unknown) =>
1835
+ typeof value === 'number' || typeof value === 'string' ? value : undefined;
1836
+ Log?.debug('[ReactNativeBleTransport] iOS operation failed', {
1837
+ connectIdSuffix: uuid.slice(-8),
1838
+ stage,
1839
+ errorCode: code(native.errorCode),
1840
+ iosErrorCode: code(native.iosErrorCode),
1841
+ attErrorCode: code(native.attErrorCode),
1842
+ });
1843
+ }
1844
+
1845
+ /**
1846
+ * iPhones that do not report a lost bond only show the device ending each new link. One such
1847
+ * attempt keeps its error so Core retries; the second in a row is the stale bond.
1848
+ */
1849
+ private resolveIosBondInvalid(input: FirmwareInstallBleAcquireInput, error: unknown): unknown {
1850
+ if (Platform.OS !== 'ios') return error;
1851
+ const { uuid, skipProtocolProbe } = input;
1852
+ // A firmware-install reconnect expects the device to come and go.
1853
+ if (skipProtocolProbe || isBleStaleBondHardwareError(error)) {
1854
+ this.iosPeerTermination.forget(uuid);
1855
+ return error;
1856
+ }
1857
+ if (!this.iosPeerTermination.attemptFailed(uuid)) return error;
1858
+ Log?.debug(
1859
+ '[ReactNativeBleTransport] iOS peer ended two new links in a row, bond is invalid:',
1860
+ {
1861
+ connectIdSuffix: uuid.slice(-8),
1862
+ }
1863
+ );
1864
+ return ERRORS.TypedError(HardwareErrorCode.BleBondInvalid, undefined, {
1865
+ phase: 'connect',
1866
+ reason: 'peer_disconnected',
1867
+ });
1868
+ }
1869
+
1870
+ /**
1871
+ * Android 16+ encrypts a bonded link on its own right after connecting. Subscribing to
1872
+ * notifications before that finishes gets the CCCD write rejected, and the framework's retry
1873
+ * encrypts again with the same stale key; firmware that allows one failure per link then drops
1874
+ * it before the system can re-pair. Holding GATT until the result lets a lost bond be re-paired
1875
+ * in place. Without the platform signal this resolves immediately.
1876
+ */
1877
+ private async waitForAndroidLinkSecurity(uuid: string): Promise<AndroidLinkEncryption> {
1878
+ const linkStartedAt = this.androidLinkStartedAt.get(uuid);
1879
+ if (linkStartedAt === undefined) return 'unresolved';
1880
+ const waitStartedAt = Date.now();
1881
+ const result = await waitForAndroidLinkEncryption({
1882
+ deviceId: uuid,
1883
+ linkStartedAt,
1884
+ resultTimeoutMs: ANDROID_ENCRYPTION_RESULT_TIMEOUT_MS,
1885
+ repairTimeoutMs: ANDROID_SYSTEM_REPAIR_TIMEOUT_MS,
1886
+ keyMissingGraceMs: ANDROID_KEY_MISSING_GRACE_MS,
1887
+ signal: this.bondAbortController.signal,
1888
+ onRepairStarted: () => {
1889
+ Log?.debug(
1890
+ '[ReactNativeBleTransport] Android bond lost, waiting for system re-pairing:',
1891
+ uuid
1892
+ );
1893
+ },
1894
+ });
1895
+ Log?.debug('[ReactNativeBleTransport] Android link encryption', {
1896
+ connectIdSuffix: uuid.slice(-8),
1897
+ result,
1898
+ waitedMs: Date.now() - waitStartedAt,
1899
+ });
1900
+ return result;
1651
1901
  }
1652
1902
 
1653
1903
  private async callProtocolV1(
@@ -1915,6 +2165,10 @@ export default class ReactNativeBleTransport {
1915
2165
  this.androidPriorityResetTimers.forEach(timeout => clearTimeout(timeout));
1916
2166
  this.androidPriorityResetTimers.clear();
1917
2167
  this.androidHighPriorityDevices.clear();
2168
+ this.androidLinkStartedAt.clear();
2169
+ this.iosPeerTermination.reset();
2170
+ stopBleKeyMissingTracking();
2171
+ stopBleEncryptionTracking();
1918
2172
  const error = ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1919
2173
  this.runPromise?.reject(error);
1920
2174
  this.runPromise = null;
@@ -1988,6 +2242,7 @@ export default class ReactNativeBleTransport {
1988
2242
  }
1989
2243
  this.deviceProtocol.delete(session);
1990
2244
  this.probingProtocols.delete(session);
2245
+ this.staleBondErrors.delete(session);
1991
2246
  this.deviceProtocolHints.delete(session);
1992
2247
  this.sessionProtocols.delete(session);
1993
2248
  this.protocolReprobeFailures.delete(session);
@@ -2229,6 +2484,7 @@ export default class ReactNativeBleTransport {
2229
2484
  }),
2230
2485
  ]);
2231
2486
  succeeded = true;
2487
+ this.iosPeerTermination.linkStarted(uuid);
2232
2488
  return result;
2233
2489
  } catch (error) {
2234
2490
  if (timedOut || isNativeOperationTimeoutError(error)) {
@@ -2282,6 +2538,11 @@ export default class ReactNativeBleTransport {
2282
2538
  succeeded = true;
2283
2539
  return result;
2284
2540
  } catch (error) {
2541
+ this.noteIosLinkError(uuid, 'gatt-setup', error);
2542
+ if (Platform.OS === 'ios' && isNativeBleStaleBondError(error)) {
2543
+ // iOS can report the lost bond on the first request instead of on the connect.
2544
+ throw toBleStaleBondHardwareError(error);
2545
+ }
2285
2546
  if (timedOut || isNativeOperationTimeoutError(error)) {
2286
2547
  const resetManager = this.abandonStalledConnection(
2287
2548
  uuid,
@@ -2291,9 +2552,6 @@ export default class ReactNativeBleTransport {
2291
2552
  throw this.createWedgedBleSetupError();
2292
2553
  }
2293
2554
  }
2294
- if (isNativeBleDisconnectError(error)) {
2295
- throw toBleDisconnectHardwareError(error);
2296
- }
2297
2555
  if (Platform.OS === 'android' && isMissingGattShapeError(error)) {
2298
2556
  this.androidGattCacheRefreshes.add(uuid);
2299
2557
  }
@@ -2341,6 +2599,8 @@ export default class ReactNativeBleTransport {
2341
2599
  }
2342
2600
  this.deviceProtocol.delete(uuid);
2343
2601
  this.probingProtocols.delete(uuid);
2602
+ this.staleBondErrors.delete(uuid);
2603
+ this.acquiringProtocolV2.delete(uuid);
2344
2604
  this.protocolV2Assemblers.delete(uuid);
2345
2605
  this.resetProtocolV2Frames(uuid);
2346
2606
 
@@ -2400,6 +2660,7 @@ export default class ReactNativeBleTransport {
2400
2660
  ]);
2401
2661
  this.writeTimeoutCounts.delete(uuid);
2402
2662
  } catch (error) {
2663
+ this.noteIosLinkError(uuid, 'write', error);
2403
2664
  if (timedOut) {
2404
2665
  // A superseded call's late write must not tear down the link the current
2405
2666
  // call is using; only the owner of the transport may declare it dead.
@@ -2437,6 +2698,8 @@ export default class ReactNativeBleTransport {
2437
2698
  }
2438
2699
  this.deviceProtocol.delete(uuid);
2439
2700
  this.probingProtocols.delete(uuid);
2701
+ this.staleBondErrors.delete(uuid);
2702
+ this.acquiringProtocolV2.delete(uuid);
2440
2703
  this.protocolV2Assemblers.delete(uuid);
2441
2704
  this.resetProtocolV2Frames(uuid);
2442
2705
 
@@ -2488,6 +2751,8 @@ export default class ReactNativeBleTransport {
2488
2751
  });
2489
2752
  this.deviceProtocol.clear();
2490
2753
  this.probingProtocols.clear();
2754
+ this.staleBondErrors.clear();
2755
+ this.acquiringProtocolV2.clear();
2491
2756
  this.sessionProtocols.clear();
2492
2757
  // Keep transport-lifetime V2 proof so the same endpoint can finish a no-probe
2493
2758
  // firmware reconnect after the native BLE manager is recreated.
@@ -2570,6 +2835,10 @@ export default class ReactNativeBleTransport {
2570
2835
  return 'V1';
2571
2836
  }
2572
2837
 
2838
+ if (expectedProtocol === 'V2' || this.acquiringProtocolV2.has(uuid)) {
2839
+ this.throwIfStaleBondError(uuid);
2840
+ }
2841
+
2573
2842
  if (expectedProtocol === 'V2') {
2574
2843
  if (await this.probeProtocolV2(uuid)) {
2575
2844
  this.deviceProtocol.set(uuid, 'V2');
@@ -2758,6 +3027,7 @@ export default class ReactNativeBleTransport {
2758
3027
 
2759
3028
  this.probingProtocols.set(uuid, 'V2');
2760
3029
  this.protocolV2Assemblers.get(uuid)?.reset();
3030
+ this.throwIfStaleBondError(uuid);
2761
3031
  const detected = await probeProtocolV2Helper({
2762
3032
  call: (name: string, data: Record<string, unknown>, options?: TransportCallOptions) =>
2763
3033
  this.callProtocolV2(uuid, name, data, options),
@@ -2837,6 +3107,21 @@ export default class ReactNativeBleTransport {
2837
3107
  }
2838
3108
  }
2839
3109
 
3110
+ private rememberStaleBondError(uuid: string, error: Error) {
3111
+ this.staleBondErrors.set(uuid, error);
3112
+ this.rejectProtocolV2Frames(uuid, error);
3113
+ if (this.runPromise && this.runPromiseDeviceId === uuid) {
3114
+ this.runPromise.reject(error);
3115
+ }
3116
+ }
3117
+
3118
+ private throwIfStaleBondError(uuid: string) {
3119
+ const error = this.staleBondErrors.get(uuid);
3120
+ if (error) {
3121
+ throw error;
3122
+ }
3123
+ }
3124
+
2840
3125
  private async readProtocolV2Frame(uuid: string) {
2841
3126
  const queuedFrame = this.getProtocolV2FrameQueue(uuid).shift();
2842
3127
  if (queuedFrame) {
@@ -2895,6 +3180,11 @@ export default class ReactNativeBleTransport {
2895
3180
  assertCurrentGeneration();
2896
3181
  return;
2897
3182
  } catch (error) {
3183
+ if (isNativeBleStaleBondError(error) || isBleStaleBondHardwareError(error)) {
3184
+ const bondError = toBleStaleBondHardwareError(error);
3185
+ this.rememberStaleBondError(uuid, bondError);
3186
+ throw bondError;
3187
+ }
2898
3188
  if (isNativeBleDisconnectError(error)) {
2899
3189
  throw toBleDisconnectHardwareError(error);
2900
3190
  }
@@ -4,42 +4,23 @@ import timer from './utils/timer';
4
4
 
5
5
  import type { BlePlxManager } from './types';
6
6
 
7
- export const subscribeBleOn = (bleManager: BlePlxManager, ms = 2000): Promise<void> =>
7
+ export const subscribeBleOn = (bleManager: BlePlxManager, ms = 1000): Promise<void> =>
8
8
  new Promise((resolve, reject) => {
9
9
  let done = false;
10
- let pendingError: Error | undefined;
11
- let cancelTimeout: () => void = () => undefined;
12
- let removeSubscription: () => void = () => undefined;
13
-
14
- const finish = (error?: Error) => {
15
- if (done) return;
16
- done = true;
17
- cancelTimeout();
18
- removeSubscription();
19
- if (error) reject(error);
20
- else resolve();
21
- };
22
10
 
23
11
  const subscription = bleManager.onStateChange(state => {
24
12
  if (state === 'PoweredOn') {
25
- finish();
26
- } else if (state === 'PoweredOff') {
27
- pendingError = ERRORS.TypedError(HardwareErrorCode.BlePoweredOff);
28
- } else if (state === 'Unsupported') {
29
- pendingError = ERRORS.TypedError(HardwareErrorCode.BleUnsupported);
30
- } else if (state === 'Unauthorized') {
31
- pendingError = ERRORS.TypedError(HardwareErrorCode.BlePermissionError);
32
- } else {
33
- pendingError = undefined;
13
+ if (done) return;
14
+ clearTimeout();
15
+ done = true;
16
+ subscription.remove();
17
+ resolve();
34
18
  }
35
19
  }, true);
36
- removeSubscription = () => subscription.remove();
37
20
 
38
- if (done) {
39
- removeSubscription();
40
- } else {
41
- cancelTimeout = timer.timeout(() => {
42
- finish(pendingError ?? ERRORS.TypedError(HardwareErrorCode.BleScanError));
43
- }, ms);
44
- }
21
+ const clearTimeout = timer.timeout(() => {
22
+ if (done) return;
23
+ subscription.remove();
24
+ reject(ERRORS.TypedError(HardwareErrorCode.BlePermissionError));
25
+ }, ms);
45
26
  });