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

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