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

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,25 +47,7 @@ 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';
63
50
  import { isNativeBleDisconnectError, toBleDisconnectHardwareError } from './bleNativeDisconnect';
64
- import {
65
- isBleStaleBondHardwareError,
66
- isNativeBleStaleBondError,
67
- toBleStaleBondHardwareError,
68
- } from './bleStaleBond';
69
51
  import { isHeaderChunk } from './utils/validateNotify';
70
52
  import BleTransport from './BleTransport';
71
53
  import timer from './utils/timer';
@@ -75,7 +57,6 @@ import type { Deferred } from '@onekeyfe/hd-shared';
75
57
  import type { Characteristic, Device, Subscription } from 'react-native-ble-plx';
76
58
  import type EventEmitter from 'events';
77
59
  import type { BleAcquireInput, TransportOptions } from './types';
78
- import type { AndroidLinkEncryption } from './bleEncryption';
79
60
 
80
61
  type FirmwareInstallBleAcquireInput = BleAcquireInput & {
81
62
  /**
@@ -189,10 +170,9 @@ const shouldRethrowProtocolProbeError = (error: unknown): boolean => {
189
170
  const code = (error as { errorCode?: unknown })?.errorCode;
190
171
  // Bonding and GATT failures are not evidence of a protocol mismatch. Preserve
191
172
  // them instead of probing another protocol on an unusable connection.
192
- // Native PLX disconnects (errorCode 201 / iOS 7) must match before they are
193
- // mapped: Protocol V2 writes rethrow them unchanged unless normalized first.
173
+ // Native PLX disconnects (errorCode 201 / iOS 7, or the unstructured
174
+ // "was disconnected" fallback) must match before Protocol V2 probing.
194
175
  return (
195
- isBleStaleBondHardwareError(error) ||
196
176
  isNativeBleDisconnectError(error) ||
197
177
  code === HardwareErrorCode.BleDeviceNotBonded ||
198
178
  code === HardwareErrorCode.BleDeviceBondedCanceled ||
@@ -202,38 +182,6 @@ const shouldRethrowProtocolProbeError = (error: unknown): boolean => {
202
182
  code === HardwareErrorCode.BleWriteCharacteristicError
203
183
  );
204
184
  };
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
- };
237
185
  /** Consecutive wedged writes on one device before the BLE manager itself is recreated. */
238
186
  export const BLE_WRITE_TIMEOUT_MANAGER_RESET_THRESHOLD = 2;
239
187
  const DEVICE_SCAN_TIMEOUT_MS = 3000;
@@ -494,23 +442,11 @@ const resolveNegotiatedMtu = (
494
442
  type IOBleErrorRemap = Error | BleError | null | undefined;
495
443
 
496
444
  function remapError(error: IOBleErrorRemap) {
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
- }
445
+ if (isNativeBleDisconnectError(error)) {
446
+ throw toBleDisconnectHardwareError(error);
507
447
  }
508
448
 
509
- if (
510
- error instanceof Error &&
511
- error.message &&
512
- (error.message.includes('was disconnected') || error.message.includes('not found'))
513
- ) {
449
+ if (error instanceof Error && error.message?.includes('not found')) {
514
450
  throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
515
451
  }
516
452
 
@@ -579,22 +515,6 @@ export default class ReactNativeBleTransport {
579
515
  /** Android endpoints whose cached GATT table is suspect; the next connect refreshes it. */
580
516
  private androidGattCacheRefreshes = new Set<string>();
581
517
 
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
-
598
518
  private protocolV2Assemblers: Map<string, ProtocolV2FrameAssembler> = new Map();
599
519
 
600
520
  private protocolV2FrameQueues: Map<string, Uint8Array[]> = new Map();
@@ -656,11 +576,6 @@ export default class ReactNativeBleTransport {
656
576
  init(logger: any, emitter: EventEmitter) {
657
577
  setBleLogger(logger);
658
578
  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
- }
664
579
  }
665
580
 
666
581
  configure(signedData: any) {
@@ -908,7 +823,6 @@ export default class ReactNativeBleTransport {
908
823
  const scanStartedAt = Date.now();
909
824
  let firstDeviceMs: number | undefined;
910
825
  const blePlxManager = await this.getPlxManager();
911
- await subscribeBleOn(blePlxManager);
912
826
  if (Platform.OS === 'android' && Platform.Version >= 31) {
913
827
  Log?.debug('requesting permissions, please wait...');
914
828
 
@@ -925,6 +839,7 @@ export default class ReactNativeBleTransport {
925
839
  throw ERRORS.TypedError(HardwareErrorCode.BlePermissionError);
926
840
  }
927
841
  }
842
+ await subscribeBleOn(blePlxManager);
928
843
 
929
844
  if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
930
845
  return new Promise<IOneKeyDevice[]>((resolve, reject) => {
@@ -967,14 +882,12 @@ export default class ReactNativeBleTransport {
967
882
  (error, device) => {
968
883
  if (error) {
969
884
  Log?.debug('ble scan error: ', error);
970
- if (
971
- [BleErrorCode.BluetoothPoweredOff, BleErrorCode.BluetoothInUnknownState].includes(
972
- error.errorCode
973
- )
974
- ) {
975
- finishScan(ERRORS.TypedError(HardwareErrorCode.BlePermissionError));
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));
976
889
  } else if (error.errorCode === BleErrorCode.BluetoothUnauthorized) {
977
- finishScan(ERRORS.TypedError(HardwareErrorCode.BleLocationError));
890
+ finishScan(ERRORS.TypedError(HardwareErrorCode.BlePermissionError));
978
891
  } else if (error.errorCode === BleErrorCode.LocationServicesDisabled) {
979
892
  finishScan(ERRORS.TypedError(HardwareErrorCode.BleLocationServicesDisabled));
980
893
  } else if (error.errorCode === BleErrorCode.ScanStartFailed) {
@@ -1112,23 +1025,12 @@ export default class ReactNativeBleTransport {
1112
1025
  throw ERRORS.TypedError(HardwareErrorCode.BleRequiredUUID);
1113
1026
  }
1114
1027
 
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
- });
1028
+ return this.runLifecycleOperation(uuid, () => this.acquireUnlocked(input));
1122
1029
  }
1123
1030
 
1124
1031
  private async acquireUnlocked(input: FirmwareInstallBleAcquireInput) {
1125
1032
  if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1126
1033
  const { uuid, forceCleanRunPromise, expectedProtocol, skipProtocolProbe } = input;
1127
- this.iosPeerTermination.attemptStarted(uuid);
1128
- const shouldMapProtocolV2StaleBond = expectedProtocol
1129
- ? expectedProtocol === 'V2'
1130
- : this.confirmedProtocolV2.has(uuid);
1131
-
1132
1034
  const cachedTransport = transportCache[uuid];
1133
1035
  if (skipProtocolProbe && !cachedTransport && this.blePlxManager) {
1134
1036
  Log?.debug(
@@ -1199,8 +1101,6 @@ export default class ReactNativeBleTransport {
1199
1101
 
1200
1102
  let device: Device | null = null;
1201
1103
  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;
1204
1104
  // A firmware-install reconnect always refreshes: the new firmware may expose a different table.
1205
1105
  const refreshAndroidGattCache =
1206
1106
  isAndroid && (!!skipProtocolProbe || this.androidGattCacheRefreshes.has(uuid));
@@ -1232,19 +1132,11 @@ export default class ReactNativeBleTransport {
1232
1132
 
1233
1133
  if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1234
1134
  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);
1240
1135
  // Initiate bonding locally before GATT can trigger peripheral-initiated pairing.
1241
1136
  try {
1242
1137
  const bondState = await pairDevice(uuid);
1243
- androidBondedBeforeConnect = !bondState.bonding && bondState.bonded;
1244
1138
  if (bondState.bonding) {
1245
- await onDeviceBondState(uuid, this.bondAbortController.signal, {
1246
- systemInitiated: bondState.initiated === false,
1247
- });
1139
+ await onDeviceBondState(uuid, this.bondAbortController.signal);
1248
1140
  } else if (!bondState.bonded) {
1249
1141
  throw ERRORS.TypedError(HardwareErrorCode.BleDeviceNotBonded, 'device is not bonded');
1250
1142
  }
@@ -1256,7 +1148,6 @@ export default class ReactNativeBleTransport {
1256
1148
  });
1257
1149
  throw error;
1258
1150
  }
1259
- this.androidLinkStartedAt.set(uuid, Date.now());
1260
1151
  }
1261
1152
  if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1262
1153
 
@@ -1440,17 +1331,7 @@ export default class ReactNativeBleTransport {
1440
1331
  this.deviceProtocolHints.set(uuid, protocolHint);
1441
1332
  }
1442
1333
 
1443
- if (shouldMapProtocolV2StaleBond) {
1444
- this.acquiringProtocolV2.add(uuid);
1445
- }
1446
-
1447
- let linkEncryption: AndroidLinkEncryption | undefined;
1448
1334
  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
- }
1454
1335
  await this.installTransportForAcquire(uuid, acquiredDevice, {
1455
1336
  writeCharacteristic,
1456
1337
  notifyCharacteristic,
@@ -1497,25 +1378,17 @@ export default class ReactNativeBleTransport {
1497
1378
  }
1498
1379
  );
1499
1380
  if (this.stopped) throw ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
1500
- this.iosPeerTermination.linkProven(uuid);
1501
1381
  const currentTransport = transportCache[uuid];
1502
1382
  if (!currentTransport) {
1503
1383
  throw ERRORS.TypedError(HardwareErrorCode.TransportNotFound);
1504
1384
  }
1505
1385
  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
- }
1511
1386
  return { uuid, protocolType };
1512
1387
  } catch (error) {
1513
1388
  // A failed acquire must retire the physical link before Core retries. Logical
1514
1389
  // release leaves GATT connected even when neither protocol receives a response.
1515
1390
  await this.disconnectUnlocked(uuid);
1516
1391
  throw error;
1517
- } finally {
1518
- this.acquiringProtocolV2.delete(uuid);
1519
1392
  }
1520
1393
  }
1521
1394
 
@@ -1530,7 +1403,6 @@ export default class ReactNativeBleTransport {
1530
1403
  const subscription = characteristic.monitor((error, c) => {
1531
1404
  const isCurrentMonitor = this.monitorTokens.get(uuid) === monitorToken;
1532
1405
  if (error) {
1533
- if (isCurrentMonitor) this.noteIosLinkError(uuid, 'notify', error);
1534
1406
  Log?.debug(
1535
1407
  `error monitor ${characteristic.uuid}, deviceId: ${characteristic.deviceID}: ${
1536
1408
  error as unknown as string
@@ -1544,13 +1416,6 @@ export default class ReactNativeBleTransport {
1544
1416
  Log?.debug('monitor error ignored for stale transport: ', uuid, notifyTransactionId);
1545
1417
  return;
1546
1418
  }
1547
- if (
1548
- (this.getActiveProtocol(uuid) === 'V2' || this.acquiringProtocolV2.has(uuid)) &&
1549
- isNativeBleStaleBondError(error)
1550
- ) {
1551
- this.rememberStaleBondError(uuid, toBleStaleBondHardwareError(error));
1552
- return;
1553
- }
1554
1419
  if (Platform.OS === 'android' && isStaleGattTableNotifyReason(error.reason)) {
1555
1420
  this.androidGattCacheRefreshes.add(uuid);
1556
1421
  }
@@ -1710,8 +1575,6 @@ export default class ReactNativeBleTransport {
1710
1575
 
1711
1576
  this.deviceProtocol.delete(uuid);
1712
1577
  this.probingProtocols.delete(uuid);
1713
- this.staleBondErrors.delete(uuid);
1714
- this.acquiringProtocolV2.delete(uuid);
1715
1578
  // Confirmed protocol and caller hints stay in deviceProtocol / protocolHint.
1716
1579
  this.protocolV2Assemblers.get(uuid)?.reset();
1717
1580
  this.protocolV2Assemblers.delete(uuid);
@@ -1782,122 +1645,9 @@ export default class ReactNativeBleTransport {
1782
1645
  throw ERRORS.TypedError(HardwareErrorCode.TransportCallInProgress);
1783
1646
  }
1784
1647
 
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;
1648
+ return protocol === 'V2'
1649
+ ? this.callProtocolV2(uuid, name, data, options)
1650
+ : this.callProtocolV1(uuid, name, data, options);
1901
1651
  }
1902
1652
 
1903
1653
  private async callProtocolV1(
@@ -2165,10 +1915,6 @@ export default class ReactNativeBleTransport {
2165
1915
  this.androidPriorityResetTimers.forEach(timeout => clearTimeout(timeout));
2166
1916
  this.androidPriorityResetTimers.clear();
2167
1917
  this.androidHighPriorityDevices.clear();
2168
- this.androidLinkStartedAt.clear();
2169
- this.iosPeerTermination.reset();
2170
- stopBleKeyMissingTracking();
2171
- stopBleEncryptionTracking();
2172
1918
  const error = ERRORS.TypedError(HardwareErrorCode.BleDeviceDisconnected);
2173
1919
  this.runPromise?.reject(error);
2174
1920
  this.runPromise = null;
@@ -2242,7 +1988,6 @@ export default class ReactNativeBleTransport {
2242
1988
  }
2243
1989
  this.deviceProtocol.delete(session);
2244
1990
  this.probingProtocols.delete(session);
2245
- this.staleBondErrors.delete(session);
2246
1991
  this.deviceProtocolHints.delete(session);
2247
1992
  this.sessionProtocols.delete(session);
2248
1993
  this.protocolReprobeFailures.delete(session);
@@ -2484,7 +2229,6 @@ export default class ReactNativeBleTransport {
2484
2229
  }),
2485
2230
  ]);
2486
2231
  succeeded = true;
2487
- this.iosPeerTermination.linkStarted(uuid);
2488
2232
  return result;
2489
2233
  } catch (error) {
2490
2234
  if (timedOut || isNativeOperationTimeoutError(error)) {
@@ -2538,11 +2282,6 @@ export default class ReactNativeBleTransport {
2538
2282
  succeeded = true;
2539
2283
  return result;
2540
2284
  } 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
- }
2546
2285
  if (timedOut || isNativeOperationTimeoutError(error)) {
2547
2286
  const resetManager = this.abandonStalledConnection(
2548
2287
  uuid,
@@ -2552,6 +2291,9 @@ export default class ReactNativeBleTransport {
2552
2291
  throw this.createWedgedBleSetupError();
2553
2292
  }
2554
2293
  }
2294
+ if (isNativeBleDisconnectError(error)) {
2295
+ throw toBleDisconnectHardwareError(error);
2296
+ }
2555
2297
  if (Platform.OS === 'android' && isMissingGattShapeError(error)) {
2556
2298
  this.androidGattCacheRefreshes.add(uuid);
2557
2299
  }
@@ -2599,8 +2341,6 @@ export default class ReactNativeBleTransport {
2599
2341
  }
2600
2342
  this.deviceProtocol.delete(uuid);
2601
2343
  this.probingProtocols.delete(uuid);
2602
- this.staleBondErrors.delete(uuid);
2603
- this.acquiringProtocolV2.delete(uuid);
2604
2344
  this.protocolV2Assemblers.delete(uuid);
2605
2345
  this.resetProtocolV2Frames(uuid);
2606
2346
 
@@ -2660,7 +2400,6 @@ export default class ReactNativeBleTransport {
2660
2400
  ]);
2661
2401
  this.writeTimeoutCounts.delete(uuid);
2662
2402
  } catch (error) {
2663
- this.noteIosLinkError(uuid, 'write', error);
2664
2403
  if (timedOut) {
2665
2404
  // A superseded call's late write must not tear down the link the current
2666
2405
  // call is using; only the owner of the transport may declare it dead.
@@ -2698,8 +2437,6 @@ export default class ReactNativeBleTransport {
2698
2437
  }
2699
2438
  this.deviceProtocol.delete(uuid);
2700
2439
  this.probingProtocols.delete(uuid);
2701
- this.staleBondErrors.delete(uuid);
2702
- this.acquiringProtocolV2.delete(uuid);
2703
2440
  this.protocolV2Assemblers.delete(uuid);
2704
2441
  this.resetProtocolV2Frames(uuid);
2705
2442
 
@@ -2751,8 +2488,6 @@ export default class ReactNativeBleTransport {
2751
2488
  });
2752
2489
  this.deviceProtocol.clear();
2753
2490
  this.probingProtocols.clear();
2754
- this.staleBondErrors.clear();
2755
- this.acquiringProtocolV2.clear();
2756
2491
  this.sessionProtocols.clear();
2757
2492
  // Keep transport-lifetime V2 proof so the same endpoint can finish a no-probe
2758
2493
  // firmware reconnect after the native BLE manager is recreated.
@@ -2835,10 +2570,6 @@ export default class ReactNativeBleTransport {
2835
2570
  return 'V1';
2836
2571
  }
2837
2572
 
2838
- if (expectedProtocol === 'V2' || this.acquiringProtocolV2.has(uuid)) {
2839
- this.throwIfStaleBondError(uuid);
2840
- }
2841
-
2842
2573
  if (expectedProtocol === 'V2') {
2843
2574
  if (await this.probeProtocolV2(uuid)) {
2844
2575
  this.deviceProtocol.set(uuid, 'V2');
@@ -3027,7 +2758,6 @@ export default class ReactNativeBleTransport {
3027
2758
 
3028
2759
  this.probingProtocols.set(uuid, 'V2');
3029
2760
  this.protocolV2Assemblers.get(uuid)?.reset();
3030
- this.throwIfStaleBondError(uuid);
3031
2761
  const detected = await probeProtocolV2Helper({
3032
2762
  call: (name: string, data: Record<string, unknown>, options?: TransportCallOptions) =>
3033
2763
  this.callProtocolV2(uuid, name, data, options),
@@ -3107,21 +2837,6 @@ export default class ReactNativeBleTransport {
3107
2837
  }
3108
2838
  }
3109
2839
 
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
-
3125
2840
  private async readProtocolV2Frame(uuid: string) {
3126
2841
  const queuedFrame = this.getProtocolV2FrameQueue(uuid).shift();
3127
2842
  if (queuedFrame) {
@@ -3180,11 +2895,6 @@ export default class ReactNativeBleTransport {
3180
2895
  assertCurrentGeneration();
3181
2896
  return;
3182
2897
  } catch (error) {
3183
- if (isNativeBleStaleBondError(error) || isBleStaleBondHardwareError(error)) {
3184
- const bondError = toBleStaleBondHardwareError(error);
3185
- this.rememberStaleBondError(uuid, bondError);
3186
- throw bondError;
3187
- }
3188
2898
  if (isNativeBleDisconnectError(error)) {
3189
2899
  throw toBleDisconnectHardwareError(error);
3190
2900
  }
@@ -4,23 +4,42 @@ import timer from './utils/timer';
4
4
 
5
5
  import type { BlePlxManager } from './types';
6
6
 
7
- export const subscribeBleOn = (bleManager: BlePlxManager, ms = 1000): Promise<void> =>
7
+ export const subscribeBleOn = (bleManager: BlePlxManager, ms = 2000): 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
+ };
10
22
 
11
23
  const subscription = bleManager.onStateChange(state => {
12
24
  if (state === 'PoweredOn') {
13
- if (done) return;
14
- clearTimeout();
15
- done = true;
16
- subscription.remove();
17
- resolve();
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;
18
34
  }
19
35
  }, true);
36
+ removeSubscription = () => subscription.remove();
20
37
 
21
- const clearTimeout = timer.timeout(() => {
22
- if (done) return;
23
- subscription.remove();
24
- reject(ERRORS.TypedError(HardwareErrorCode.BlePermissionError));
25
- }, ms);
38
+ if (done) {
39
+ removeSubscription();
40
+ } else {
41
+ cancelTimeout = timer.timeout(() => {
42
+ finish(pendingError ?? ERRORS.TypedError(HardwareErrorCode.BleScanError));
43
+ }, ms);
44
+ }
26
45
  });
@@ -1,17 +0,0 @@
1
- export declare const HCI_PIN_OR_KEY_MISSING = 6;
2
- export type AndroidLinkEncryption = 'encrypted' | 'already-encrypted' | 're-paired' | 'unresolved';
3
- export declare const isBleEncryptionTrackingSupported: () => boolean;
4
- export declare const startBleEncryptionTracking: () => boolean;
5
- export declare const stopBleEncryptionTracking: () => void;
6
- export declare const markBleLinkEncrypted: (deviceId: string) => void;
7
- export type WaitForAndroidLinkEncryptionOptions = {
8
- deviceId: string;
9
- linkStartedAt: number;
10
- resultTimeoutMs: number;
11
- repairTimeoutMs: number;
12
- keyMissingGraceMs: number;
13
- signal?: AbortSignal;
14
- onRepairStarted?: () => void;
15
- };
16
- export declare const waitForAndroidLinkEncryption: ({ deviceId, linkStartedAt, resultTimeoutMs, repairTimeoutMs, keyMissingGraceMs, signal, onRepairStarted, }: WaitForAndroidLinkEncryptionOptions) => Promise<AndroidLinkEncryption>;
17
- //# sourceMappingURL=bleEncryption.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"bleEncryption.d.ts","sourceRoot":"","sources":["../src/bleEncryption.ts"],"names":[],"mappings":"AAsBA,eAAO,MAAM,sBAAsB,IAAO,CAAC;AAE3C,MAAM,MAAM,qBAAqB,GAE7B,WAAW,GAEX,mBAAmB,GAEnB,WAAW,GAEX,YAAY,CAAC;AA0CjB,eAAO,MAAM,gCAAgC,eAA2C,CAAC;AAGzF,eAAO,MAAM,0BAA0B,QAAO,OAwB7C,CAAC;AAEF,eAAO,MAAM,yBAAyB,YAMrC,CAAC;AAMF,eAAO,MAAM,oBAAoB,aAAc,MAAM,SAGpD,CAAC;AAEF,MAAM,MAAM,mCAAmC,GAAG;IAChD,QAAQ,EAAE,MAAM,CAAC;IAEjB,aAAa,EAAE,MAAM,CAAC;IAEtB,eAAe,EAAE,MAAM,CAAC;IAExB,eAAe,EAAE,MAAM,CAAC;IAExB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,eAAe,CAAC,EAAE,MAAM,IAAI,CAAC;CAC9B,CAAC;AAOF,eAAO,MAAM,4BAA4B,+GAQtC,mCAAmC,KAAG,QAAQ,qBAAqB,CAuHrE,CAAC"}
@@ -1,16 +0,0 @@
1
- export declare const IOS_PEER_TERMINATION_LINK_WINDOW_MS = 10000;
2
- export declare const IOS_PEER_TERMINATION_REPEAT_WINDOW_MS = 60000;
3
- export declare const isIosPeerTerminationError: (error: unknown) => boolean;
4
- export declare class IosPeerTerminationTracker {
5
- private linkStartedAt;
6
- private terminatedAt;
7
- private evidenceAt;
8
- attemptStarted(deviceId: string): void;
9
- linkStarted(deviceId: string): void;
10
- note(deviceId: string, error: unknown): void;
11
- linkProven(deviceId: string): void;
12
- forget(deviceId: string): void;
13
- attemptFailed(deviceId: string): boolean;
14
- reset(): void;
15
- }
16
- //# sourceMappingURL=bleIosStaleBond.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"bleIosStaleBond.d.ts","sourceRoot":"","sources":["../src/bleIosStaleBond.ts"],"names":[],"mappings":"AAiBA,eAAO,MAAM,mCAAmC,QAAS,CAAC;AAE1D,eAAO,MAAM,qCAAqC,QAAS,CAAC;AAE5D,eAAO,MAAM,yBAAyB,UAAW,OAAO,KAAG,OAE9B,CAAC;AAE9B,qBAAa,yBAAyB;IAEpC,OAAO,CAAC,aAAa,CAA6B;IAGlD,OAAO,CAAC,YAAY,CAA6B;IAGjD,OAAO,CAAC,UAAU,CAA6B;IAE/C,cAAc,CAAC,QAAQ,EAAE,MAAM;IAK/B,WAAW,CAAC,QAAQ,EAAE,MAAM;IAM5B,IAAI,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO;IAMrC,UAAU,CAAC,QAAQ,EAAE,MAAM;IAI3B,MAAM,CAAC,QAAQ,EAAE,MAAM;IAOvB,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO;IAuBxC,KAAK;CAKN"}
@@ -1,7 +0,0 @@
1
- export declare const isBleKeyMissingSupported: () => boolean;
2
- export declare const startBleKeyMissingTracking: () => boolean;
3
- export declare const stopBleKeyMissingTracking: () => void;
4
- export declare const hasBleKeyMissingSince: (deviceId: string, sinceMs: number) => boolean;
5
- export declare const onBleKeyMissing: (deviceId: string, callback: () => void) => (() => void);
6
- export declare const waitForBleKeyMissing: (deviceId: string, sinceMs: number, timeoutMs: number) => Promise<boolean>;
7
- //# sourceMappingURL=bleKeyMissing.d.ts.map