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

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
 
@@ -836,10 +922,9 @@ export default class ReactNativeBleTransport {
836
922
  resultConnect[PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT] !== 'granted' ||
837
923
  resultConnect[PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN] !== 'granted'
838
924
  ) {
839
- throw ERRORS.TypedError(HardwareErrorCode.BleLocationError);
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,10 +967,12 @@ 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));
970
+ if (
971
+ [BleErrorCode.BluetoothPoweredOff, BleErrorCode.BluetoothInUnknownState].includes(
972
+ error.errorCode
973
+ )
974
+ ) {
975
+ finishScan(ERRORS.TypedError(HardwareErrorCode.BlePermissionError));
889
976
  } else if (error.errorCode === BleErrorCode.BluetoothUnauthorized) {
890
977
  finishScan(ERRORS.TypedError(HardwareErrorCode.BleLocationError));
891
978
  } else if (error.errorCode === BleErrorCode.LocationServicesDisabled) {
@@ -1010,7 +1097,6 @@ export default class ReactNativeBleTransport {
1010
1097
  if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1011
1098
 
1012
1099
  Log?.debug('[ReactNativeBleTransport] BLE MTU ready', {
1013
- connectionId: monitorToken,
1014
1100
  platform: Platform.OS,
1015
1101
  requested: getRequestedBleMtu(),
1016
1102
  actual: transport.mtuSize,
@@ -1026,12 +1112,23 @@ export default class ReactNativeBleTransport {
1026
1112
  throw ERRORS.TypedError(HardwareErrorCode.BleRequiredUUID);
1027
1113
  }
1028
1114
 
1029
- 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
+ });
1030
1122
  }
1031
1123
 
1032
1124
  private async acquireUnlocked(input: FirmwareInstallBleAcquireInput) {
1033
1125
  if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1034
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
+
1035
1132
  const cachedTransport = transportCache[uuid];
1036
1133
  if (skipProtocolProbe && !cachedTransport && this.blePlxManager) {
1037
1134
  Log?.debug(
@@ -1102,6 +1199,8 @@ export default class ReactNativeBleTransport {
1102
1199
 
1103
1200
  let device: Device | null = null;
1104
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;
1105
1204
  // A firmware-install reconnect always refreshes: the new firmware may expose a different table.
1106
1205
  const refreshAndroidGattCache =
1107
1206
  isAndroid && (!!skipProtocolProbe || this.androidGattCacheRefreshes.has(uuid));
@@ -1133,9 +1232,15 @@ export default class ReactNativeBleTransport {
1133
1232
 
1134
1233
  if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1135
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);
1136
1240
  // Initiate bonding locally before GATT can trigger peripheral-initiated pairing.
1137
1241
  try {
1138
1242
  const bondState = await pairDevice(uuid);
1243
+ androidBondedBeforeConnect = !bondState.bonding && bondState.bonded;
1139
1244
  if (bondState.bonding) {
1140
1245
  await onDeviceBondState(uuid, this.bondAbortController.signal, {
1141
1246
  systemInitiated: bondState.initiated === false,
@@ -1151,6 +1256,7 @@ export default class ReactNativeBleTransport {
1151
1256
  });
1152
1257
  throw error;
1153
1258
  }
1259
+ this.androidLinkStartedAt.set(uuid, Date.now());
1154
1260
  }
1155
1261
  if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1156
1262
 
@@ -1334,7 +1440,17 @@ export default class ReactNativeBleTransport {
1334
1440
  this.deviceProtocolHints.set(uuid, protocolHint);
1335
1441
  }
1336
1442
 
1443
+ if (shouldMapProtocolV2StaleBond) {
1444
+ this.acquiringProtocolV2.add(uuid);
1445
+ }
1446
+
1447
+ let linkEncryption: AndroidLinkEncryption | undefined;
1337
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
+ }
1338
1454
  await this.installTransportForAcquire(uuid, acquiredDevice, {
1339
1455
  writeCharacteristic,
1340
1456
  notifyCharacteristic,
@@ -1381,17 +1497,25 @@ export default class ReactNativeBleTransport {
1381
1497
  }
1382
1498
  );
1383
1499
  if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1500
+ this.iosPeerTermination.linkProven(uuid);
1384
1501
  const currentTransport = transportCache[uuid];
1385
1502
  if (!currentTransport) {
1386
1503
  throw ERRORS.TypedError(HardwareErrorCode.TransportNotFound);
1387
1504
  }
1388
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
+ }
1389
1511
  return { uuid, protocolType };
1390
1512
  } catch (error) {
1391
1513
  // A failed acquire must retire the physical link before Core retries. Logical
1392
1514
  // release leaves GATT connected even when neither protocol receives a response.
1393
1515
  await this.disconnectUnlocked(uuid);
1394
1516
  throw error;
1517
+ } finally {
1518
+ this.acquiringProtocolV2.delete(uuid);
1395
1519
  }
1396
1520
  }
1397
1521
 
@@ -1406,6 +1530,7 @@ export default class ReactNativeBleTransport {
1406
1530
  const subscription = characteristic.monitor((error, c) => {
1407
1531
  const isCurrentMonitor = this.monitorTokens.get(uuid) === monitorToken;
1408
1532
  if (error) {
1533
+ if (isCurrentMonitor) this.noteIosLinkError(uuid, 'notify', error);
1409
1534
  Log?.debug(
1410
1535
  `error monitor ${characteristic.uuid}, deviceId: ${characteristic.deviceID}: ${
1411
1536
  error as unknown as string
@@ -1419,6 +1544,13 @@ export default class ReactNativeBleTransport {
1419
1544
  Log?.debug('monitor error ignored for stale transport: ', uuid, notifyTransactionId);
1420
1545
  return;
1421
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
+ }
1422
1554
  if (Platform.OS === 'android' && isStaleGattTableNotifyReason(error.reason)) {
1423
1555
  this.androidGattCacheRefreshes.add(uuid);
1424
1556
  }
@@ -1578,6 +1710,8 @@ export default class ReactNativeBleTransport {
1578
1710
 
1579
1711
  this.deviceProtocol.delete(uuid);
1580
1712
  this.probingProtocols.delete(uuid);
1713
+ this.staleBondErrors.delete(uuid);
1714
+ this.acquiringProtocolV2.delete(uuid);
1581
1715
  // Confirmed protocol and caller hints stay in deviceProtocol / protocolHint.
1582
1716
  this.protocolV2Assemblers.get(uuid)?.reset();
1583
1717
  this.protocolV2Assemblers.delete(uuid);
@@ -1648,9 +1782,122 @@ export default class ReactNativeBleTransport {
1648
1782
  throw ERRORS.TypedError(HardwareErrorCode.TransportCallInProgress);
1649
1783
  }
1650
1784
 
1651
- return protocol === 'V2'
1652
- ? this.callProtocolV2(uuid, name, data, options)
1653
- : 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;
1654
1901
  }
1655
1902
 
1656
1903
  private async callProtocolV1(
@@ -1918,6 +2165,10 @@ export default class ReactNativeBleTransport {
1918
2165
  this.androidPriorityResetTimers.forEach(timeout => clearTimeout(timeout));
1919
2166
  this.androidPriorityResetTimers.clear();
1920
2167
  this.androidHighPriorityDevices.clear();
2168
+ this.androidLinkStartedAt.clear();
2169
+ this.iosPeerTermination.reset();
2170
+ stopBleKeyMissingTracking();
2171
+ stopBleEncryptionTracking();
1921
2172
  const error = ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1922
2173
  this.runPromise?.reject(error);
1923
2174
  this.runPromise = null;
@@ -1991,6 +2242,7 @@ export default class ReactNativeBleTransport {
1991
2242
  }
1992
2243
  this.deviceProtocol.delete(session);
1993
2244
  this.probingProtocols.delete(session);
2245
+ this.staleBondErrors.delete(session);
1994
2246
  this.deviceProtocolHints.delete(session);
1995
2247
  this.sessionProtocols.delete(session);
1996
2248
  this.protocolReprobeFailures.delete(session);
@@ -2232,6 +2484,7 @@ export default class ReactNativeBleTransport {
2232
2484
  }),
2233
2485
  ]);
2234
2486
  succeeded = true;
2487
+ this.iosPeerTermination.linkStarted(uuid);
2235
2488
  return result;
2236
2489
  } catch (error) {
2237
2490
  if (timedOut || isNativeOperationTimeoutError(error)) {
@@ -2285,6 +2538,11 @@ export default class ReactNativeBleTransport {
2285
2538
  succeeded = true;
2286
2539
  return result;
2287
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
+ }
2288
2546
  if (timedOut || isNativeOperationTimeoutError(error)) {
2289
2547
  const resetManager = this.abandonStalledConnection(
2290
2548
  uuid,
@@ -2294,9 +2552,6 @@ export default class ReactNativeBleTransport {
2294
2552
  throw this.createWedgedBleSetupError();
2295
2553
  }
2296
2554
  }
2297
- if (isNativeBleDisconnectError(error)) {
2298
- throw toBleDisconnectHardwareError(error);
2299
- }
2300
2555
  if (Platform.OS === 'android' && isMissingGattShapeError(error)) {
2301
2556
  this.androidGattCacheRefreshes.add(uuid);
2302
2557
  }
@@ -2344,6 +2599,8 @@ export default class ReactNativeBleTransport {
2344
2599
  }
2345
2600
  this.deviceProtocol.delete(uuid);
2346
2601
  this.probingProtocols.delete(uuid);
2602
+ this.staleBondErrors.delete(uuid);
2603
+ this.acquiringProtocolV2.delete(uuid);
2347
2604
  this.protocolV2Assemblers.delete(uuid);
2348
2605
  this.resetProtocolV2Frames(uuid);
2349
2606
 
@@ -2403,6 +2660,7 @@ export default class ReactNativeBleTransport {
2403
2660
  ]);
2404
2661
  this.writeTimeoutCounts.delete(uuid);
2405
2662
  } catch (error) {
2663
+ this.noteIosLinkError(uuid, 'write', error);
2406
2664
  if (timedOut) {
2407
2665
  // A superseded call's late write must not tear down the link the current
2408
2666
  // call is using; only the owner of the transport may declare it dead.
@@ -2440,6 +2698,8 @@ export default class ReactNativeBleTransport {
2440
2698
  }
2441
2699
  this.deviceProtocol.delete(uuid);
2442
2700
  this.probingProtocols.delete(uuid);
2701
+ this.staleBondErrors.delete(uuid);
2702
+ this.acquiringProtocolV2.delete(uuid);
2443
2703
  this.protocolV2Assemblers.delete(uuid);
2444
2704
  this.resetProtocolV2Frames(uuid);
2445
2705
 
@@ -2491,6 +2751,8 @@ export default class ReactNativeBleTransport {
2491
2751
  });
2492
2752
  this.deviceProtocol.clear();
2493
2753
  this.probingProtocols.clear();
2754
+ this.staleBondErrors.clear();
2755
+ this.acquiringProtocolV2.clear();
2494
2756
  this.sessionProtocols.clear();
2495
2757
  // Keep transport-lifetime V2 proof so the same endpoint can finish a no-probe
2496
2758
  // firmware reconnect after the native BLE manager is recreated.
@@ -2573,6 +2835,10 @@ export default class ReactNativeBleTransport {
2573
2835
  return 'V1';
2574
2836
  }
2575
2837
 
2838
+ if (expectedProtocol === 'V2' || this.acquiringProtocolV2.has(uuid)) {
2839
+ this.throwIfStaleBondError(uuid);
2840
+ }
2841
+
2576
2842
  if (expectedProtocol === 'V2') {
2577
2843
  if (await this.probeProtocolV2(uuid)) {
2578
2844
  this.deviceProtocol.set(uuid, 'V2');
@@ -2761,6 +3027,7 @@ export default class ReactNativeBleTransport {
2761
3027
 
2762
3028
  this.probingProtocols.set(uuid, 'V2');
2763
3029
  this.protocolV2Assemblers.get(uuid)?.reset();
3030
+ this.throwIfStaleBondError(uuid);
2764
3031
  const detected = await probeProtocolV2Helper({
2765
3032
  call: (name: string, data: Record<string, unknown>, options?: TransportCallOptions) =>
2766
3033
  this.callProtocolV2(uuid, name, data, options),
@@ -2840,6 +3107,21 @@ export default class ReactNativeBleTransport {
2840
3107
  }
2841
3108
  }
2842
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
+
2843
3125
  private async readProtocolV2Frame(uuid: string) {
2844
3126
  const queuedFrame = this.getProtocolV2FrameQueue(uuid).shift();
2845
3127
  if (queuedFrame) {
@@ -2898,6 +3180,11 @@ export default class ReactNativeBleTransport {
2898
3180
  assertCurrentGeneration();
2899
3181
  return;
2900
3182
  } catch (error) {
3183
+ if (isNativeBleStaleBondError(error) || isBleStaleBondHardwareError(error)) {
3184
+ const bondError = toBleStaleBondHardwareError(error);
3185
+ this.rememberStaleBondError(uuid, bondError);
3186
+ throw bondError;
3187
+ }
2901
3188
  if (isNativeBleDisconnectError(error)) {
2902
3189
  throw toBleDisconnectHardwareError(error);
2903
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.BleLocationError);
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
  });